@qwen-code/qwen-code 0.25.4-preview.0 → 0.25.4-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/bundled/browser-use/runtime/native-host.js +0 -0
  2. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +0 -0
  3. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +0 -0
  4. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +0 -0
  5. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +0 -0
  6. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +0 -0
  7. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +0 -0
  8. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +0 -0
  9. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +0 -0
  10. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +0 -0
  11. package/bundled/browser-use/runtime/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +0 -0
  12. package/bundled/browser-use/runtime/node_modules/playwright-core/cli.js +0 -0
  13. package/bundled/browser-use/runtime/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
  14. package/bundled/browser-use/runtime/node_modules/playwright-core/lib/xdg-open +0 -0
  15. package/bundled/browser-use/runtime/scripts/native-host-setup.js +0 -0
  16. package/chunks/{MaxSizedBox-M27H235V.js → MaxSizedBox-E4RKSA7W.js} +1 -1
  17. package/chunks/{StandaloneSessionPicker-LWWDDYOW.js → StandaloneSessionPicker-2D3UKLVS.js} +1 -1
  18. package/chunks/{acp-subagent-executor-NUV52JVS.js → acp-subagent-executor-UQYUN6AB.js} +1 -1
  19. package/chunks/{acpAgent-IUJDXLZM.js → acpAgent-P7WGK2BP.js} +3 -3
  20. package/chunks/{advisor-MSOUBMJ6.js → advisor-GCH2MBXT.js} +1 -1
  21. package/chunks/{agent-H7XIWYWQ.js → agent-57T4YAYP.js} +1 -1
  22. package/chunks/{agent-headless-XDN3D3S3.js → agent-headless-IBON3A7N.js} +1 -1
  23. package/chunks/{agent-host-client-AZP3PZXS.js → agent-host-client-LE7P72FR.js} +1 -1
  24. package/chunks/{agent-host-connections-JRVX7I6I.js → agent-host-connections-4DM57L26.js} +1 -1
  25. package/chunks/{anthropicContentGenerator-N7TV53LD.js → anthropicContentGenerator-C4TPFXUK.js} +1 -1
  26. package/chunks/{batch-MKSJFJUH.js → batch-YJJGMJWO.js} +1 -1
  27. package/chunks/{bridge-GNMKKHQ4.js → bridge-FIO2ENBG.js} +1 -1
  28. package/chunks/{channel-settings-store-Y4YCS7JX.js → channel-settings-store-TEBCLK2B.js} +1 -1
  29. package/chunks/{chunk-GPOUP5OK.js → chunk-27MTSS3T.js} +1 -1
  30. package/chunks/{chunk-C4ANA47H.js → chunk-2MGCRPM3.js} +1 -1
  31. package/chunks/{chunk-6DQNNRRC.js → chunk-2WBKWPSO.js} +1 -1
  32. package/chunks/{chunk-CATL2PQS.js → chunk-34WLYVDK.js} +5 -5
  33. package/chunks/{chunk-B7CXPNCV.js → chunk-3J2YNEHG.js} +1 -1
  34. package/chunks/{chunk-VTNHPXNL.js → chunk-3TBFTELA.js} +1 -1
  35. package/chunks/{chunk-7JT34VGK.js → chunk-46I6JBVL.js} +1 -1
  36. package/chunks/{chunk-FEMWELCV.js → chunk-4ZKFLOEH.js} +1 -1
  37. package/chunks/{chunk-7AYXAVTZ.js → chunk-5DUJIOOX.js} +3 -3
  38. package/chunks/{chunk-6QLHJSVW.js → chunk-6PWOLWTH.js} +1 -1
  39. package/chunks/{chunk-OW4QBRSR.js → chunk-6UZ65Z2P.js} +1 -1
  40. package/chunks/{chunk-V2JZO5MS.js → chunk-7DSJE3CL.js} +1 -1
  41. package/chunks/{chunk-TJMHIEYI.js → chunk-7LCY7GGX.js} +1 -1
  42. package/chunks/{chunk-TLJHBK3A.js → chunk-7RNTXEWH.js} +1 -1
  43. package/chunks/{chunk-YZ7OO4AQ.js → chunk-A3IF6IOB.js} +1 -1
  44. package/chunks/{chunk-VTF6AVZB.js → chunk-A6OQSOUO.js} +1 -1
  45. package/chunks/{chunk-Y7YDHCON.js → chunk-AJ6JUUP7.js} +1 -1
  46. package/chunks/{chunk-QTMHQGWQ.js → chunk-AOMEBVFW.js} +1 -1
  47. package/chunks/{chunk-KVTG2ZNH.js → chunk-AUNAS7AS.js} +1 -1
  48. package/chunks/{chunk-BOFD4CN3.js → chunk-AVIDPC5K.js} +1 -1
  49. package/chunks/{chunk-ETYTRKB2.js → chunk-BOLPBPWC.js} +1 -1
  50. package/chunks/{chunk-OAPA66DR.js → chunk-BQQBFDBY.js} +1 -1
  51. package/chunks/{chunk-NOS2CNOI.js → chunk-CN22ATWU.js} +1 -1
  52. package/chunks/{chunk-XYBEQRSZ.js → chunk-DIHJELGW.js} +1 -1
  53. package/chunks/{chunk-XCEL3EDX.js → chunk-DJFCI7TU.js} +1 -1
  54. package/chunks/{chunk-VKEL2XTM.js → chunk-DQPDMFS3.js} +1 -1
  55. package/chunks/{chunk-DJRFEZBY.js → chunk-DSYKB77N.js} +1 -1
  56. package/chunks/{chunk-UEW7Q26E.js → chunk-EDNOGHMN.js} +2 -2
  57. package/chunks/{chunk-RXNGYG64.js → chunk-EE36D2EV.js} +1 -1
  58. package/chunks/{chunk-NZKX7HYL.js → chunk-EGQDN3FJ.js} +1 -1
  59. package/chunks/{chunk-DFRSQK5Q.js → chunk-FHFBCG6N.js} +1 -1
  60. package/chunks/{chunk-PECV2VVZ.js → chunk-GI6T3RBV.js} +1 -1
  61. package/chunks/{chunk-37BNHIUB.js → chunk-GOLT5JXA.js} +1 -1
  62. package/chunks/{chunk-KITFF4GL.js → chunk-IDGXHMNL.js} +1 -1
  63. package/chunks/{chunk-6HIOSLUM.js → chunk-IIZWK7ZP.js} +1 -1
  64. package/chunks/{chunk-MPGEAX4K.js → chunk-IJC6ZH2S.js} +1 -1
  65. package/chunks/{chunk-TLYJVB5H.js → chunk-IO6LSEPV.js} +1 -1
  66. package/chunks/{chunk-QIJKEZZR.js → chunk-IYVNCBMS.js} +1 -1
  67. package/chunks/{chunk-S4GOHFRN.js → chunk-JHGOWK7M.js} +1 -1
  68. package/chunks/{chunk-GHRD2MMC.js → chunk-JRJY343T.js} +1 -1
  69. package/chunks/{chunk-WCYZSCG7.js → chunk-JVUXQU3W.js} +1 -1
  70. package/chunks/{chunk-DMCTJUIJ.js → chunk-K2K2YYWO.js} +1 -1
  71. package/chunks/{chunk-37OHWQHB.js → chunk-KF6HU732.js} +2 -2
  72. package/chunks/{chunk-5LSV73BG.js → chunk-KVWUOBH7.js} +1 -1
  73. package/chunks/{chunk-7V4BAHFT.js → chunk-LBWBGFHD.js} +1 -1
  74. package/chunks/{chunk-RKPHDO42.js → chunk-LDXZT3SG.js} +5 -5
  75. package/chunks/{chunk-BGFA2SAQ.js → chunk-LFOZ6AIH.js} +1 -1
  76. package/chunks/{chunk-4322TZID.js → chunk-LGQHT42X.js} +2 -2
  77. package/chunks/{chunk-PDXZ2CUO.js → chunk-M3O2XDHA.js} +1 -1
  78. package/chunks/{chunk-47K2NMP6.js → chunk-M3UC46LS.js} +1 -1
  79. package/chunks/{chunk-UFRY7WND.js → chunk-M7JLPTQI.js} +1 -1
  80. package/chunks/{chunk-SATEKHQP.js → chunk-MBUXP3IS.js} +1 -1
  81. package/chunks/{chunk-RN6JS263.js → chunk-MEZA3VVH.js} +1 -1
  82. package/chunks/{chunk-OBFKP7RI.js → chunk-MWN6TR36.js} +1 -1
  83. package/chunks/{chunk-VHJ43ZYJ.js → chunk-O7XRQWCG.js} +1 -1
  84. package/chunks/{chunk-H224LNV3.js → chunk-OYFRLT5E.js} +1 -1
  85. package/chunks/{chunk-3NWFV2YF.js → chunk-PMBGV76N.js} +1 -1
  86. package/chunks/{chunk-YFAPACDE.js → chunk-PVM4IVFL.js} +6 -6
  87. package/chunks/{chunk-7WS2EYMQ.js → chunk-PWHD4NK3.js} +1 -1
  88. package/chunks/{chunk-JZIQSEFO.js → chunk-Q54NROBX.js} +1 -1
  89. package/chunks/{chunk-FCLAPJ22.js → chunk-QE7R4DPT.js} +1 -1
  90. package/chunks/{chunk-J6TW7GNF.js → chunk-QIUTQICH.js} +1 -1
  91. package/chunks/{chunk-TWDCN5H2.js → chunk-QK63EULE.js} +1 -1
  92. package/chunks/{chunk-HZZT75LI.js → chunk-QTAC4W7J.js} +1 -1
  93. package/chunks/{chunk-P7DIAJNX.js → chunk-R7HBR4QQ.js} +1 -1
  94. package/chunks/{chunk-U2FJSKS3.js → chunk-RHEMFKMX.js} +1 -1
  95. package/chunks/{chunk-TRRY3QMM.js → chunk-RL57IU47.js} +1 -1
  96. package/chunks/{chunk-SPWDYRDH.js → chunk-S2OOQRLJ.js} +1 -1
  97. package/chunks/{chunk-QBRADQ7L.js → chunk-SWTMWNTZ.js} +1 -1
  98. package/chunks/{chunk-AZUDF52L.js → chunk-SXTKQHFZ.js} +1 -1
  99. package/chunks/{chunk-5RQRSPPD.js → chunk-T5S3MJIK.js} +1 -1
  100. package/chunks/{chunk-I3ORWQ2U.js → chunk-UDGDEIBB.js} +1 -1
  101. package/chunks/{chunk-EMDEBV33.js → chunk-UIFBF3E7.js} +1 -1
  102. package/chunks/{chunk-BGEMWNES.js → chunk-UQDPWI7D.js} +1 -1
  103. package/chunks/{chunk-I5LKOTZT.js → chunk-VON4MVIM.js} +1 -1
  104. package/chunks/{chunk-HJPO6MEW.js → chunk-W5D2T2JK.js} +1 -1
  105. package/chunks/{chunk-F6YYDRMH.js → chunk-WNGYYU67.js} +1 -1
  106. package/chunks/{chunk-S2GKUZZZ.js → chunk-WO3F62ZD.js} +1 -1
  107. package/chunks/{chunk-K7KW3ZJQ.js → chunk-WVY5Q6YY.js} +1 -1
  108. package/chunks/{chunk-GH6DPLWU.js → chunk-Y4Q667BW.js} +1 -1
  109. package/chunks/{chunk-FH74N7Y7.js → chunk-YJLMFUCS.js} +2 -2
  110. package/chunks/{chunk-C3Y2S5AM.js → chunk-YKHRCSKP.js} +1 -1
  111. package/chunks/{chunk-P4UJ7CXJ.js → chunk-YLIS36QA.js} +1 -1
  112. package/chunks/{chunk-4QIFOIBS.js → chunk-YVZ4XZRB.js} +1 -1
  113. package/chunks/{chunk-KGRD6G5J.js → chunk-Z27JJPKN.js} +1 -1
  114. package/chunks/{chunk-KOHHDB2L.js → chunk-ZCIS6MJZ.js} +1 -1
  115. package/chunks/{chunk-QNNDZYVW.js → chunk-ZHLQ222N.js} +1 -1
  116. package/chunks/{chunk-KWRZ3WJO.js → chunk-ZP7MTWMR.js} +1 -1
  117. package/chunks/{codex-subagent-executor-H44VDB5E.js → codex-subagent-executor-6OJVGF2S.js} +1 -1
  118. package/chunks/{config-utils-4X4SV4RL.js → config-utils-FI3A4QAN.js} +1 -1
  119. package/chunks/{contextCommand-4KVOHTAJ.js → contextCommand-YEBZQHG4.js} +1 -1
  120. package/chunks/{core-runtime-4RARI4NX.js → core-runtime-CFMHUAS7.js} +1 -1
  121. package/chunks/{create-sub-session-CNSRJFYG.js → create-sub-session-G26337FT.js} +1 -1
  122. package/chunks/{daemon-git-worktree-guard-6XQQPP2H.js → daemon-git-worktree-guard-ITU6NQIV.js} +1 -1
  123. package/chunks/{daemon-status-provider-PRTEQT5T.js → daemon-status-provider-CSWRGMRX.js} +1 -1
  124. package/chunks/{daemon-trust-policy-GXKJVZDU.js → daemon-trust-policy-IYD7NOGK.js} +1 -1
  125. package/chunks/{daemon-trust-policy-monitor-L2ORKHMM.js → daemon-trust-policy-monitor-OWUP5SYB.js} +1 -1
  126. package/chunks/{deferred-core-runtime-RZQFUSPX.js → deferred-core-runtime-CVCQU7O4.js} +1 -1
  127. package/chunks/{edit-W44XQCIS.js → edit-7YBQLILC.js} +1 -1
  128. package/chunks/{enterPlanMode-B456A2XO.js → enterPlanMode-L3PVSD2P.js} +1 -1
  129. package/chunks/{environment-DSGQSQFS.js → environment-BVEOYQHO.js} +1 -1
  130. package/chunks/{errors-KL725247.js → errors-VQWBGR6D.js} +1 -1
  131. package/chunks/{execution-tool-KT3EBWHG.js → execution-tool-P7CBXSGZ.js} +1 -1
  132. package/chunks/{execution-worker-LPQ4HMN4.js → execution-worker-RZXNYK4B.js} +1 -1
  133. package/chunks/{exitPlanMode-JLKS76IA.js → exitPlanMode-MBUTM3NW.js} +1 -1
  134. package/chunks/{fast-path-5UD52IHH.js → fast-path-T2FDUSHV.js} +1 -1
  135. package/chunks/{glob-LYA2H6X3.js → glob-RH7XXSYE.js} +1 -1
  136. package/chunks/{goal-tools-SHSIDLZX.js → goal-tools-K6XBCE5E.js} +1 -1
  137. package/chunks/{handleAutoUpdate-T4RE6CZN.js → handleAutoUpdate-PG7R3KPH.js} +1 -1
  138. package/chunks/{i18n-5DK327WA.js → i18n-EGTBMA3N.js} +1 -1
  139. package/chunks/{initializer-TJGE4OJA.js → initializer-RIKH4PCP.js} +1 -1
  140. package/chunks/{installationInfo-MZ62GDIC.js → installationInfo-BBADHZLD.js} +1 -1
  141. package/chunks/{interactive-mod-session-YCUBQ6RM.js → interactive-mod-session-7RDKAHZ4.js} +1 -1
  142. package/chunks/{list-4L3LYDQM.js → list-YEGWEHJX.js} +1 -1
  143. package/chunks/{llm-3JQWBZXV.js → llm-D3LHPY27.js} +4 -4
  144. package/chunks/{llm-content-generator-6UPJWPOM.js → llm-content-generator-BLTBMV66.js} +1 -1
  145. package/chunks/{loadedSettingsAdapter-STPKAFJG.js → loadedSettingsAdapter-PLGMKMFO.js} +1 -1
  146. package/chunks/{local-execution-environment-IE5BOI7Y.js → local-execution-environment-4LDKFNC4.js} +1 -1
  147. package/chunks/{loggingContentGenerator-4KKWPZJA.js → loggingContentGenerator-376R7DRI.js} +1 -1
  148. package/chunks/{manage-memory-CRV5SXZZ.js → manage-memory-2ZTIVKNU.js} +1 -1
  149. package/chunks/{managed-execution-engine-FHLEWVND.js → managed-execution-engine-5LOM3MXG.js} +1 -1
  150. package/chunks/{managed-npm-update-BRHPOKDU.js → managed-npm-update-2C5JYEXW.js} +1 -1
  151. package/chunks/{managed-runtime-attestation-worker-GIQKZ5BH.js → managed-runtime-attestation-worker-R2FECMZK.js} +1 -1
  152. package/chunks/{managed-runtime-bootstrap-P72BT46H.js → managed-runtime-bootstrap-KPLGH4UE.js} +1 -1
  153. package/chunks/{managed-runtime-session-worker-IYCJDB5K.js → managed-runtime-session-worker-EVKNPK3V.js} +1 -1
  154. package/chunks/{managed-runtime-ssh-worker-ONT4V5ZG.js → managed-runtime-ssh-worker-IA4HZ3PD.js} +1 -1
  155. package/chunks/{mcp-NXCQVE2Y.js → mcp-S67IJLI6.js} +1 -1
  156. package/chunks/{model-call-collection-3DNL45M5.js → model-call-collection-6OGPDTPG.js} +1 -1
  157. package/chunks/{model-configuration-6HRNYBWV.js → model-configuration-6RWVBOQS.js} +1 -1
  158. package/chunks/{modelConfigUtils-SKBN64ZW.js → modelConfigUtils-M3TVVYAO.js} +1 -1
  159. package/chunks/{monitor-7I7Q73UR.js → monitor-ZHOFTN7N.js} +1 -1
  160. package/chunks/{nonInteractiveCli-YLYRJUBE.js → nonInteractiveCli-6SUGPTJ4.js} +1 -1
  161. package/chunks/{nonInteractiveToolExecutor-U2ASWT63.js → nonInteractiveToolExecutor-SAHBGO3A.js} +1 -1
  162. package/chunks/{notebook-edit-WAD7IQCF.js → notebook-edit-ETUOQH6G.js} +1 -1
  163. package/chunks/{omni-POUUDVU3.js → omni-HV2UBGMZ.js} +1 -1
  164. package/chunks/{openaiContentGenerator-L7X6IVPL.js → openaiContentGenerator-RZCG7E4M.js} +1 -1
  165. package/chunks/{openaiResponsesContentGenerator-7XCMFI6P.js → openaiResponsesContentGenerator-X23L5JV3.js} +1 -1
  166. package/chunks/{pidfile-MQQT2ZDA.js → pidfile-26WXQCHG.js} +1 -1
  167. package/chunks/{processUtils-OZLF72NC.js → processUtils-WXLFGNBT.js} +1 -1
  168. package/chunks/{prompt-terminal-ledger-IYUF6SUU.js → prompt-terminal-ledger-EIZZHF4A.js} +1 -1
  169. package/chunks/{qwenContentGenerator-DKH3ILUO.js → qwenContentGenerator-GOY7Y6KH.js} +1 -1
  170. package/chunks/{reactive-degrade-KSNGHMBN.js → reactive-degrade-MNMTTHO5.js} +1 -1
  171. package/chunks/{read-file-VEELW4OQ.js → read-file-OJNGPNTQ.js} +1 -1
  172. package/chunks/{resumeHistoryUtils-4SFDTBXU.js → resumeHistoryUtils-QWOWF4VY.js} +1 -1
  173. package/chunks/{review-QA6HRLVU.js → review-5S24HP2V.js} +1 -1
  174. package/chunks/{ripGrep-4J6ASSE3.js → ripGrep-Y4PY2MQF.js} +1 -1
  175. package/chunks/{run-qwen-serve-EJ67LA5O.js → run-qwen-serve-EOUUDZUK.js} +2 -2
  176. package/chunks/{runtime-6E2FSB5U.js → runtime-ZBPOQX6E.js} +1 -1
  177. package/chunks/{sandboxConfig-4VE4LNRI.js → sandboxConfig-R7KDS3P5.js} +1 -1
  178. package/chunks/{scheduled-tasks-GM5EJMK7.js → scheduled-tasks-Q6V7D6K6.js} +1 -1
  179. package/chunks/{scheduler-HOSVIIOE.js → scheduler-EBQY6BOK.js} +1 -1
  180. package/chunks/{search-memory-HEAQCHIK.js → search-memory-HX6E23JC.js} +1 -1
  181. package/chunks/{send-message-FAQ7XEZ5.js → send-message-OZCCCH2F.js} +1 -1
  182. package/chunks/{serve-VNKPOWSW.js → serve-CMGCI4BK.js} +1 -1
  183. package/chunks/{server-U2XBJLOV.js → server-7LOAKPDN.js} +3 -3
  184. package/chunks/{session-AZGROSFX.js → session-LVQYZSJE.js} +1 -1
  185. package/chunks/{session-attachments-root-6M2ECUNK.js → session-attachments-root-NWG7JOMN.js} +1 -1
  186. package/chunks/{session-execution-engine-selector-PYDVOSJF.js → session-execution-engine-selector-PHH47ZMA.js} +1 -1
  187. package/chunks/{session-pr-refresh-3IS7DLEV.js → session-pr-refresh-5IACZPCY.js} +1 -1
  188. package/chunks/{sessionService-3FWNA4ZB.js → sessionService-7PFAWLHC.js} +1 -1
  189. package/chunks/{settings-VHKT7JJC.js → settings-CPZBOHN5.js} +1 -1
  190. package/chunks/{shell-TYOPVB7H.js → shell-A7NLPS2W.js} +1 -1
  191. package/chunks/{skill-GJQIE5AX.js → skill-VGANGVOD.js} +1 -1
  192. package/chunks/{skill-settings-76NI6SF3.js → skill-settings-TSZO3X6N.js} +1 -1
  193. package/chunks/{spawnChannel-FMSYLDKB.js → spawnChannel-2JQYNQKT.js} +1 -1
  194. package/chunks/{standalone-update-BPZQDQHD.js → standalone-update-QXC3RM6I.js} +1 -1
  195. package/chunks/{start-opentui-ui-X7XYV5N3.js → start-opentui-ui-BKJ4JHVK.js} +1 -1
  196. package/chunks/{startInteractiveUI-UZDF4JUB.js → startInteractiveUI-4QIPR7ZY.js} +1 -1
  197. package/chunks/{team-create-RFZNEF76.js → team-create-5MU6BGXX.js} +1 -1
  198. package/chunks/{team-plan-approval-MGW3JGSC.js → team-plan-approval-NZUJ6FSA.js} +1 -1
  199. package/chunks/{terminal-image-renderer-3UED5GZV.js → terminal-image-renderer-CTMJULJ2.js} +1 -1
  200. package/chunks/{theme-manager-SF6FSSZW.js → theme-manager-6H7GA6QR.js} +1 -1
  201. package/chunks/{tool-call-W2CJR74U.js → tool-call-XG4CAD5X.js} +1 -1
  202. package/chunks/{tool-result-media-XSFON2ZQ.js → tool-result-media-RJ5ONO7R.js} +1 -1
  203. package/chunks/{tool-search-7GY5YTOU.js → tool-search-KBINGEWV.js} +1 -1
  204. package/chunks/{total-session-admission-OATGW6M5.js → total-session-admission-XNWYCO7G.js} +1 -1
  205. package/chunks/{trustedFolders-AM4PSGUB.js → trustedFolders-JT5MOB3A.js} +1 -1
  206. package/chunks/{update-relaunch-YKY52XUT.js → update-relaunch-HXMQI3HO.js} +1 -1
  207. package/chunks/{updateCheck-RKQ5CPZM.js → updateCheck-XWE3TWL5.js} +1 -1
  208. package/chunks/{upload-config-CBT7ARZY.js → upload-config-ET7NRHU7.js} +1 -1
  209. package/chunks/{useAutoAcceptIndicator-Z3YWPUNO.js → useAutoAcceptIndicator-TPMYKNJX.js} +1 -1
  210. package/chunks/{validateNonInterActiveAuth-7CQHU2RF.js → validateNonInterActiveAuth-U52KMEDS.js} +1 -1
  211. package/chunks/{version-N2OB6KWP.js → version-CW4RTJ3H.js} +1 -1
  212. package/chunks/{web-fetch-L5XCBCBA.js → web-fetch-UPMJ3XIZ.js} +1 -1
  213. package/chunks/{web-search-4EHUA3LJ.js → web-search-PXABWQVC.js} +1 -1
  214. package/chunks/{workflow-FGAUAYIP.js → workflow-UQ4V3NBZ.js} +1 -1
  215. package/chunks/{workflow-ancestor-trust-F7RRN6I3.js → workflow-ancestor-trust-QII5KTUJ.js} +1 -1
  216. package/chunks/{workspace-agents-QW4TKC52.js → workspace-agents-Q3KKMDX2.js} +1 -1
  217. package/chunks/{workspace-providers-status-MFSZT3YA.js → workspace-providers-status-3ASB64FB.js} +1 -1
  218. package/chunks/{workspace-registration-store-WQRDSIEI.js → workspace-registration-store-2NPD6U3B.js} +1 -1
  219. package/chunks/{workspace-registry-FXZFRSCH.js → workspace-registry-6QJKRCDR.js} +1 -1
  220. package/chunks/{workspace-runtime-coordinator-LJ5YAT3A.js → workspace-runtime-coordinator-ZXUWDQIB.js} +1 -1
  221. package/chunks/{workspace-service-U632SUWU.js → workspace-service-YPYTYYUN.js} +1 -1
  222. package/chunks/{workspace-skills-status-M7YXM3LF.js → workspace-skills-status-VTFHQ6R7.js} +1 -1
  223. package/chunks/{workspace-trust-reconciler-NLJGGI4K.js → workspace-trust-reconciler-52CZVPKH.js} +1 -1
  224. package/chunks/{write-file-BJCKSXX7.js → write-file-FDBR76G5.js} +1 -1
  225. package/chunks/{zoom-image-TLJPD4DB.js → zoom-image-MYKWCCXO.js} +1 -1
  226. package/cli.js +2 -2
  227. package/execution-worker.js +1 -1
  228. package/export-transcript-document.js +1 -1
  229. package/package.json +4 -4
  230. package/vendor/landlock-run/arm64-linux/qwen-landlock-run +0 -0
  231. package/vendor/landlock-run/x64-linux/qwen-landlock-run +0 -0
  232. package/vendor/ripgrep/arm64-darwin/rg +0 -0
  233. package/vendor/ripgrep/arm64-linux/rg +0 -0
  234. package/vendor/ripgrep/x64-darwin/rg +0 -0
  235. package/vendor/ripgrep/x64-linux/rg +0 -0
  236. package/vendor/tree-sitter/tree-sitter-bash.wasm +0 -0
  237. package/vendor/tree-sitter/tree-sitter.wasm +0 -0
  238. package/web-shell/assets/{PierreFilePreview-D9tbdFw8.js → PierreFilePreview-DGTp45Z4.js} +1 -1
  239. package/web-shell/assets/{SpreadsheetPreview-CeFAk2s-.js → SpreadsheetPreview-DVC_YVei.js} +1 -1
  240. package/web-shell/assets/{WorkspaceFileBrowser-iaURw8SR.js → WorkspaceFileBrowser-DaQNpS06.js} +1 -1
  241. package/web-shell/assets/{abnfDiagram-VCTEODGH-Z4CT1NCF.js → abnfDiagram-VCTEODGH-wJbiOoPK.js} +1 -1
  242. package/web-shell/assets/{agents-route-B7o2Rq-a.js → agents-route-DUhhA1KI.js} +1 -1
  243. package/web-shell/assets/{arc-DcHBdUJQ.js → arc-CvpNMy1d.js} +1 -1
  244. package/web-shell/assets/{architectureDiagram-5GKGNRK7-DRDhEC81.js → architectureDiagram-5GKGNRK7-DIhi3dIz.js} +1 -1
  245. package/web-shell/assets/{blockDiagram-NRAW4CY4-CYRE6WIc.js → blockDiagram-NRAW4CY4-CoeyTlVJ.js} +1 -1
  246. package/web-shell/assets/{c4Diagram-UCG6FXSJ-CIM8N_Sj.js → c4Diagram-UCG6FXSJ-BYoK_I9M.js} +1 -1
  247. package/web-shell/assets/channel-DvtGOCg6.js +1 -0
  248. package/web-shell/assets/{chunk-2Q5K7J3B-Bbfka9Fe.js → chunk-2Q5K7J3B-BeD4GwPg.js} +1 -1
  249. package/web-shell/assets/{chunk-5VM5RSS4-C02zF3RY.js → chunk-5VM5RSS4-BpkJsB_y.js} +1 -1
  250. package/web-shell/assets/{chunk-F27PBJKO-Dn0wRD2F.js → chunk-F27PBJKO-BROEWQ1J.js} +1 -1
  251. package/web-shell/assets/{chunk-G27WJ6UU-Dwpl3l0W.js → chunk-G27WJ6UU-DA8Wtppt.js} +1 -1
  252. package/web-shell/assets/{chunk-JWPE2WC7-sQbzSoTR.js → chunk-JWPE2WC7-GqB-QFh5.js} +1 -1
  253. package/web-shell/assets/{chunk-LCL6LL3I-DNlNDtfr.js → chunk-LCL6LL3I-DIPUwYsX.js} +1 -1
  254. package/web-shell/assets/{chunk-POPQ4Y6H-BOgf1Dl3.js → chunk-POPQ4Y6H-DbnU-jxX.js} +1 -1
  255. package/web-shell/assets/{chunk-SVP7TREG-DOofWP00.js → chunk-SVP7TREG-DvH7bQ-w.js} +1 -1
  256. package/web-shell/assets/{chunk-XXDRQBXY-Bj9FxhWU.js → chunk-XXDRQBXY-DdVWVo3U.js} +1 -1
  257. package/web-shell/assets/classDiagram-DTDB5LWJ-9NR5W1rE.js +1 -0
  258. package/web-shell/assets/classDiagram-v2-JRS7N3AN-9NR5W1rE.js +1 -0
  259. package/web-shell/assets/{cose-bilkent-JH36ORCC-CUlPjyww.js → cose-bilkent-JH36ORCC-JgMKxP9H.js} +1 -1
  260. package/web-shell/assets/{cynefin-OW5HDTMX-5noArzI7.js → cynefin-OW5HDTMX-BVUpNgVm.js} +1 -1
  261. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-DELvTqmf.js → cynefinDiagram-5FMLGOSQ-CxAdk-iS.js} +1 -1
  262. package/web-shell/assets/{dagre-3AP2YEHR-CAL6Z3hL.js → dagre-3AP2YEHR-CvXWkM86.js} +1 -1
  263. package/web-shell/assets/{diagram-S7CK7UJ4-DQC2gaIi.js → diagram-S7CK7UJ4-DD_PS4nm.js} +1 -1
  264. package/web-shell/assets/{diagram-UQ7AKVKN-CkU6M-3R.js → diagram-UQ7AKVKN-EVZkTODD.js} +1 -1
  265. package/web-shell/assets/{diagram-VSXAHHWV-CvHpHwVx.js → diagram-VSXAHHWV-CGZc1pZU.js} +1 -1
  266. package/web-shell/assets/{diagram-VX7I27RA-D9l5F9iB.js → diagram-VX7I27RA-DjNql499.js} +1 -1
  267. package/web-shell/assets/{diagram-Z3DM3KII-DW-VFvYx.js → diagram-Z3DM3KII-CCa0WtmR.js} +1 -1
  268. package/web-shell/assets/{docx-preview-8MQfOGQh.js → docx-preview-DpVElxvj.js} +1 -1
  269. package/web-shell/assets/{ebnfDiagram-PWID7BFC-C0Q71wC_.js → ebnfDiagram-PWID7BFC-W2hoOJZF.js} +1 -1
  270. package/web-shell/assets/{erDiagram-SSCWMZ5O-DWDLRh1S.js → erDiagram-SSCWMZ5O-Dz5NxxEb.js} +1 -1
  271. package/web-shell/assets/{flowDiagram-A5DVABFB-CVzJnl1P.js → flowDiagram-A5DVABFB-BTMAn8b5.js} +1 -1
  272. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-B320pcgR.js → ganttDiagram-EL5Y4UJY-BaFrd5ZY.js} +1 -1
  273. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-Di4uZh-J.js → gitGraphDiagram-WWUBYQGX-IlmdUqRk.js} +1 -1
  274. package/web-shell/assets/{index-Csr8Hx_O.js → index-C2ez0ZjE.js} +1 -1
  275. package/web-shell/assets/{index-C9BecA_H.js → index-Cs-XBNmB.js} +101 -101
  276. package/web-shell/assets/{infoDiagram-RXCK75RN-CbafhxET.js → infoDiagram-RXCK75RN-BHs9kpar.js} +1 -1
  277. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-DrQuIDeR.js → ishikawaDiagram-5VMMS53U-DWCEQ85v.js} +1 -1
  278. package/web-shell/assets/{journeyDiagram-EYS64GPL-BschmjBj.js → journeyDiagram-EYS64GPL-RTDAw9yc.js} +1 -1
  279. package/web-shell/assets/{kanban-definition-3QL26DDD-B7x9BU9N.js → kanban-definition-3QL26DDD-B7Nl9bq6.js} +1 -1
  280. package/web-shell/assets/{layout-BewPaOyO.js → layout-BabjFEb1.js} +1 -1
  281. package/web-shell/assets/{linear-CnLILCVp.js → linear-CZuGjuQd.js} +1 -1
  282. package/web-shell/assets/{mermaid.core-Csj9KPfJ.js → mermaid.core-CK78bIGt.js} +6 -6
  283. package/web-shell/assets/{mindmap-definition-FBJOCRG2-CIGTi5gg.js → mindmap-definition-FBJOCRG2-BbcCi_jP.js} +1 -1
  284. package/web-shell/assets/{pegDiagram-XKGWAZYB-CuWBRQzb.js → pegDiagram-XKGWAZYB-DpLQ7u8i.js} +1 -1
  285. package/web-shell/assets/{pieDiagram-E7YTZNPT-Co5ukXCE.js → pieDiagram-E7YTZNPT-BpWFVtM0.js} +1 -1
  286. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-B0hzjh6o.js → quadrantDiagram-AXDQQJYC-CGzYlaN1.js} +1 -1
  287. package/web-shell/assets/{railroadDiagram-O6MQD6OU-nhkJB0xD.js → railroadDiagram-O6MQD6OU-BNQYW-Zi.js} +1 -1
  288. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-C7NpxjVR.js → requirementDiagram-EFPCY7ZU-C4fCdIDW.js} +1 -1
  289. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CUWlnhZC.js → sankeyDiagram-P5KCCOFB-BvbbAnMA.js} +1 -1
  290. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BoykH0_J.js → sequenceDiagram-WJ2MYXX4-DGXNc6E1.js} +1 -1
  291. package/web-shell/assets/{sizeCapture-X5ZJPWSS-aF-PkSe5.js → sizeCapture-X5ZJPWSS-C4W45Xf5.js} +1 -1
  292. package/web-shell/assets/{stateDiagram-HBIQ2CUA-g5q0b922.js → stateDiagram-HBIQ2CUA-D3q0fen-.js} +1 -1
  293. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-XKoYIi05.js +1 -0
  294. package/web-shell/assets/{swimlanes-XN3QIQJK-BbASszfe.js → swimlanes-XN3QIQJK-D8n-ResR.js} +1 -1
  295. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-C7qJMSzs.js +8 -0
  296. package/web-shell/assets/{timeline-definition-24CTP7MA-AXIV0TJJ.js → timeline-definition-24CTP7MA-Cio4y1mM.js} +1 -1
  297. package/web-shell/assets/{vennDiagram-4TSXK5OY-B-E0rj1h.js → vennDiagram-4TSXK5OY-DVlg0xnc.js} +1 -1
  298. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-DiOOYJ2D.js → wardleyDiagram-VM6X3IG4-CgeIsimQ.js} +1 -1
  299. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-De_z7HkS.js → xychartDiagram-S5SC5T6Z-UXjyTLnU.js} +1 -1
  300. package/web-shell/index.html +1 -1
  301. package/web-shell/sw.js +1 -1
  302. package/web-shell/assets/channel-Bwr9aS_E.js +0 -1
  303. package/web-shell/assets/classDiagram-DTDB5LWJ-BmY8Mmyo.js +0 -1
  304. package/web-shell/assets/classDiagram-v2-JRS7N3AN-BmY8Mmyo.js +0 -1
  305. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-CTOjUMow.js +0 -1
  306. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Bz6ia3oL.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{loadProjectMcpServers}from"./chunk-3NWFV2YF.js";import{loadSettings}from"./chunk-DFRSQK5Q.js";import{getCurrentLanguage}from"./chunk-H45OX4VY.js";import{require_strip_json_comments}from"./chunk-DOLUT3XC.js";import{isWorkspaceTrusted}from"./chunk-HJPO6MEW.js";import{hashMcpServerConfig}from"./chunk-BOFD4CN3.js";import{Config,ExtensionManager,FileDiscoveryService,MCPOAuthTokenStorage,createMcpClient,createTransport,isGatedMcpScope,runWithTimeout}from"./chunk-RKPHDO42.js";import{parseBooleanEnvFlag}from"./chunk-F63ESLTI.js";import{getMCPServerLastError,getMCPServerStatus}from"./chunk-DR3HLUJ5.js";import{atomicWriteFile}from"./chunk-BMHYEQTI.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();function splitCommaList(values){if(values===void 0)return void 0;const strings=values.filter(value=>typeof value==="string");if(strings.length===0)return values.length?void 0:[];return strings.flatMap(value=>value.split(",")).map(value=>value.trim()).filter(Boolean)}__name(splitCommaList,"splitCommaList");async function addMcpServer(name,commandOrUrl,args,options){const{scope,transport,env,header,timeout,trust,description,includeTools,excludeTools,oauthClientId,oauthClientSecret,oauthRedirectUri,oauthAuthorizationUrl,oauthTokenUrl,oauthScopes}=options;const settings=loadSettings(process.cwd());const inHome=settings.workspace.path===settings.user.path;if(scope==="project"&&inHome){writeStderrLine("Error: Please use --scope user to edit settings in the home directory.");process.exit(1)}const settingsScope=scope==="user"?"User":"Workspace";let newServer={};const scopes=splitCommaList(oauthScopes);const hasOAuth=Boolean(oauthClientId||oauthClientSecret||oauthRedirectUri||oauthAuthorizationUrl||oauthTokenUrl||scopes&&scopes.length>0);if(hasOAuth&&transport==="stdio"){writeStderrLine("Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http.");process.exit(1)}const oauthConfig=hasOAuth?{enabled:true,...oauthClientId&&{clientId:oauthClientId},...oauthClientSecret&&{clientSecret:oauthClientSecret},...oauthRedirectUri&&{redirectUri:oauthRedirectUri},...oauthAuthorizationUrl&&{authorizationUrl:oauthAuthorizationUrl},...oauthTokenUrl&&{tokenUrl:oauthTokenUrl},...scopes&&scopes.length>0&&{scopes}}:void 0;const headers=header?.reduce((acc,curr)=>{const[key,...valueParts]=curr.split(":");const value=valueParts.join(":").trim();if(key.trim()&&value){acc[key.trim()]=value}return acc},{});switch(transport){case"sse":newServer={url:commandOrUrl,headers,timeout,trust,description,includeTools,excludeTools,oauth:oauthConfig};break;case"http":newServer={httpUrl:commandOrUrl,headers,timeout,trust,description,includeTools,excludeTools,oauth:oauthConfig};break;case"stdio":default:newServer={command:commandOrUrl,args:args?.map(String),env:env?.reduce((acc,curr)=>{const separator=curr.indexOf("=");if(separator===-1){return acc}const key=curr.slice(0,separator);const value=curr.slice(separator+1);if(key&&value){acc[key]=value}return acc},{}),timeout,trust,description,includeTools,excludeTools};break}const existingSettings=settings.forScope(settingsScope).settings;const mcpServers=existingSettings.mcpServers||{};const isExistingServer=!!mcpServers[name];if(isExistingServer){writeStdoutLine(`MCP server "${name}" is already configured within ${scope} settings.`)}mcpServers[name]=newServer;settings.setValue(settingsScope,"mcpServers",mcpServers);if(isExistingServer){writeStdoutLine(`MCP server "${name}" updated in ${scope} settings.`)}else{writeStdoutLine(`MCP server "${name}" added to ${scope} settings. (${transport})`)}}__name(addMcpServer,"addMcpServer");var addCommand={command:"add <name> <commandOrUrl> [args...]",describe:"Add a server",builder:__name(yargs=>yargs.usage("Usage: qwen mcp add [options] <name> <commandOrUrl> [args...]").parserConfiguration({"unknown-options-as-args":true,"populate--":true}).positional("name",{describe:"Name of the server",type:"string",demandOption:true}).positional("commandOrUrl",{describe:"Command (stdio) or URL (sse, http)",type:"string",demandOption:true}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}).option("transport",{alias:"t",describe:"Transport type (stdio, sse, http). Auto-detected from URL if not specified.",type:"string",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:"Set environment variables (e.g. -e KEY=value)",type:"array",string:true,nargs:1}).option("header",{alias:"H",describe:'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',type:"array",string:true,nargs:1}).option("timeout",{describe:"Set connection timeout in milliseconds",type:"number"}).option("trust",{describe:"Trust the server (bypass its tool call confirmations in a trusted workspace)",type:"boolean"}).option("description",{describe:"Set the description for the server",type:"string"}).option("include-tools",{describe:"A comma-separated list of tools to include",type:"array",string:true}).option("exclude-tools",{describe:"A comma-separated list of tools to exclude",type:"array",string:true}).option("oauth-client-id",{describe:"OAuth client ID for MCP server authentication",type:"string"}).option("oauth-client-secret",{describe:"OAuth client secret for MCP server authentication",type:"string"}).option("oauth-redirect-uri",{describe:"OAuth redirect URI (e.g., https://your-server.com/oauth/callback). Defaults to localhost for local setups.",type:"string"}).option("oauth-authorization-url",{describe:"OAuth authorization URL",type:"string"}).option("oauth-token-url",{describe:"OAuth token URL",type:"string"}).option("oauth-scopes",{describe:"OAuth scopes (comma-separated)",type:"array",string:true}).middleware(argv=>{if(argv["--"]){const existingArgs=argv["args"]||[];argv["args"]=[...existingArgs,...argv["--"]]}if(!argv["transport"]){const commandOrUrl=argv["commandOrUrl"];if(commandOrUrl&&/^https?:\/\//i.test(commandOrUrl)){argv["transport"]="http"}else{argv["transport"]="stdio"}}}),"builder"),handler:__name(async argv=>{await addMcpServer(argv["name"],argv["commandOrUrl"],argv["args"],{scope:argv["scope"],transport:argv["transport"],env:argv["env"],header:argv["header"],timeout:argv["timeout"],trust:argv["trust"],description:argv["description"],includeTools:splitCommaList(argv["includeTools"]),excludeTools:splitCommaList(argv["excludeTools"]),oauthClientId:argv["oauthClientId"],oauthClientSecret:argv["oauthClientSecret"],oauthRedirectUri:argv["oauthRedirectUri"],oauthAuthorizationUrl:argv["oauthAuthorizationUrl"],oauthTokenUrl:argv["oauthTokenUrl"],oauthScopes:argv["oauthScopes"]})},"handler")};init_esbuild_shims();async function removeMcpServer(name,options){const{scope}=options;const settingsScope=scope==="user"?"User":"Workspace";const settings=loadSettings();const existingSettings=settings.forScope(settingsScope).settings;const mcpServers=existingSettings.mcpServers||{};if(!mcpServers[name]){writeStdoutLine(`Server "${name}" not found in ${scope} settings.`);return}delete mcpServers[name];settings.setValue(settingsScope,"mcpServers",mcpServers);try{const tokenStorage=new MCPOAuthTokenStorage;await tokenStorage.deleteCredentials(name)}catch{}writeStdoutLine(`Server "${name}" removed from ${scope} settings.`)}__name(removeMcpServer,"removeMcpServer");var removeCommand={command:"remove <name>",describe:"Remove a server",builder:__name(yargs=>yargs.usage("Usage: qwen mcp remove [options] <name>").positional("name",{describe:"Name of the server",type:"string",demandOption:true}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}),"builder"),handler:__name(async argv=>{await removeMcpServer(argv["name"],{scope:argv["scope"]})},"handler")};init_esbuild_shims();init_esbuild_shims();function assembleMcpServers(mergedSettingsServers,cwd,cliMcpServers){const belowProject={};const aboveProject={};for(const[name,config]of Object.entries(mergedSettingsServers??{})){if(config.scope==="workspace"||config.scope==="system"){aboveProject[name]=config}else{belowProject[name]=config}}const projectResult=loadProjectMcpServers(cwd);for(const error of projectResult.errors){writeStderrLine(`Warning: ${error}`)}return{...belowProject,...projectResult.servers,...aboveProject,...cliMcpServers??{}}}__name(assembleMcpServers,"assembleMcpServers");init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var MCP_APPROVALS_FILENAME="mcpApprovals.json";function getMcpApprovalsPath(){if(process.env["QWEN_CODE_MCP_APPROVALS_PATH"]){return process.env["QWEN_CODE_MCP_APPROVALS_PATH"]}return path.join(Storage.getGlobalQwenDir(),MCP_APPROVALS_FILENAME)}__name(getMcpApprovalsPath,"getMcpApprovalsPath");function normalizeProjectRoot(projectRoot){const resolved=path.resolve(projectRoot);return os.platform()==="win32"?resolved.toLowerCase():resolved}__name(normalizeProjectRoot,"normalizeProjectRoot");function isApprovalRecordMap(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isApprovalRecordMap,"isApprovalRecordMap");function isWin32AbsolutePath(p){return/^[A-Za-z]:[\\/]/.test(p)||/^\\\\/.test(p)}__name(isWin32AbsolutePath,"isWin32AbsolutePath");function mergeApprovalRecords(existing,incoming){const merged=Object.assign(Object.create(null),existing);for(const[name,record]of Object.entries(incoming)){if(!isApprovalRecordMap(record)){continue}const current=merged[name];if(!current){merged[name]=record}else if(current.status!==record.status){merged[name]=current.status==="rejected"?current:record}}return merged}__name(mergeApprovalRecords,"mergeApprovalRecords");function normalizeStoredProjectKeys(config){if(os.platform()!=="win32"){return config}const normalized=Object.create(null);for(const[key,value]of Object.entries(config)){const projectKey=isWin32AbsolutePath(key)?key.toLowerCase():key;const existing=normalized[projectKey];normalized[projectKey]=isApprovalRecordMap(existing)&&isApprovalRecordMap(value)?mergeApprovalRecords(existing,value):isApprovalRecordMap(value)||!isApprovalRecordMap(existing)?value:existing}return normalized}__name(normalizeStoredProjectKeys,"normalizeStoredProjectKeys");var LoadedMcpApprovals=class{constructor(file,errors){this.file=file;this.errors=errors}static{__name(this,"LoadedMcpApprovals")}getState(projectRoot,serverName,config){const record=this.file.config[normalizeProjectRoot(projectRoot)]?.[serverName];if(!record){return"pending"}if(record.hash!==hashMcpServerConfig(config)){return"pending"}return record.status}async setState(projectRoot,serverName,config,status){const root=normalizeProjectRoot(projectRoot);const existing=this.file.config[root];const project=isApprovalRecordMap(existing)?existing:Object.create(null);Object.defineProperty(project,serverName,{value:{hash:hashMcpServerConfig(config),status},enumerable:true,configurable:true,writable:true});this.file.config[root]=project;await saveMcpApprovals(this.file)}};var loadedMcpApprovals;function loadMcpApprovals(){if(loadedMcpApprovals){return loadedMcpApprovals}const errors=[];let config={};const filePath=getMcpApprovalsPath();try{if(fs.existsSync(filePath)){const content=fs.readFileSync(filePath,"utf-8");const parsed=JSON.parse((0,import_strip_json_comments.default)(content));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){errors.push({message:"MCP approvals file is not a valid JSON object.",path:filePath})}else{config=normalizeStoredProjectKeys(parsed)}}}catch(error){errors.push({message:getErrorMessage(error),path:filePath})}loadedMcpApprovals=new LoadedMcpApprovals({path:filePath,config},errors);for(const error of errors){writeStderrLine(`Warning: MCP approvals file error: ${error.message}`)}return loadedMcpApprovals}__name(loadMcpApprovals,"loadMcpApprovals");function getPendingGatedMcpServers(mcpServers,projectRoot){const approvals=loadMcpApprovals();const pending=[];for(const[name,config]of Object.entries(mcpServers)){if(!isGatedMcpScope(config.scope)){continue}if(approvals.getState(projectRoot,name,config)!=="approved"){pending.push(name)}}return pending}__name(getPendingGatedMcpServers,"getPendingGatedMcpServers");function getPromptableMcpServers(mcpServers,projectRoot){const approvals=loadMcpApprovals();const promptable=[];for(const[name,config]of Object.entries(mcpServers)){if(!isGatedMcpScope(config.scope)){continue}if(approvals.getState(projectRoot,name,config)==="pending"){promptable.push(name)}}return promptable}__name(getPromptableMcpServers,"getPromptableMcpServers");async function saveMcpApprovals(file){try{const dirPath=path.dirname(file.path);if(!fs.existsSync(dirPath)){fs.mkdirSync(dirPath,{recursive:true})}await atomicWriteFile(file.path,JSON.stringify(file.config,null,2),{mode:384})}catch(error){writeStderrLine("Error saving MCP approvals file.");writeStderrLine(error instanceof Error?error.message:String(error))}}__name(saveMcpApprovals,"saveMcpApprovals");var COLOR_GREEN="\x1B[32m";var COLOR_YELLOW="\x1B[33m";var COLOR_RED="\x1B[31m";var RESET_COLOR="\x1B[0m";var MCP_CONNECT_TIMEOUT_MS=1e4;async function getMcpServersFromConfig(){const settings=loadSettings();const extensionManager=new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});await extensionManager.refreshCache();const extensions=extensionManager.getLoadedExtensions();const mcpServers=assembleMcpServers(settings.merged.mcpServers,process.cwd());for(const extension of extensions){if(extension.isActive){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key]){return}mcpServers[key]={...server,extensionName:extension.config.name}})}}return mcpServers}__name(getMcpServersFromConfig,"getMcpServersFromConfig");async function testMCPConnection(serverName,config){const client=createMcpClient("mcp-test-client",config);let transport;try{transport=await createTransport(serverName,config,false)}catch(_error){await client.close();return{status:"disconnected",timedOut:false}}try{await runWithTimeout(client.connect(transport,{timeout:MCP_CONNECT_TIMEOUT_MS}),MCP_CONNECT_TIMEOUT_MS,`MCP connection for ${serverName}`);await client.close();return{status:"connected",timedOut:false}}catch(error){await transport.close();return{status:"disconnected",timedOut:error instanceof Error&&error.message.startsWith("Timed out after ")}}}__name(testMCPConnection,"testMCPConnection");async function getServerStatus(serverName,server){return await testMCPConnection(serverName,server)}__name(getServerStatus,"getServerStatus");async function listMcpServers(){const mcpServers=await getMcpServersFromConfig();const serverNames=Object.keys(mcpServers);if(serverNames.length===0){writeStdoutLine("No MCP servers configured.");return}writeStdoutLine("Configured MCP servers:\n");const cwd=process.cwd();let approvals;for(const serverName of serverNames){const server=mcpServers[serverName];let serverInfo=`${serverName}: `;if(server.httpUrl){serverInfo+=`${server.httpUrl} (http)`}else if(server.url){serverInfo+=`${server.url} (sse)`}else if(server.command){serverInfo+=`${server.command} ${server.args?.join(" ")||""} (stdio)`}if(isGatedMcpScope(server.scope)){approvals??=loadMcpApprovals();const state=approvals.getState(cwd,serverName,server);if(state!=="approved"){const statusText2=state==="rejected"?"Rejected":"Pending approval";writeStdoutLine(`${COLOR_YELLOW}\u25CF${RESET_COLOR} ${serverInfo} - ${statusText2}`);continue}}const{status,timedOut}=await getServerStatus(serverName,server);let statusIndicator="";let statusText="";switch(status){case"connected":statusIndicator=COLOR_GREEN+"\u2713"+RESET_COLOR;statusText="Connected";break;case"connecting":statusIndicator=COLOR_YELLOW+"\u2026"+RESET_COLOR;statusText="Connecting";break;case"disconnected":default:statusIndicator=COLOR_RED+"\u2717"+RESET_COLOR;statusText=timedOut?`Disconnected (timed out after ${MCP_CONNECT_TIMEOUT_MS}ms)`:"Disconnected";break}writeStdoutLine(`${statusIndicator} ${serverInfo} - ${statusText}`)}}__name(listMcpServers,"listMcpServers");var listCommand={command:"list",describe:"List all configured MCP servers",handler:__name(async()=>{await listMcpServers()},"handler")};init_esbuild_shims();async function getMcpServersFromConfig2(extensionManager){const settings=loadSettings();const extManager=extensionManager??new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});if(!extensionManager){await extManager.refreshCache()}const extensions=extManager.getLoadedExtensions();const mcpServers=assembleMcpServers(settings.merged.mcpServers,process.cwd());for(const extension of extensions){if(extension.isActive){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key]){return}mcpServers[key]={...server,extensionName:extension.config.name}})}}return mcpServers}__name(getMcpServersFromConfig2,"getMcpServersFromConfig");async function createMinimalConfig(){const settings=loadSettings();const cwd=process.cwd();const fileFiltering=settings.merged.context?.fileFiltering;const fileService=new FileDiscoveryService(cwd,fileFiltering?.customIgnoreFiles);const mcpServers=await getMcpServersFromConfig2();const allowedMcpServers=settings.merged.mcp?.allowed?new Set(settings.merged.mcp.allowed.filter(Boolean)):void 0;const excludedMcpServers=settings.merged.mcp?.excluded?new Set(settings.merged.mcp.excluded.filter(Boolean)):void 0;const config=new Config({sessionId:"mcp-reconnect",targetDir:cwd,cwd,debugMode:false,chatRecording:false,mcpServers,pendingMcpServers:getPendingGatedMcpServers(mcpServers,cwd),fileDiscoveryService:fileService,mcpServerCommand:settings.merged.mcp?.serverCommand,allowedMcpServers:allowedMcpServers?Array.from(allowedMcpServers):void 0,excludedMcpServers:excludedMcpServers?Array.from(excludedMcpServers):void 0,trustedFolder:isWorkspaceTrusted(settings.merged).isTrusted??true,usageStatisticsEnabled:parseBooleanEnvFlag(process.env["QWEN_USAGE_STATISTICS_ENABLED"])??settings.merged.privacy?.usageStatisticsEnabled??true,proxy:settings.merged.proxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"],...fileFiltering!==void 0?{fileFiltering}:{}});await config.initialize({skipMcpDiscovery:true});return config}__name(createMinimalConfig,"createMinimalConfig");var SkippedConnectionError=class extends Error{static{__name(this,"SkippedConnectionError")}skipReason;constructor(skipReason){super(`no connection attempt was made: ${skipReason}`);this.name="SkippedConnectionError";this.skipReason=skipReason}};var SESSION_SCOPE_NOTE="Note: this command reconnects in a separate process; it cannot refresh the MCP tools of an already-running Qwen Code session. Restart that session if its tools remain unavailable.";function createReconnectError(message,exitCode=1){const error=new Error(message);error.exitCode=exitCode;return error}__name(createReconnectError,"createReconnectError");function describeSkippedConnectionReason(config,serverName){const unavailableReason=config.getMcpServerUnavailableReason(serverName);if(unavailableReason==="excluded"){return"server is excluded in settings (mcp.excluded)"}if(unavailableReason==="not_allowed"){return"server is not in the mcp.allowed list"}if(config.isMcpServerDisabled(serverName)){return"server is disabled in settings"}if(config.isMcpServerPendingApproval(serverName)){return"server is pending approval (.mcp.json)"}if(config.isTrustedFolder()===false){return"workspace folder is not trusted"}return void 0}__name(describeSkippedConnectionReason,"describeSkippedConnectionReason");async function discoverAndVerifyConnection(config,serverName){const toolRegistry=config.getToolRegistry();await toolRegistry.discoverToolsForServer(serverName);const status=getMCPServerStatus(serverName);if(status!=="connected"){const skippedReason=describeSkippedConnectionReason(config,serverName);if(skippedReason){throw new SkippedConnectionError(skippedReason)}const lastError=getMCPServerLastError(serverName);throw new Error(`connection attempt finished without a live connection (status: ${status})`+(lastError?`: ${lastError}`:""))}}__name(discoverAndVerifyConnection,"discoverAndVerifyConnection");async function reconnectMcpServer(serverName){const mcpServers=await getMcpServersFromConfig2();if(!mcpServers[serverName]){throw createReconnectError(`Error: Server "${serverName}" not found in configuration.`)}writeStdoutLine(`Reconnecting to server "${serverName}"...`);let config;try{config=await createMinimalConfig();await discoverAndVerifyConnection(config,serverName);writeStdoutLine(`Successfully reconnected to server "${serverName}".`);writeStdoutLine(SESSION_SCOPE_NOTE)}catch(error){const message=error instanceof Error?error.message:String(error);writeStdoutLine(SESSION_SCOPE_NOTE);throw createReconnectError(`Failed to reconnect to server "${serverName}": ${message}`)}finally{if(config){await config.shutdown()}}}__name(reconnectMcpServer,"reconnectMcpServer");async function reconnectAllMcpServers(){const settings=loadSettings();const extensionManager=new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});await extensionManager.refreshCache();const mcpServers=await getMcpServersFromConfig2(extensionManager);const serverNames=Object.keys(mcpServers);if(serverNames.length===0){writeStdoutLine("No MCP servers configured.");return}writeStdoutLine("Reconnecting to all MCP servers...\n");let config;let failedCount=0;try{config=await createMinimalConfig();for(const serverName of serverNames){try{await discoverAndVerifyConnection(config,serverName);writeStdoutLine(`\u2713 ${serverName}: Reconnected successfully`)}catch(error){if(error instanceof SkippedConnectionError){writeStdoutLine(`- ${serverName}: Skipped - ${error.skipReason}`);continue}failedCount++;const message=error instanceof Error?error.message:String(error);writeStdoutLine(`\u2717 ${serverName}: Failed - ${message}`)}}writeStdoutLine("");writeStdoutLine(SESSION_SCOPE_NOTE)}finally{if(config){await config.shutdown()}}if(failedCount>0){throw createReconnectError(`Failed to reconnect ${failedCount} of ${serverNames.length} configured server(s).`)}}__name(reconnectAllMcpServers,"reconnectAllMcpServers");var reconnectCommand={command:"reconnect [server-name]",describe:"Reconnect MCP server(s)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp reconnect [options] [server-name]").positional("server-name",{describe:"Name of the server to reconnect",type:"string"}).option("all",{alias:"a",describe:"Reconnect all configured servers",type:"boolean",default:false}).conflicts("server-name","all").check(argv=>{const serverName=argv["server-name"];const all=argv["all"];if(!serverName&&!all){throw new Error("Please specify a server name or use --all to reconnect all servers.")}return true}),"builder"),handler:__name(async argv=>{const serverName=argv["server-name"];const all=argv["all"];try{if(all){await reconnectAllMcpServers()}else if(serverName){await reconnectMcpServer(serverName)}}catch(error){const message=error instanceof Error?error.message:String(error);const exitCode=error?.exitCode??1;writeStderrLine(message);process.exit(exitCode)}},"handler")};init_esbuild_shims();function loadGatedServers(cwd){const settings=loadSettings(cwd);const all=assembleMcpServers(settings.merged.mcpServers,cwd);const gated={};for(const[serverName,config]of Object.entries(all)){if(isGatedMcpScope(config.scope)){gated[serverName]=config}}return gated}__name(loadGatedServers,"loadGatedServers");async function setProjectServerStatus(name,status,all){const cwd=process.cwd();const servers=loadGatedServers(cwd);const names=Object.keys(servers);if(names.length===0){writeStdoutLine("No approval-requiring MCP servers found (looked in .mcp.json and .qwen/settings.json).");return}const verb=status==="approved"?"Approved":"Rejected";const approvals=loadMcpApprovals();const targets=all?names:name?[name]:[];if(targets.length===0){writeStdoutLine("Specify a server name or pass --all.");return}for(const target of targets){const config=servers[target];if(!config){writeStdoutLine(`Server "${target}" not found. Available: ${names.join(", ")}`);continue}await approvals.setState(cwd,target,config,status);writeStdoutLine(`${verb} MCP server "${target}" (bound to its current config).`)}if(status==="approved"){writeStdoutLine("Approved servers connect in your next interactive session.")}}__name(setProjectServerStatus,"setProjectServerStatus");var approveCommand={command:"approve [name]",describe:"Approve a gated MCP server (.mcp.json or workspace .qwen/settings.json)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp approve [options] [name]").positional("name",{describe:"Name of the gated server to approve",type:"string"}).option("all",{describe:"Approve all gated servers in this workspace",type:"boolean",default:false}),"builder"),handler:__name(async argv=>{await setProjectServerStatus(argv["name"],"approved",argv["all"])},"handler")};var rejectCommand={command:"reject [name]",describe:"Reject a gated MCP server (.mcp.json or workspace .qwen/settings.json)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp reject [options] [name]").positional("name",{describe:"Name of the gated server to reject",type:"string"}).option("all",{describe:"Reject all gated servers in this workspace",type:"boolean",default:false}),"builder"),handler:__name(async argv=>{await setProjectServerStatus(argv["name"],"rejected",argv["all"])},"handler")};var mcpCommand={command:"mcp",describe:"Manage MCP servers",builder:__name(yargs=>yargs.command(addCommand).command(removeCommand).command(listCommand).command(reconnectCommand).command(approveCommand).command(rejectCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{assembleMcpServers,loadMcpApprovals,getPendingGatedMcpServers,getPromptableMcpServers,mcpCommand};
3
+ import{loadProjectMcpServers}from"./chunk-PMBGV76N.js";import{loadSettings}from"./chunk-FHFBCG6N.js";import{getCurrentLanguage}from"./chunk-H45OX4VY.js";import{require_strip_json_comments}from"./chunk-DOLUT3XC.js";import{isWorkspaceTrusted}from"./chunk-W5D2T2JK.js";import{hashMcpServerConfig}from"./chunk-AVIDPC5K.js";import{Config,ExtensionManager,FileDiscoveryService,MCPOAuthTokenStorage,createMcpClient,createTransport,isGatedMcpScope,runWithTimeout}from"./chunk-LDXZT3SG.js";import{parseBooleanEnvFlag}from"./chunk-F63ESLTI.js";import{getMCPServerLastError,getMCPServerStatus}from"./chunk-DR3HLUJ5.js";import{atomicWriteFile}from"./chunk-BMHYEQTI.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();function splitCommaList(values){if(values===void 0)return void 0;const strings=values.filter(value=>typeof value==="string");if(strings.length===0)return values.length?void 0:[];return strings.flatMap(value=>value.split(",")).map(value=>value.trim()).filter(Boolean)}__name(splitCommaList,"splitCommaList");async function addMcpServer(name,commandOrUrl,args,options){const{scope,transport,env,header,timeout,trust,description,includeTools,excludeTools,oauthClientId,oauthClientSecret,oauthRedirectUri,oauthAuthorizationUrl,oauthTokenUrl,oauthScopes}=options;const settings=loadSettings(process.cwd());const inHome=settings.workspace.path===settings.user.path;if(scope==="project"&&inHome){writeStderrLine("Error: Please use --scope user to edit settings in the home directory.");process.exit(1)}const settingsScope=scope==="user"?"User":"Workspace";let newServer={};const scopes=splitCommaList(oauthScopes);const hasOAuth=Boolean(oauthClientId||oauthClientSecret||oauthRedirectUri||oauthAuthorizationUrl||oauthTokenUrl||scopes&&scopes.length>0);if(hasOAuth&&transport==="stdio"){writeStderrLine("Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http.");process.exit(1)}const oauthConfig=hasOAuth?{enabled:true,...oauthClientId&&{clientId:oauthClientId},...oauthClientSecret&&{clientSecret:oauthClientSecret},...oauthRedirectUri&&{redirectUri:oauthRedirectUri},...oauthAuthorizationUrl&&{authorizationUrl:oauthAuthorizationUrl},...oauthTokenUrl&&{tokenUrl:oauthTokenUrl},...scopes&&scopes.length>0&&{scopes}}:void 0;const headers=header?.reduce((acc,curr)=>{const[key,...valueParts]=curr.split(":");const value=valueParts.join(":").trim();if(key.trim()&&value){acc[key.trim()]=value}return acc},{});switch(transport){case"sse":newServer={url:commandOrUrl,headers,timeout,trust,description,includeTools,excludeTools,oauth:oauthConfig};break;case"http":newServer={httpUrl:commandOrUrl,headers,timeout,trust,description,includeTools,excludeTools,oauth:oauthConfig};break;case"stdio":default:newServer={command:commandOrUrl,args:args?.map(String),env:env?.reduce((acc,curr)=>{const separator=curr.indexOf("=");if(separator===-1){return acc}const key=curr.slice(0,separator);const value=curr.slice(separator+1);if(key&&value){acc[key]=value}return acc},{}),timeout,trust,description,includeTools,excludeTools};break}const existingSettings=settings.forScope(settingsScope).settings;const mcpServers=existingSettings.mcpServers||{};const isExistingServer=!!mcpServers[name];if(isExistingServer){writeStdoutLine(`MCP server "${name}" is already configured within ${scope} settings.`)}mcpServers[name]=newServer;settings.setValue(settingsScope,"mcpServers",mcpServers);if(isExistingServer){writeStdoutLine(`MCP server "${name}" updated in ${scope} settings.`)}else{writeStdoutLine(`MCP server "${name}" added to ${scope} settings. (${transport})`)}}__name(addMcpServer,"addMcpServer");var addCommand={command:"add <name> <commandOrUrl> [args...]",describe:"Add a server",builder:__name(yargs=>yargs.usage("Usage: qwen mcp add [options] <name> <commandOrUrl> [args...]").parserConfiguration({"unknown-options-as-args":true,"populate--":true}).positional("name",{describe:"Name of the server",type:"string",demandOption:true}).positional("commandOrUrl",{describe:"Command (stdio) or URL (sse, http)",type:"string",demandOption:true}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}).option("transport",{alias:"t",describe:"Transport type (stdio, sse, http). Auto-detected from URL if not specified.",type:"string",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:"Set environment variables (e.g. -e KEY=value)",type:"array",string:true,nargs:1}).option("header",{alias:"H",describe:'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',type:"array",string:true,nargs:1}).option("timeout",{describe:"Set connection timeout in milliseconds",type:"number"}).option("trust",{describe:"Trust the server (bypass its tool call confirmations in a trusted workspace)",type:"boolean"}).option("description",{describe:"Set the description for the server",type:"string"}).option("include-tools",{describe:"A comma-separated list of tools to include",type:"array",string:true}).option("exclude-tools",{describe:"A comma-separated list of tools to exclude",type:"array",string:true}).option("oauth-client-id",{describe:"OAuth client ID for MCP server authentication",type:"string"}).option("oauth-client-secret",{describe:"OAuth client secret for MCP server authentication",type:"string"}).option("oauth-redirect-uri",{describe:"OAuth redirect URI (e.g., https://your-server.com/oauth/callback). Defaults to localhost for local setups.",type:"string"}).option("oauth-authorization-url",{describe:"OAuth authorization URL",type:"string"}).option("oauth-token-url",{describe:"OAuth token URL",type:"string"}).option("oauth-scopes",{describe:"OAuth scopes (comma-separated)",type:"array",string:true}).middleware(argv=>{if(argv["--"]){const existingArgs=argv["args"]||[];argv["args"]=[...existingArgs,...argv["--"]]}if(!argv["transport"]){const commandOrUrl=argv["commandOrUrl"];if(commandOrUrl&&/^https?:\/\//i.test(commandOrUrl)){argv["transport"]="http"}else{argv["transport"]="stdio"}}}),"builder"),handler:__name(async argv=>{await addMcpServer(argv["name"],argv["commandOrUrl"],argv["args"],{scope:argv["scope"],transport:argv["transport"],env:argv["env"],header:argv["header"],timeout:argv["timeout"],trust:argv["trust"],description:argv["description"],includeTools:splitCommaList(argv["includeTools"]),excludeTools:splitCommaList(argv["excludeTools"]),oauthClientId:argv["oauthClientId"],oauthClientSecret:argv["oauthClientSecret"],oauthRedirectUri:argv["oauthRedirectUri"],oauthAuthorizationUrl:argv["oauthAuthorizationUrl"],oauthTokenUrl:argv["oauthTokenUrl"],oauthScopes:argv["oauthScopes"]})},"handler")};init_esbuild_shims();async function removeMcpServer(name,options){const{scope}=options;const settingsScope=scope==="user"?"User":"Workspace";const settings=loadSettings();const existingSettings=settings.forScope(settingsScope).settings;const mcpServers=existingSettings.mcpServers||{};if(!mcpServers[name]){writeStdoutLine(`Server "${name}" not found in ${scope} settings.`);return}delete mcpServers[name];settings.setValue(settingsScope,"mcpServers",mcpServers);try{const tokenStorage=new MCPOAuthTokenStorage;await tokenStorage.deleteCredentials(name)}catch{}writeStdoutLine(`Server "${name}" removed from ${scope} settings.`)}__name(removeMcpServer,"removeMcpServer");var removeCommand={command:"remove <name>",describe:"Remove a server",builder:__name(yargs=>yargs.usage("Usage: qwen mcp remove [options] <name>").positional("name",{describe:"Name of the server",type:"string",demandOption:true}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}),"builder"),handler:__name(async argv=>{await removeMcpServer(argv["name"],{scope:argv["scope"]})},"handler")};init_esbuild_shims();init_esbuild_shims();function assembleMcpServers(mergedSettingsServers,cwd,cliMcpServers){const belowProject={};const aboveProject={};for(const[name,config]of Object.entries(mergedSettingsServers??{})){if(config.scope==="workspace"||config.scope==="system"){aboveProject[name]=config}else{belowProject[name]=config}}const projectResult=loadProjectMcpServers(cwd);for(const error of projectResult.errors){writeStderrLine(`Warning: ${error}`)}return{...belowProject,...projectResult.servers,...aboveProject,...cliMcpServers??{}}}__name(assembleMcpServers,"assembleMcpServers");init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var MCP_APPROVALS_FILENAME="mcpApprovals.json";function getMcpApprovalsPath(){if(process.env["QWEN_CODE_MCP_APPROVALS_PATH"]){return process.env["QWEN_CODE_MCP_APPROVALS_PATH"]}return path.join(Storage.getGlobalQwenDir(),MCP_APPROVALS_FILENAME)}__name(getMcpApprovalsPath,"getMcpApprovalsPath");function normalizeProjectRoot(projectRoot){const resolved=path.resolve(projectRoot);return os.platform()==="win32"?resolved.toLowerCase():resolved}__name(normalizeProjectRoot,"normalizeProjectRoot");function isApprovalRecordMap(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isApprovalRecordMap,"isApprovalRecordMap");function isWin32AbsolutePath(p){return/^[A-Za-z]:[\\/]/.test(p)||/^\\\\/.test(p)}__name(isWin32AbsolutePath,"isWin32AbsolutePath");function mergeApprovalRecords(existing,incoming){const merged=Object.assign(Object.create(null),existing);for(const[name,record]of Object.entries(incoming)){if(!isApprovalRecordMap(record)){continue}const current=merged[name];if(!current){merged[name]=record}else if(current.status!==record.status){merged[name]=current.status==="rejected"?current:record}}return merged}__name(mergeApprovalRecords,"mergeApprovalRecords");function normalizeStoredProjectKeys(config){if(os.platform()!=="win32"){return config}const normalized=Object.create(null);for(const[key,value]of Object.entries(config)){const projectKey=isWin32AbsolutePath(key)?key.toLowerCase():key;const existing=normalized[projectKey];normalized[projectKey]=isApprovalRecordMap(existing)&&isApprovalRecordMap(value)?mergeApprovalRecords(existing,value):isApprovalRecordMap(value)||!isApprovalRecordMap(existing)?value:existing}return normalized}__name(normalizeStoredProjectKeys,"normalizeStoredProjectKeys");var LoadedMcpApprovals=class{constructor(file,errors){this.file=file;this.errors=errors}static{__name(this,"LoadedMcpApprovals")}getState(projectRoot,serverName,config){const record=this.file.config[normalizeProjectRoot(projectRoot)]?.[serverName];if(!record){return"pending"}if(record.hash!==hashMcpServerConfig(config)){return"pending"}return record.status}async setState(projectRoot,serverName,config,status){const root=normalizeProjectRoot(projectRoot);const existing=this.file.config[root];const project=isApprovalRecordMap(existing)?existing:Object.create(null);Object.defineProperty(project,serverName,{value:{hash:hashMcpServerConfig(config),status},enumerable:true,configurable:true,writable:true});this.file.config[root]=project;await saveMcpApprovals(this.file)}};var loadedMcpApprovals;function loadMcpApprovals(){if(loadedMcpApprovals){return loadedMcpApprovals}const errors=[];let config={};const filePath=getMcpApprovalsPath();try{if(fs.existsSync(filePath)){const content=fs.readFileSync(filePath,"utf-8");const parsed=JSON.parse((0,import_strip_json_comments.default)(content));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){errors.push({message:"MCP approvals file is not a valid JSON object.",path:filePath})}else{config=normalizeStoredProjectKeys(parsed)}}}catch(error){errors.push({message:getErrorMessage(error),path:filePath})}loadedMcpApprovals=new LoadedMcpApprovals({path:filePath,config},errors);for(const error of errors){writeStderrLine(`Warning: MCP approvals file error: ${error.message}`)}return loadedMcpApprovals}__name(loadMcpApprovals,"loadMcpApprovals");function getPendingGatedMcpServers(mcpServers,projectRoot){const approvals=loadMcpApprovals();const pending=[];for(const[name,config]of Object.entries(mcpServers)){if(!isGatedMcpScope(config.scope)){continue}if(approvals.getState(projectRoot,name,config)!=="approved"){pending.push(name)}}return pending}__name(getPendingGatedMcpServers,"getPendingGatedMcpServers");function getPromptableMcpServers(mcpServers,projectRoot){const approvals=loadMcpApprovals();const promptable=[];for(const[name,config]of Object.entries(mcpServers)){if(!isGatedMcpScope(config.scope)){continue}if(approvals.getState(projectRoot,name,config)==="pending"){promptable.push(name)}}return promptable}__name(getPromptableMcpServers,"getPromptableMcpServers");async function saveMcpApprovals(file){try{const dirPath=path.dirname(file.path);if(!fs.existsSync(dirPath)){fs.mkdirSync(dirPath,{recursive:true})}await atomicWriteFile(file.path,JSON.stringify(file.config,null,2),{mode:384})}catch(error){writeStderrLine("Error saving MCP approvals file.");writeStderrLine(error instanceof Error?error.message:String(error))}}__name(saveMcpApprovals,"saveMcpApprovals");var COLOR_GREEN="\x1B[32m";var COLOR_YELLOW="\x1B[33m";var COLOR_RED="\x1B[31m";var RESET_COLOR="\x1B[0m";var MCP_CONNECT_TIMEOUT_MS=1e4;async function getMcpServersFromConfig(){const settings=loadSettings();const extensionManager=new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});await extensionManager.refreshCache();const extensions=extensionManager.getLoadedExtensions();const mcpServers=assembleMcpServers(settings.merged.mcpServers,process.cwd());for(const extension of extensions){if(extension.isActive){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key]){return}mcpServers[key]={...server,extensionName:extension.config.name}})}}return mcpServers}__name(getMcpServersFromConfig,"getMcpServersFromConfig");async function testMCPConnection(serverName,config){const client=createMcpClient("mcp-test-client",config);let transport;try{transport=await createTransport(serverName,config,false)}catch(_error){await client.close();return{status:"disconnected",timedOut:false}}try{await runWithTimeout(client.connect(transport,{timeout:MCP_CONNECT_TIMEOUT_MS}),MCP_CONNECT_TIMEOUT_MS,`MCP connection for ${serverName}`);await client.close();return{status:"connected",timedOut:false}}catch(error){await transport.close();return{status:"disconnected",timedOut:error instanceof Error&&error.message.startsWith("Timed out after ")}}}__name(testMCPConnection,"testMCPConnection");async function getServerStatus(serverName,server){return await testMCPConnection(serverName,server)}__name(getServerStatus,"getServerStatus");async function listMcpServers(){const mcpServers=await getMcpServersFromConfig();const serverNames=Object.keys(mcpServers);if(serverNames.length===0){writeStdoutLine("No MCP servers configured.");return}writeStdoutLine("Configured MCP servers:\n");const cwd=process.cwd();let approvals;for(const serverName of serverNames){const server=mcpServers[serverName];let serverInfo=`${serverName}: `;if(server.httpUrl){serverInfo+=`${server.httpUrl} (http)`}else if(server.url){serverInfo+=`${server.url} (sse)`}else if(server.command){serverInfo+=`${server.command} ${server.args?.join(" ")||""} (stdio)`}if(isGatedMcpScope(server.scope)){approvals??=loadMcpApprovals();const state=approvals.getState(cwd,serverName,server);if(state!=="approved"){const statusText2=state==="rejected"?"Rejected":"Pending approval";writeStdoutLine(`${COLOR_YELLOW}\u25CF${RESET_COLOR} ${serverInfo} - ${statusText2}`);continue}}const{status,timedOut}=await getServerStatus(serverName,server);let statusIndicator="";let statusText="";switch(status){case"connected":statusIndicator=COLOR_GREEN+"\u2713"+RESET_COLOR;statusText="Connected";break;case"connecting":statusIndicator=COLOR_YELLOW+"\u2026"+RESET_COLOR;statusText="Connecting";break;case"disconnected":default:statusIndicator=COLOR_RED+"\u2717"+RESET_COLOR;statusText=timedOut?`Disconnected (timed out after ${MCP_CONNECT_TIMEOUT_MS}ms)`:"Disconnected";break}writeStdoutLine(`${statusIndicator} ${serverInfo} - ${statusText}`)}}__name(listMcpServers,"listMcpServers");var listCommand={command:"list",describe:"List all configured MCP servers",handler:__name(async()=>{await listMcpServers()},"handler")};init_esbuild_shims();async function getMcpServersFromConfig2(extensionManager){const settings=loadSettings();const extManager=extensionManager??new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});if(!extensionManager){await extManager.refreshCache()}const extensions=extManager.getLoadedExtensions();const mcpServers=assembleMcpServers(settings.merged.mcpServers,process.cwd());for(const extension of extensions){if(extension.isActive){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key]){return}mcpServers[key]={...server,extensionName:extension.config.name}})}}return mcpServers}__name(getMcpServersFromConfig2,"getMcpServersFromConfig");async function createMinimalConfig(){const settings=loadSettings();const cwd=process.cwd();const fileFiltering=settings.merged.context?.fileFiltering;const fileService=new FileDiscoveryService(cwd,fileFiltering?.customIgnoreFiles);const mcpServers=await getMcpServersFromConfig2();const allowedMcpServers=settings.merged.mcp?.allowed?new Set(settings.merged.mcp.allowed.filter(Boolean)):void 0;const excludedMcpServers=settings.merged.mcp?.excluded?new Set(settings.merged.mcp.excluded.filter(Boolean)):void 0;const config=new Config({sessionId:"mcp-reconnect",targetDir:cwd,cwd,debugMode:false,chatRecording:false,mcpServers,pendingMcpServers:getPendingGatedMcpServers(mcpServers,cwd),fileDiscoveryService:fileService,mcpServerCommand:settings.merged.mcp?.serverCommand,allowedMcpServers:allowedMcpServers?Array.from(allowedMcpServers):void 0,excludedMcpServers:excludedMcpServers?Array.from(excludedMcpServers):void 0,trustedFolder:isWorkspaceTrusted(settings.merged).isTrusted??true,usageStatisticsEnabled:parseBooleanEnvFlag(process.env["QWEN_USAGE_STATISTICS_ENABLED"])??settings.merged.privacy?.usageStatisticsEnabled??true,proxy:settings.merged.proxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"],...fileFiltering!==void 0?{fileFiltering}:{}});await config.initialize({skipMcpDiscovery:true});return config}__name(createMinimalConfig,"createMinimalConfig");var SkippedConnectionError=class extends Error{static{__name(this,"SkippedConnectionError")}skipReason;constructor(skipReason){super(`no connection attempt was made: ${skipReason}`);this.name="SkippedConnectionError";this.skipReason=skipReason}};var SESSION_SCOPE_NOTE="Note: this command reconnects in a separate process; it cannot refresh the MCP tools of an already-running Qwen Code session. Restart that session if its tools remain unavailable.";function createReconnectError(message,exitCode=1){const error=new Error(message);error.exitCode=exitCode;return error}__name(createReconnectError,"createReconnectError");function describeSkippedConnectionReason(config,serverName){const unavailableReason=config.getMcpServerUnavailableReason(serverName);if(unavailableReason==="excluded"){return"server is excluded in settings (mcp.excluded)"}if(unavailableReason==="not_allowed"){return"server is not in the mcp.allowed list"}if(config.isMcpServerDisabled(serverName)){return"server is disabled in settings"}if(config.isMcpServerPendingApproval(serverName)){return"server is pending approval (.mcp.json)"}if(config.isTrustedFolder()===false){return"workspace folder is not trusted"}return void 0}__name(describeSkippedConnectionReason,"describeSkippedConnectionReason");async function discoverAndVerifyConnection(config,serverName){const toolRegistry=config.getToolRegistry();await toolRegistry.discoverToolsForServer(serverName);const status=getMCPServerStatus(serverName);if(status!=="connected"){const skippedReason=describeSkippedConnectionReason(config,serverName);if(skippedReason){throw new SkippedConnectionError(skippedReason)}const lastError=getMCPServerLastError(serverName);throw new Error(`connection attempt finished without a live connection (status: ${status})`+(lastError?`: ${lastError}`:""))}}__name(discoverAndVerifyConnection,"discoverAndVerifyConnection");async function reconnectMcpServer(serverName){const mcpServers=await getMcpServersFromConfig2();if(!mcpServers[serverName]){throw createReconnectError(`Error: Server "${serverName}" not found in configuration.`)}writeStdoutLine(`Reconnecting to server "${serverName}"...`);let config;try{config=await createMinimalConfig();await discoverAndVerifyConnection(config,serverName);writeStdoutLine(`Successfully reconnected to server "${serverName}".`);writeStdoutLine(SESSION_SCOPE_NOTE)}catch(error){const message=error instanceof Error?error.message:String(error);writeStdoutLine(SESSION_SCOPE_NOTE);throw createReconnectError(`Failed to reconnect to server "${serverName}": ${message}`)}finally{if(config){await config.shutdown()}}}__name(reconnectMcpServer,"reconnectMcpServer");async function reconnectAllMcpServers(){const settings=loadSettings();const extensionManager=new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});await extensionManager.refreshCache();const mcpServers=await getMcpServersFromConfig2(extensionManager);const serverNames=Object.keys(mcpServers);if(serverNames.length===0){writeStdoutLine("No MCP servers configured.");return}writeStdoutLine("Reconnecting to all MCP servers...\n");let config;let failedCount=0;try{config=await createMinimalConfig();for(const serverName of serverNames){try{await discoverAndVerifyConnection(config,serverName);writeStdoutLine(`\u2713 ${serverName}: Reconnected successfully`)}catch(error){if(error instanceof SkippedConnectionError){writeStdoutLine(`- ${serverName}: Skipped - ${error.skipReason}`);continue}failedCount++;const message=error instanceof Error?error.message:String(error);writeStdoutLine(`\u2717 ${serverName}: Failed - ${message}`)}}writeStdoutLine("");writeStdoutLine(SESSION_SCOPE_NOTE)}finally{if(config){await config.shutdown()}}if(failedCount>0){throw createReconnectError(`Failed to reconnect ${failedCount} of ${serverNames.length} configured server(s).`)}}__name(reconnectAllMcpServers,"reconnectAllMcpServers");var reconnectCommand={command:"reconnect [server-name]",describe:"Reconnect MCP server(s)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp reconnect [options] [server-name]").positional("server-name",{describe:"Name of the server to reconnect",type:"string"}).option("all",{alias:"a",describe:"Reconnect all configured servers",type:"boolean",default:false}).conflicts("server-name","all").check(argv=>{const serverName=argv["server-name"];const all=argv["all"];if(!serverName&&!all){throw new Error("Please specify a server name or use --all to reconnect all servers.")}return true}),"builder"),handler:__name(async argv=>{const serverName=argv["server-name"];const all=argv["all"];try{if(all){await reconnectAllMcpServers()}else if(serverName){await reconnectMcpServer(serverName)}}catch(error){const message=error instanceof Error?error.message:String(error);const exitCode=error?.exitCode??1;writeStderrLine(message);process.exit(exitCode)}},"handler")};init_esbuild_shims();function loadGatedServers(cwd){const settings=loadSettings(cwd);const all=assembleMcpServers(settings.merged.mcpServers,cwd);const gated={};for(const[serverName,config]of Object.entries(all)){if(isGatedMcpScope(config.scope)){gated[serverName]=config}}return gated}__name(loadGatedServers,"loadGatedServers");async function setProjectServerStatus(name,status,all){const cwd=process.cwd();const servers=loadGatedServers(cwd);const names=Object.keys(servers);if(names.length===0){writeStdoutLine("No approval-requiring MCP servers found (looked in .mcp.json and .qwen/settings.json).");return}const verb=status==="approved"?"Approved":"Rejected";const approvals=loadMcpApprovals();const targets=all?names:name?[name]:[];if(targets.length===0){writeStdoutLine("Specify a server name or pass --all.");return}for(const target of targets){const config=servers[target];if(!config){writeStdoutLine(`Server "${target}" not found. Available: ${names.join(", ")}`);continue}await approvals.setState(cwd,target,config,status);writeStdoutLine(`${verb} MCP server "${target}" (bound to its current config).`)}if(status==="approved"){writeStdoutLine("Approved servers connect in your next interactive session.")}}__name(setProjectServerStatus,"setProjectServerStatus");var approveCommand={command:"approve [name]",describe:"Approve a gated MCP server (.mcp.json or workspace .qwen/settings.json)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp approve [options] [name]").positional("name",{describe:"Name of the gated server to approve",type:"string"}).option("all",{describe:"Approve all gated servers in this workspace",type:"boolean",default:false}),"builder"),handler:__name(async argv=>{await setProjectServerStatus(argv["name"],"approved",argv["all"])},"handler")};var rejectCommand={command:"reject [name]",describe:"Reject a gated MCP server (.mcp.json or workspace .qwen/settings.json)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp reject [options] [name]").positional("name",{describe:"Name of the gated server to reject",type:"string"}).option("all",{describe:"Reject all gated servers in this workspace",type:"boolean",default:false}),"builder"),handler:__name(async argv=>{await setProjectServerStatus(argv["name"],"rejected",argv["all"])},"handler")};var mcpCommand={command:"mcp",describe:"Manage MCP servers",builder:__name(yargs=>yargs.command(addCommand).command(removeCommand).command(listCommand).command(reconnectCommand).command(approveCommand).command(rejectCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{assembleMcpServers,loadMcpApprovals,getPendingGatedMcpServers,getPromptableMcpServers,mcpCommand};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -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{DEFAULT_RING_SIZE}from"./chunk-BWQ5AIEA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,JOURNAL_GROWTH_HARD_CAP_BYTES}from"./chunk-WDR5XP3Y.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-DFRSQK5Q.js";import{MCP_BUDGET_WARN_FRACTION}from"./chunk-RKPHDO42.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-SLPJ4OII.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";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}:{})}catch(err){if(err instanceof Error&&err.code==="ambiguous_lan_interface"){throw new Error(`${err.message}. Pass --local-control-address <ip>.`)}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("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",default:32,description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable."}).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("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."}).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(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("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."}).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."}).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."}).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=>{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.")}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-EJ67LA5O.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"],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["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"]}:{},...argv["managed-runtime-broker-url"]!==void 0?{managedRuntimeBrokerUrl:argv["managed-runtime-broker-url"]}:{},...argv["managed-runtime-broker-token"]!==void 0?{managedRuntimeBrokerToken:argv["managed-runtime-broker-token"]}:{},...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-FVXQH3JA.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-AZP3PZXS.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,maybeOpenWebShellBrowser,serveCommand};
3
+ import{HEADLESS_YOLO_NO_SANDBOX_WARNING}from"./chunk-Z57KDB5F.js";import{DEFAULT_RING_SIZE}from"./chunk-BWQ5AIEA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,JOURNAL_GROWTH_HARD_CAP_BYTES}from"./chunk-WDR5XP3Y.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-FHFBCG6N.js";import{MCP_BUDGET_WARN_FRACTION}from"./chunk-LDXZT3SG.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-SLPJ4OII.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";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}:{})}catch(err){if(err instanceof Error&&err.code==="ambiguous_lan_interface"){throw new Error(`${err.message}. Pass --local-control-address <ip>.`)}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("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",default:32,description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable."}).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("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."}).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(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("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."}).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."}).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."}).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=>{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.")}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-EOUUDZUK.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"],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["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"]}:{},...argv["managed-runtime-broker-url"]!==void 0?{managedRuntimeBrokerUrl:argv["managed-runtime-broker-url"]}:{},...argv["managed-runtime-broker-token"]!==void 0?{managedRuntimeBrokerToken:argv["managed-runtime-broker-token"]}:{},...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-FVXQH3JA.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-LE7P72FR.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,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{TaskStopTool}from"./chunk-IDMI4UMG.js";import{WriteFileTool}from"./chunk-P7DIAJNX.js";import{EditTool}from"./chunk-KWRZ3WJO.js";import{GlobTool}from"./chunk-6OP7FXSJ.js";import{GrepTool}from"./chunk-A5DPNEBH.js";import{LSTool}from"./chunk-XUQ73TBA.js";import{NotebookEditTool}from"./chunk-QTMHQGWQ.js";import{ShellTool,isModifiableDeclarativeTool}from"./chunk-RKPHDO42.js";import{stableJson}from"./chunk-JUPGJYC2.js";import{ReadFileTool}from"./chunk-DR3HLUJ5.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat}from"node:fs/promises";function createExecutionTools(config){const tools=[new ReadFileTool(config),new WriteFileTool(config),new EditTool(config),new NotebookEditTool(config),new GlobTool(config),new GrepTool(config),new LSTool(config),new ShellTool(config),new TaskStopTool(config)];return new Map(tools.map(tool=>[tool.name,tool]))}__name(createExecutionTools,"createExecutionTools");var LocalExecutionEnvironment=class{constructor(config,options={}){this.config=config;this.toolNames=options.toolNames;this.run=options.run;this.tools=createExecutionTools(config);if(options.toolNames){for(const name of this.tools.keys()){if(!options.toolNames.has(name))this.tools.delete(name)}}}static{__name(this,"LocalExecutionEnvironment")}toolNames;tools;invocations=new Map;controllers=new Set;run;disposed=false;tool(name){if(this.disposed)throw new Error("Execution environment is disposed.");const tool=this.tools.get(name);if(!tool)throw new Error(`Unsupported execution tool: ${name}`);return tool}pending(id){if(this.disposed)throw new Error("Execution environment is disposed.");const pending=this.invocations.get(id);if(!pending)throw new Error(`Unknown execution invocation: ${id}`);if(pending.executing)throw new Error(`Invocation is executing: ${id}`);return pending}toolDefinition(name){const{name:toolName,description,parametersJsonSchema}=this.tool(name).schema;return{name:toolName,description,parametersJsonSchema}}async prepare(request,signal){signal.throwIfAborted();const tool=this.tool(request.toolName);if(this.invocations.has(request.id))throw new Error(`Duplicate invocation: ${request.id}`);if(this.invocations.size>=256)throw new Error("Too many pending execution invocations.");let params=structuredClone(request.params);if(request.modification){if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");params=tool.getModifyContext(signal).createUpdatedParams(request.modification.oldContent,request.modification.newContent,params)}const invocation=tool.build(params);this.invocations.set(request.id,{toolName:request.toolName,invocation,executing:false,...request.callId===void 0?{}:{callId:request.callId}});return{params:invocation.params,description:invocation.getDescription(),locations:invocation.toolLocations()}}async permission(id,signal){signal.throwIfAborted();return this.pending(id).invocation.getDefaultPermission(signal)}async confirmation(id,signal){signal.throwIfAborted();const pending=this.pending(id);const details=await pending.invocation.getConfirmationDetails(signal);pending.confirmation=details;const{onConfirm:_onConfirm,...serializable}=details;return serializable}async confirm(id,outcome,payload,signal){signal.throwIfAborted();const pending=this.pending(id);await pending.confirmation?.onConfirm(outcome,payload);if(outcome==="cancel")this.invocations.delete(id)}async execute(id,signal,updateOutput){signal.throwIfAborted();const pending=this.pending(id);pending.executing=true;const controller=new AbortController;const abort=__name(()=>controller.abort(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});this.controllers.add(controller);try{if(this.run){const params=structuredClone(pending.invocation.params);const rebuilt=this.tool(pending.toolName).build(structuredClone(params)).params;if(stableJson(rebuilt)!==stableJson(params)){throw new Error("The approved parameters change when the tool builds them again; the call did not run.")}return await this.run({id,toolName:pending.toolName,params,...pending.callId===void 0?{}:{callId:pending.callId}},controller.signal,updateOutput)}return await pending.invocation.execute(controller.signal,updateOutput,{...this.config.getShellExecutionConfig(),streamBufferedOutput:true})}finally{signal.removeEventListener("abort",abort);this.controllers.delete(controller);this.invocations.delete(id)}}async modificationContent(toolName,params,signal){signal.throwIfAborted();const tool=this.tool(toolName);if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");const context=tool.getModifyContext(signal);const current=await context.getCurrentContent(params);const proposed=await context.getProposedContent(params);return{current,proposed}}async release(id,signal){signal.throwIfAborted();if(!this.invocations.get(id)?.executing)this.invocations.delete(id)}async invalidateReadCache(paths){const cache=this.config.getFileReadCache();if(!paths){cache.clear();return}await Promise.all(paths.map(async filePath=>{const stats=await stat(filePath).catch(()=>void 0);if(!stats||!cache.markReadEvictedFromHistory(stats))cache.invalidateByPath(filePath)}))}async dispose(){this.disposed=true;for(const controller of this.controllers)controller.abort();this.config.getBackgroundShellRegistry().abortAll();this.invocations.clear();this.tools.clear()}};export{createExecutionTools,LocalExecutionEnvironment};
3
+ import{TaskStopTool}from"./chunk-IDMI4UMG.js";import{WriteFileTool}from"./chunk-R7HBR4QQ.js";import{EditTool}from"./chunk-ZP7MTWMR.js";import{GlobTool}from"./chunk-6OP7FXSJ.js";import{GrepTool}from"./chunk-A5DPNEBH.js";import{LSTool}from"./chunk-XUQ73TBA.js";import{NotebookEditTool}from"./chunk-AOMEBVFW.js";import{ShellTool,isModifiableDeclarativeTool}from"./chunk-LDXZT3SG.js";import{stableJson}from"./chunk-JUPGJYC2.js";import{ReadFileTool}from"./chunk-DR3HLUJ5.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat}from"node:fs/promises";function createExecutionTools(config){const tools=[new ReadFileTool(config),new WriteFileTool(config),new EditTool(config),new NotebookEditTool(config),new GlobTool(config),new GrepTool(config),new LSTool(config),new ShellTool(config),new TaskStopTool(config)];return new Map(tools.map(tool=>[tool.name,tool]))}__name(createExecutionTools,"createExecutionTools");var LocalExecutionEnvironment=class{constructor(config,options={}){this.config=config;this.toolNames=options.toolNames;this.run=options.run;this.tools=createExecutionTools(config);if(options.toolNames){for(const name of this.tools.keys()){if(!options.toolNames.has(name))this.tools.delete(name)}}}static{__name(this,"LocalExecutionEnvironment")}toolNames;tools;invocations=new Map;controllers=new Set;run;disposed=false;tool(name){if(this.disposed)throw new Error("Execution environment is disposed.");const tool=this.tools.get(name);if(!tool)throw new Error(`Unsupported execution tool: ${name}`);return tool}pending(id){if(this.disposed)throw new Error("Execution environment is disposed.");const pending=this.invocations.get(id);if(!pending)throw new Error(`Unknown execution invocation: ${id}`);if(pending.executing)throw new Error(`Invocation is executing: ${id}`);return pending}toolDefinition(name){const{name:toolName,description,parametersJsonSchema}=this.tool(name).schema;return{name:toolName,description,parametersJsonSchema}}async prepare(request,signal){signal.throwIfAborted();const tool=this.tool(request.toolName);if(this.invocations.has(request.id))throw new Error(`Duplicate invocation: ${request.id}`);if(this.invocations.size>=256)throw new Error("Too many pending execution invocations.");let params=structuredClone(request.params);if(request.modification){if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");params=tool.getModifyContext(signal).createUpdatedParams(request.modification.oldContent,request.modification.newContent,params)}const invocation=tool.build(params);this.invocations.set(request.id,{toolName:request.toolName,invocation,executing:false,...request.callId===void 0?{}:{callId:request.callId}});return{params:invocation.params,description:invocation.getDescription(),locations:invocation.toolLocations()}}async permission(id,signal){signal.throwIfAborted();return this.pending(id).invocation.getDefaultPermission(signal)}async confirmation(id,signal){signal.throwIfAborted();const pending=this.pending(id);const details=await pending.invocation.getConfirmationDetails(signal);pending.confirmation=details;const{onConfirm:_onConfirm,...serializable}=details;return serializable}async confirm(id,outcome,payload,signal){signal.throwIfAborted();const pending=this.pending(id);await pending.confirmation?.onConfirm(outcome,payload);if(outcome==="cancel")this.invocations.delete(id)}async execute(id,signal,updateOutput){signal.throwIfAborted();const pending=this.pending(id);pending.executing=true;const controller=new AbortController;const abort=__name(()=>controller.abort(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});this.controllers.add(controller);try{if(this.run){const params=structuredClone(pending.invocation.params);const rebuilt=this.tool(pending.toolName).build(structuredClone(params)).params;if(stableJson(rebuilt)!==stableJson(params)){throw new Error("The approved parameters change when the tool builds them again; the call did not run.")}return await this.run({id,toolName:pending.toolName,params,...pending.callId===void 0?{}:{callId:pending.callId}},controller.signal,updateOutput)}return await pending.invocation.execute(controller.signal,updateOutput,{...this.config.getShellExecutionConfig(),streamBufferedOutput:true})}finally{signal.removeEventListener("abort",abort);this.controllers.delete(controller);this.invocations.delete(id)}}async modificationContent(toolName,params,signal){signal.throwIfAborted();const tool=this.tool(toolName);if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");const context=tool.getModifyContext(signal);const current=await context.getCurrentContent(params);const proposed=await context.getProposedContent(params);return{current,proposed}}async release(id,signal){signal.throwIfAborted();if(!this.invocations.get(id)?.executing)this.invocations.delete(id)}async invalidateReadCache(paths){const cache=this.config.getFileReadCache();if(!paths){cache.clear();return}await Promise.all(paths.map(async filePath=>{const stats=await stat(filePath).catch(()=>void 0);if(!stats||!cache.markReadEvictedFromHistory(stats))cache.invalidateByPath(filePath)}))}async dispose(){this.disposed=true;for(const controller of this.controllers)controller.abort();this.config.getBackgroundShellRegistry().abortAll();this.invocations.clear();this.tools.clear()}};export{createExecutionTools,LocalExecutionEnvironment};
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{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-VTNHPXNL.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-UYYQB2TU.js";import{runStartupRecoveryOnce}from"./chunk-GBFZYVZ4.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-ZBHL2CXR.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-NIOS3B3V.js";import{resolveNetworkTarget}from"./chunk-JKXBHBE3.js";import{isOmniDeliveryActive}from"./chunk-OW4QBRSR.js";import{requireEffectiveOmniUploadConfig}from"./chunk-6QLHJSVW.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{isPermittedRedirect,isPrivateHost}from"./chunk-OW25BC3M.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-P3RLMP7L.js";import{detectRuntime,loadUndici}from"./chunk-ZZZAYAJW.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-HTW7PYHK.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
3
+ import{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-3TBFTELA.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-UYYQB2TU.js";import{runStartupRecoveryOnce}from"./chunk-GBFZYVZ4.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-ZBHL2CXR.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-NIOS3B3V.js";import{resolveNetworkTarget}from"./chunk-JKXBHBE3.js";import{isOmniDeliveryActive}from"./chunk-6UZ65Z2P.js";import{requireEffectiveOmniUploadConfig}from"./chunk-6PWOLWTH.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{isPermittedRedirect,isPrivateHost}from"./chunk-OW25BC3M.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-P3RLMP7L.js";import{detectRuntime,loadUndici}from"./chunk-ZZZAYAJW.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-HTW7PYHK.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC