@qwen-code/qwen-code 0.27.2-preview.0 → 0.27.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/{MaxSizedBox-XGJBXFET.js → MaxSizedBox-QRQEXRXW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-BNFJWFLQ.js → StandaloneSessionPicker-X274Q6BX.js} +1 -1
- package/chunks/{acp-subagent-executor-P5FBYPD5.js → acp-subagent-executor-YIFQD4LJ.js} +1 -1
- package/chunks/{acpAgent-J6G57ZCE.js → acpAgent-NW4XNW7P.js} +3 -3
- package/chunks/{advisor-3O63GFOM.js → advisor-W7KCVPBR.js} +1 -1
- package/chunks/{agent-ALZEISY2.js → agent-FGDWPNXW.js} +1 -1
- package/chunks/{agent-headless-XAKKB6OT.js → agent-headless-7KA3VVAB.js} +1 -1
- package/chunks/{agent-host-client-DIV2XAL5.js → agent-host-client-YZJLSOLB.js} +1 -1
- package/chunks/{agent-host-connections-ZQUMCO2F.js → agent-host-connections-5JGDPG3L.js} +1 -1
- package/chunks/{anthropicContentGenerator-ZE7TAQPO.js → anthropicContentGenerator-QUXJVJ3I.js} +1 -1
- package/chunks/{autofix-pr-RZ4PWQ46.js → autofix-pr-UDRPJC7L.js} +1 -1
- package/chunks/{batch-AIMBHUMX.js → batch-GCEHGR5P.js} +1 -1
- package/chunks/{bridge-A3RRGPEI.js → bridge-JY2JXNVV.js} +1 -1
- package/chunks/{channel-settings-store-P3KM5GTN.js → channel-settings-store-EX6ZU6R3.js} +1 -1
- package/chunks/{chunk-P22U5UQR.js → chunk-27MJJU2I.js} +1 -1
- package/chunks/{chunk-RYRMDOIX.js → chunk-2LDABIAY.js} +3 -3
- package/chunks/{chunk-MYPEVUKI.js → chunk-2QZDPMIH.js} +1 -1
- package/chunks/{chunk-TW2REHPX.js → chunk-2SGTJMSU.js} +1 -1
- package/chunks/{chunk-NCW3NPS5.js → chunk-3BHXPXCC.js} +1 -1
- package/chunks/{chunk-XUB4JKSR.js → chunk-3NR3JBMA.js} +6 -6
- package/chunks/{chunk-NRJOUWP4.js → chunk-3QCFMVI6.js} +1 -1
- package/chunks/{chunk-EGMV4S6D.js → chunk-3YOERSU5.js} +1 -1
- package/chunks/{chunk-WXKD4L4A.js → chunk-4NIUXYUF.js} +1 -1
- package/chunks/{chunk-YHC27L5W.js → chunk-5FS5OQHO.js} +1 -1
- package/chunks/{chunk-L76RFQKW.js → chunk-5MGG2BGT.js} +1 -1
- package/chunks/{chunk-HHDQ5JAA.js → chunk-66LFVQJP.js} +1 -1
- package/chunks/{chunk-RJPELYUW.js → chunk-6KU7LHBT.js} +1 -1
- package/chunks/{chunk-SKU5J7Q7.js → chunk-6O7CARPF.js} +1 -1
- package/chunks/{chunk-CPOFE42B.js → chunk-6Z3TBTUS.js} +1 -1
- package/chunks/{chunk-HRRQHZQE.js → chunk-73TSS7KS.js} +1 -1
- package/chunks/{chunk-BSGONILH.js → chunk-776L3HAN.js} +1 -1
- package/chunks/{chunk-MZNZYCAC.js → chunk-7BL2OTHX.js} +1 -1
- package/chunks/{chunk-5DPLJQUC.js → chunk-7GYFDPEP.js} +1 -1
- package/chunks/{chunk-OD44AOSX.js → chunk-7KGCNYE4.js} +1 -1
- package/chunks/{chunk-4JLLFT6S.js → chunk-7SX547WS.js} +1 -1
- package/chunks/{chunk-5Q6POUDM.js → chunk-7VIES3RW.js} +1 -1
- package/chunks/{chunk-NMK72ZA4.js → chunk-ABEBQNYK.js} +1 -1
- package/chunks/{chunk-QZ5JBF3E.js → chunk-AD7JBW6R.js} +2 -2
- package/chunks/{chunk-E6XRNALG.js → chunk-AEX3XSTE.js} +1 -1
- package/chunks/{chunk-B7CYUTAO.js → chunk-AKDODQCI.js} +1 -1
- package/chunks/{chunk-EEARSY3D.js → chunk-B3I5LFFK.js} +1 -1
- package/chunks/{chunk-YSGVX6LT.js → chunk-B5Y56PDI.js} +1 -1
- package/chunks/{chunk-MEFN5DY3.js → chunk-BEBKKJP3.js} +1 -1
- package/chunks/{chunk-GYCGVZ32.js → chunk-BFPP7X4E.js} +1 -1
- package/chunks/{chunk-GNWPYWGQ.js → chunk-BY5GX6DQ.js} +1 -1
- package/chunks/{chunk-6W5ZZSQF.js → chunk-CUX3C6QV.js} +1 -1
- package/chunks/{chunk-HXYHIEMH.js → chunk-CXPRHT3E.js} +1 -1
- package/chunks/{chunk-53CWA7N2.js → chunk-D5H5GARR.js} +1 -1
- package/chunks/{chunk-DV67DRNT.js → chunk-DLY7QJ5Y.js} +1 -1
- package/chunks/{chunk-SFDOJ2FF.js → chunk-DN4QKOFL.js} +1 -1
- package/chunks/{chunk-VOAIDOUV.js → chunk-DP4YE24V.js} +1 -1
- package/chunks/{chunk-D2X6A5FH.js → chunk-DQLI7HH7.js} +1 -1
- package/chunks/{chunk-ET7ADS4X.js → chunk-DS2FKATN.js} +1 -1
- package/chunks/{chunk-FRSSRLIO.js → chunk-E6EW43WZ.js} +1 -1
- package/chunks/{chunk-F4AWT5LV.js → chunk-EEBFFC76.js} +1 -1
- package/chunks/{chunk-B7PJ5TNK.js → chunk-EGKUF5NS.js} +2 -2
- package/chunks/{chunk-B2YLVSQE.js → chunk-ERMAKXS3.js} +2 -2
- package/chunks/{chunk-PEZZTKPM.js → chunk-FB73O3E5.js} +1 -1
- package/chunks/{chunk-36DBNBTF.js → chunk-FEIUMWFA.js} +1 -1
- package/chunks/{chunk-YE3LA3U4.js → chunk-FWJKQA2H.js} +1 -1
- package/chunks/{chunk-VDNPMX5W.js → chunk-FZQJOSHD.js} +1 -1
- package/chunks/{chunk-YYSMMFK7.js → chunk-GNI5J2ON.js} +1 -1
- package/chunks/{chunk-6OCKLRQC.js → chunk-H3VGRICV.js} +1 -1
- package/chunks/{chunk-OSLFWRV2.js → chunk-HRTWLOGK.js} +1 -1
- package/chunks/{chunk-XZYQKCTU.js → chunk-IGIZ6AZE.js} +1 -1
- package/chunks/{chunk-RIBVEHUG.js → chunk-IHB7CDQ2.js} +1 -1
- package/chunks/{chunk-LO6OFMFC.js → chunk-IHEGGZBE.js} +1 -1
- package/chunks/{chunk-N5S6SIRO.js → chunk-IMTHBYJP.js} +1 -1
- package/chunks/{chunk-I5F24CVP.js → chunk-IP3K5SRR.js} +1 -1
- package/chunks/{chunk-2FYWJVGW.js → chunk-ISA4MFNT.js} +1 -1
- package/chunks/{chunk-GV3E2RHX.js → chunk-JGF3ND5D.js} +1 -1
- package/chunks/{chunk-ASQ7BSJ4.js → chunk-JJ4UPR4A.js} +1 -1
- package/chunks/{chunk-HOCNE2LO.js → chunk-JTUWFGEB.js} +1 -1
- package/chunks/{chunk-FDQFJFO5.js → chunk-KAN5KUJD.js} +1 -1
- package/chunks/{chunk-K7GCWWTI.js → chunk-KU4F6SSJ.js} +2 -2
- package/chunks/{chunk-QDQQFQB4.js → chunk-LBAINHIN.js} +1 -1
- package/chunks/{chunk-BAPIZCC7.js → chunk-LTJLPYFS.js} +1 -1
- package/chunks/{chunk-ZOUMCSDW.js → chunk-MSNPEQ2I.js} +1 -1
- package/chunks/{chunk-MPDGSR2S.js → chunk-N3YWQWSR.js} +5 -5
- package/chunks/{chunk-VEVQB4CI.js → chunk-NDTPBVER.js} +1 -1
- package/chunks/{chunk-L4WG2XDS.js → chunk-NJ77L3GS.js} +1 -1
- package/chunks/{chunk-U2DX235N.js → chunk-NL62UQDW.js} +1 -1
- package/chunks/{chunk-QASJXL5B.js → chunk-NYXR2655.js} +1 -1
- package/chunks/{chunk-5SPQ5V35.js → chunk-OEPXWKZL.js} +1 -1
- package/chunks/{chunk-EOR7AP7Z.js → chunk-OIKWJN7E.js} +1 -1
- package/chunks/{chunk-BT7V3O75.js → chunk-OIQKVWR7.js} +1 -1
- package/chunks/{chunk-ESXBBANA.js → chunk-OPBSEVFC.js} +1 -1
- package/chunks/{chunk-NW3H676V.js → chunk-P5RBFVMP.js} +1 -1
- package/chunks/{chunk-F7KVMGGZ.js → chunk-QD4KNY2J.js} +1 -1
- package/chunks/{chunk-2ZE6CAZV.js → chunk-RSLBGXPB.js} +1 -1
- package/chunks/{chunk-3R7NEEW7.js → chunk-S542WTV7.js} +1 -1
- package/chunks/{chunk-KXAZ2Z5M.js → chunk-SEK234IM.js} +1 -1
- package/chunks/{chunk-5DPXLL3H.js → chunk-TM6IVXAM.js} +1 -1
- package/chunks/{chunk-KMJLEAS3.js → chunk-TPTV6HPU.js} +1 -1
- package/chunks/{chunk-DCUBMMWG.js → chunk-TQ6FKWSC.js} +1 -1
- package/chunks/{chunk-JK2S74SA.js → chunk-TUBHG6EI.js} +1 -1
- package/chunks/{chunk-FMZ5U7J5.js → chunk-UBPC3F32.js} +1 -1
- package/chunks/{chunk-XB7DJWOJ.js → chunk-UG5B4UOQ.js} +6 -6
- package/chunks/{chunk-36S57YYW.js → chunk-UGWTN5IK.js} +1 -1
- package/chunks/{chunk-SK2DTYBZ.js → chunk-URMRX2MG.js} +1 -1
- package/chunks/{chunk-VB4DB57C.js → chunk-UY6J5CHF.js} +1 -1
- package/chunks/{chunk-STQ3TEZW.js → chunk-VSTQT667.js} +2 -2
- package/chunks/{chunk-SGUUOXLH.js → chunk-WDO33SWR.js} +1 -1
- package/chunks/{chunk-IVXR5JO2.js → chunk-WFJHBU7B.js} +1 -1
- package/chunks/{chunk-BINJRUHZ.js → chunk-XSRHGC5R.js} +1 -1
- package/chunks/{chunk-HN7EGFIP.js → chunk-XVF3FMTM.js} +1 -1
- package/chunks/{chunk-C5X6K67T.js → chunk-XYRNYCRQ.js} +1 -1
- package/chunks/{chunk-HZOPWFFL.js → chunk-YAMLF3SM.js} +1 -1
- package/chunks/{chunk-CMW64XU2.js → chunk-ZEZCRRQC.js} +1 -1
- package/chunks/{chunk-J5W6P7QD.js → chunk-ZF56DRDP.js} +1 -1
- package/chunks/{chunk-LHIEE3A2.js → chunk-ZSPOFXP3.js} +1 -1
- package/chunks/{chunk-Q6CXEN4H.js → chunk-ZZXAOGUV.js} +1 -1
- package/chunks/{codex-subagent-executor-HB3MUCY4.js → codex-subagent-executor-7RAVQBYA.js} +1 -1
- package/chunks/{config-utils-F7OF5UR2.js → config-utils-JFD4RJK3.js} +1 -1
- package/chunks/{contextCommand-Y3KO2FY6.js → contextCommand-U6CD3CW7.js} +1 -1
- package/chunks/{core-runtime-D7DAA5NY.js → core-runtime-ORCZRJ4O.js} +1 -1
- package/chunks/{create-sub-session-2HTWYAP4.js → create-sub-session-57WMU2AE.js} +1 -1
- package/chunks/{cron-create-Y5I6E2X4.js → cron-create-V466MOUE.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-UOBMXOUC.js → daemon-git-worktree-guard-ATD77XOF.js} +1 -1
- package/chunks/{daemon-status-provider-L2225KDS.js → daemon-status-provider-5FVRNMAZ.js} +1 -1
- package/chunks/{daemon-trust-policy-5D52N5GL.js → daemon-trust-policy-6YRQV4ZM.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-RUE25K7A.js → daemon-trust-policy-monitor-QRUOWZQP.js} +1 -1
- package/chunks/{deferred-core-runtime-6BO5DI5B.js → deferred-core-runtime-TXIXMDDH.js} +1 -1
- package/chunks/{edit-B6DKSK3O.js → edit-FNXBINJ3.js} +1 -1
- package/chunks/{enterPlanMode-WVJ3XC3P.js → enterPlanMode-YMLAOTTS.js} +1 -1
- package/chunks/{environment-7WMACN3E.js → environment-RFNJLRF7.js} +1 -1
- package/chunks/{errors-BN73QF2O.js → errors-NHGSZ2BV.js} +1 -1
- package/chunks/{execution-tool-IGDH3MQT.js → execution-tool-L2BF6ZKP.js} +1 -1
- package/chunks/{execution-worker-WWP3JZGV.js → execution-worker-F5B2BI2W.js} +1 -1
- package/chunks/{exitPlanMode-7WHKOTS7.js → exitPlanMode-ZZVBF5V4.js} +1 -1
- package/chunks/{fast-path-B37HGFQO.js → fast-path-TOJYOAD3.js} +1 -1
- package/chunks/{glob-ZRXU5G5X.js → glob-SYPMYU4V.js} +1 -1
- package/chunks/{goal-tools-DQ5IZXCM.js → goal-tools-NOXNXZFR.js} +1 -1
- package/chunks/{handleAutoUpdate-FD7QAG2R.js → handleAutoUpdate-RS6Y2IWS.js} +1 -1
- package/chunks/{i18n-TI3ZCEHR.js → i18n-WWZD25J5.js} +1 -1
- package/chunks/{initializer-SB7P3LRU.js → initializer-YGR4YXAM.js} +1 -1
- package/chunks/{installationInfo-B337C7R4.js → installationInfo-EPURVILN.js} +1 -1
- package/chunks/{interactive-mod-session-OWRMETPP.js → interactive-mod-session-2VSTTHPA.js} +1 -1
- package/chunks/{list-2QKQIEOB.js → list-6JAKVRMZ.js} +1 -1
- package/chunks/{llm-GQ76E4DL.js → llm-V272EOVL.js} +4 -4
- package/chunks/{llm-content-generator-2A23HFLD.js → llm-content-generator-EXMC3NYS.js} +1 -1
- package/chunks/{loadedSettingsAdapter-RGQOA5BG.js → loadedSettingsAdapter-T6W2CKFA.js} +1 -1
- package/chunks/{local-OEBLERSJ.js → local-NUBKA3T2.js} +1 -1
- package/chunks/{local-execution-environment-FT5J4SUH.js → local-execution-environment-WO62QDKJ.js} +1 -1
- package/chunks/{loggingContentGenerator-WC23RZYM.js → loggingContentGenerator-KHRN6S3S.js} +1 -1
- package/chunks/{loop-wakeup-GIIIDUNG.js → loop-wakeup-TTAZMOYH.js} +1 -1
- package/chunks/{manage-memory-E2OAR2RV.js → manage-memory-BKA7QM4N.js} +1 -1
- package/chunks/{managed-execution-engine-CYYNVVP5.js → managed-execution-engine-32BLALNC.js} +1 -1
- package/chunks/{managed-local-serve-TUVNNY7K.js → managed-local-serve-UTJFLZI6.js} +1 -1
- package/chunks/{managed-npm-update-IDRZ32UK.js → managed-npm-update-XPIRAQ47.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-HON7TGY2.js → managed-runtime-attestation-worker-DDU4HUGS.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-OMLX5CTV.js → managed-runtime-bootstrap-7TTCLDQJ.js} +1 -1
- package/chunks/{managed-runtime-session-worker-J3P7WMDW.js → managed-runtime-session-worker-WBYLRXU3.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-LPFPOBTL.js → managed-runtime-ssh-worker-X2U2OK2E.js} +1 -1
- package/chunks/{managed-session-authority-I5OHOM7N.js → managed-session-authority-U76OGS6U.js} +1 -1
- package/chunks/{mcp-CGDIDRDI.js → mcp-UROGTJ3U.js} +1 -1
- package/chunks/{memory-VKXOH5UM.js → memory-M4OF6FV7.js} +1 -1
- package/chunks/{model-call-collection-ZTYFDFBB.js → model-call-collection-TW6Q7SXP.js} +1 -1
- package/chunks/{model-configuration-EXLM4SD3.js → model-configuration-4PJUBAYR.js} +1 -1
- package/chunks/{modelConfigUtils-XDMB6XPY.js → modelConfigUtils-ARMBTDAK.js} +1 -1
- package/chunks/{monitor-LKKCC6MQ.js → monitor-URMSEGAJ.js} +1 -1
- package/chunks/{nonInteractiveCli-J3Z3IZIF.js → nonInteractiveCli-YHOC5KZF.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-UQTMGYN2.js → nonInteractiveToolExecutor-DM5IGBP7.js} +1 -1
- package/chunks/{notebook-edit-JFD2KDI6.js → notebook-edit-3YSG73BK.js} +1 -1
- package/chunks/{omni-CI5JTMPR.js → omni-J6YYWKII.js} +1 -1
- package/chunks/{openaiContentGenerator-YZOV2TQX.js → openaiContentGenerator-UIFSPMTE.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-AHL7V6TE.js → openaiResponsesContentGenerator-U6Q536RZ.js} +1 -1
- package/chunks/{pidfile-ULOUTG67.js → pidfile-WCZE5ONH.js} +1 -1
- package/chunks/{processUtils-XX62FVFO.js → processUtils-3CDEN2GV.js} +1 -1
- package/chunks/{prompt-terminal-ledger-L6CWXBAW.js → prompt-terminal-ledger-VAQC6TC3.js} +1 -1
- package/chunks/{qwenContentGenerator-ZDXJW7EM.js → qwenContentGenerator-RWBGMON6.js} +1 -1
- package/chunks/{reactive-degrade-4OJ7XKSJ.js → reactive-degrade-GOTSVZKO.js} +1 -1
- package/chunks/{read-file-H6I32UZS.js → read-file-WNNTTHL5.js} +1 -1
- package/chunks/{resumeHistoryUtils-CTRMXPKQ.js → resumeHistoryUtils-UAGV4TC3.js} +1 -1
- package/chunks/{review-7SV2M7EL.js → review-JETUJT7N.js} +1 -1
- package/chunks/{ripGrep-Y2TGCQH5.js → ripGrep-OJNMOYPD.js} +1 -1
- package/chunks/{run-qwen-serve-6SWKYY6I.js → run-qwen-serve-BVNSBOLL.js} +1 -1
- package/chunks/{runtime-ITZIIC6D.js → runtime-CERVMTEG.js} +1 -1
- package/chunks/{sandboxConfig-FF2YF3RY.js → sandboxConfig-ZHW3GTMH.js} +1 -1
- package/chunks/{scheduled-tasks-WWPWNM3Y.js → scheduled-tasks-AAB5OESY.js} +1 -1
- package/chunks/{scheduler-ELSUH4GZ.js → scheduler-4ZZA357S.js} +1 -1
- package/chunks/{search-memory-465ZSHKG.js → search-memory-USJ3D7WQ.js} +1 -1
- package/chunks/{send-message-M5JFT3VH.js → send-message-QE2YZZ6M.js} +1 -1
- package/chunks/{serve-VTR7PTK2.js → serve-SX2PK3OZ.js} +1 -1
- package/chunks/{server-5NHPPEPR.js → server-OGTIIX65.js} +3 -3
- package/chunks/{session-HZLRQKEB.js → session-DXORIQDK.js} +1 -1
- package/chunks/{session-attachments-root-LS5Q4OT3.js → session-attachments-root-VHH2OZF6.js} +1 -1
- package/chunks/{session-execution-engine-selector-GS4LJPUU.js → session-execution-engine-selector-5WKZ6WXX.js} +1 -1
- package/chunks/{session-pr-refresh-FKYCCTWD.js → session-pr-refresh-MHXNT44I.js} +1 -1
- package/chunks/{sessionService-XUBKN4CM.js → sessionService-QDDGXOB7.js} +1 -1
- package/chunks/{settings-BFTTGWJN.js → settings-W3ALYJZM.js} +1 -1
- package/chunks/{shell-YEUMIQVE.js → shell-YROF2KXZ.js} +1 -1
- package/chunks/{skill-2MJ7S5SK.js → skill-CBEQAUIQ.js} +1 -1
- package/chunks/{skill-settings-DP7A2GMB.js → skill-settings-YRN4SHJO.js} +1 -1
- package/chunks/{spawnChannel-3IZ7S6U7.js → spawnChannel-M7Q6URLT.js} +1 -1
- package/chunks/{standalone-update-NAI3OI3P.js → standalone-update-WIRHMWE6.js} +1 -1
- package/chunks/{start-opentui-ui-D6ETKJSG.js → start-opentui-ui-OLHWNKCY.js} +1 -1
- package/chunks/{startInteractiveUI-FR5ZT72L.js → startInteractiveUI-KCHCIQWO.js} +1 -1
- package/chunks/{subscription-content-generator-JHU5YG2L.js → subscription-content-generator-YQLQKG6S.js} +1 -1
- package/chunks/{team-create-ZW3NXJ2M.js → team-create-I432CHIX.js} +1 -1
- package/chunks/{team-plan-approval-GPFOKUEV.js → team-plan-approval-APMPMLXS.js} +1 -1
- package/chunks/{terminal-image-renderer-WTEEKRMJ.js → terminal-image-renderer-3BNICGAX.js} +1 -1
- package/chunks/{theme-manager-STF74SF2.js → theme-manager-6KY7Q4ZR.js} +1 -1
- package/chunks/{tool-call-TVX5UHRJ.js → tool-call-QGOVXOVJ.js} +1 -1
- package/chunks/{tool-result-media-QALAETZ4.js → tool-result-media-LRSYJOND.js} +1 -1
- package/chunks/{tool-search-ZGJEYTBI.js → tool-search-HXP25AWV.js} +1 -1
- package/chunks/{total-session-admission-BOYLCRYA.js → total-session-admission-ISTRHUQ7.js} +1 -1
- package/chunks/{trustedFolders-65OZWLQO.js → trustedFolders-5BXMWMYB.js} +1 -1
- package/chunks/{update-relaunch-4LJ3SY6L.js → update-relaunch-NYGYYLSC.js} +1 -1
- package/chunks/{updateCheck-2QOAKEIH.js → updateCheck-UBLS3LUD.js} +1 -1
- package/chunks/{upload-config-5N7UDWC6.js → upload-config-Y372LVXX.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-V37CGGMF.js → useAutoAcceptIndicator-RXZJRU74.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-6ZTVWZ6W.js → validateNonInterActiveAuth-2GJ4ICJ3.js} +1 -1
- package/chunks/{version-EO3VIRH6.js → version-XRSNVEB2.js} +1 -1
- package/chunks/{web-fetch-B6LNZ2YK.js → web-fetch-B4VFVGWW.js} +1 -1
- package/chunks/{web-search-VIPZWUJX.js → web-search-3DSQWMAV.js} +1 -1
- package/chunks/{workflow-W5QEAOGN.js → workflow-RCCH5FPV.js} +1 -1
- package/chunks/{workflow-ancestor-trust-VE7B4RD2.js → workflow-ancestor-trust-N3QYH3OL.js} +1 -1
- package/chunks/{workspace-agents-D32D3K5S.js → workspace-agents-KEV4VBZD.js} +1 -1
- package/chunks/{workspace-providers-status-BOH7RJPV.js → workspace-providers-status-HW4VI4T7.js} +1 -1
- package/chunks/{workspace-recovery-worker-53GJWYJ5.js → workspace-recovery-worker-C3SSJ64A.js} +1 -1
- package/chunks/{workspace-registration-store-BMX2NT45.js → workspace-registration-store-K7VEBHIU.js} +1 -1
- package/chunks/{workspace-registry-SS2NKLEL.js → workspace-registry-C5ZPYT4P.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-7ZKVLJDC.js → workspace-runtime-coordinator-ALWOLW3N.js} +1 -1
- package/chunks/{workspace-service-GIUD3D25.js → workspace-service-TNZJAC7M.js} +1 -1
- package/chunks/{workspace-skills-status-36A76TDX.js → workspace-skills-status-TI763F5M.js} +1 -1
- package/chunks/{workspace-trust-reconciler-VKKSY2AR.js → workspace-trust-reconciler-6UQ7HSUG.js} +1 -1
- package/chunks/{write-file-43JOGU55.js → write-file-2XXEHBZR.js} +1 -1
- package/chunks/{zoom-image-USUXATDM.js → zoom-image-P3E3V6PQ.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/package.json +3 -3
- package/web-shell/assets/{PierreFilePreview-Dx075_VT.js → PierreFilePreview-DtTOu9VE.js} +1 -1
- package/web-shell/assets/{SpreadsheetPreview-l2R-Y1o6.js → SpreadsheetPreview-C21imJIX.js} +1 -1
- package/web-shell/assets/{WorkspaceFileBrowser-CGi_eR1a.js → WorkspaceFileBrowser-DIWHfhtl.js} +1 -1
- package/web-shell/assets/{abnfDiagram-VCTEODGH-DZPHyWbH.js → abnfDiagram-VCTEODGH-qffA9juk.js} +1 -1
- package/web-shell/assets/{agents-route-Bp0Yjhm4.js → agents-route-4f6fKJaY.js} +1 -1
- package/web-shell/assets/{arc-BAS_Ct0z.js → arc-BOZg4dn0.js} +1 -1
- package/web-shell/assets/{architectureDiagram-5GKGNRK7-C5a7ooE1.js → architectureDiagram-5GKGNRK7-BOYWC6dJ.js} +1 -1
- package/web-shell/assets/{blockDiagram-NRAW4CY4-D-Wzzi9Z.js → blockDiagram-NRAW4CY4-CiN_IMJ7.js} +1 -1
- package/web-shell/assets/{c4Diagram-UCG6FXSJ-BiYnmYkI.js → c4Diagram-UCG6FXSJ-WYLA0JW0.js} +1 -1
- package/web-shell/assets/channel-DtcoR96T.js +1 -0
- package/web-shell/assets/{chunk-2Q5K7J3B-DHi3a_yf.js → chunk-2Q5K7J3B-BZUPB745.js} +1 -1
- package/web-shell/assets/{chunk-5VM5RSS4-DKgiHWPM.js → chunk-5VM5RSS4-BHfjsu8x.js} +1 -1
- package/web-shell/assets/{chunk-F27PBJKO-qvFMzdl_.js → chunk-F27PBJKO-DHtQsOyA.js} +1 -1
- package/web-shell/assets/{chunk-G27WJ6UU-C9Apl4Df.js → chunk-G27WJ6UU-DvEX_QHY.js} +1 -1
- package/web-shell/assets/{chunk-JWPE2WC7-ManrSgDL.js → chunk-JWPE2WC7-CwQJmw1a.js} +1 -1
- package/web-shell/assets/{chunk-LCL6LL3I-DNZqkjQu.js → chunk-LCL6LL3I-Cv7bRuRV.js} +1 -1
- package/web-shell/assets/{chunk-POPQ4Y6H-CxineRE8.js → chunk-POPQ4Y6H-zGw4PzDB.js} +1 -1
- package/web-shell/assets/{chunk-SVP7TREG-BzmCQ6Bh.js → chunk-SVP7TREG-DZMGVnJg.js} +1 -1
- package/web-shell/assets/{chunk-XXDRQBXY-Dm6Ascgd.js → chunk-XXDRQBXY-Dg5_qrTq.js} +1 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-CBq-DXYQ.js +1 -0
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-CBq-DXYQ.js +1 -0
- package/web-shell/assets/{cose-bilkent-JH36ORCC-Cs-vIewG.js → cose-bilkent-JH36ORCC-D07aXZdD.js} +1 -1
- package/web-shell/assets/{cynefin-OW5HDTMX-CrxyzLrG.js → cynefin-OW5HDTMX-B4txjD0l.js} +1 -1
- package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-Bf7RdtX4.js → cynefinDiagram-5FMLGOSQ-zFtLauJ6.js} +1 -1
- package/web-shell/assets/{dagre-3AP2YEHR-jN7qDhRR.js → dagre-3AP2YEHR-CKZj9zbB.js} +1 -1
- package/web-shell/assets/{diagram-S7CK7UJ4-KcNQ38Ue.js → diagram-S7CK7UJ4-DIsLTku6.js} +1 -1
- package/web-shell/assets/{diagram-UQ7AKVKN-9VmCS0SV.js → diagram-UQ7AKVKN-60CC00CO.js} +1 -1
- package/web-shell/assets/{diagram-VSXAHHWV-D-MA8NCD.js → diagram-VSXAHHWV-BCfHqY7L.js} +1 -1
- package/web-shell/assets/{diagram-VX7I27RA-323tLIBS.js → diagram-VX7I27RA-BbTOx9qC.js} +1 -1
- package/web-shell/assets/{diagram-Z3DM3KII-C547h61H.js → diagram-Z3DM3KII-DLjgnodz.js} +1 -1
- package/web-shell/assets/{docx-preview-DHO0seXT.js → docx-preview-CfGqg6IJ.js} +1 -1
- package/web-shell/assets/{ebnfDiagram-PWID7BFC-DfB8wLF5.js → ebnfDiagram-PWID7BFC-Cf1IQbGo.js} +1 -1
- package/web-shell/assets/{erDiagram-SSCWMZ5O-tzqYkCjp.js → erDiagram-SSCWMZ5O-BTVNpu1y.js} +1 -1
- package/web-shell/assets/{flowDiagram-A5DVABFB-Dsw6uHjD.js → flowDiagram-A5DVABFB-BC404IkJ.js} +1 -1
- package/web-shell/assets/{ganttDiagram-EL5Y4UJY-D1SaF3O0.js → ganttDiagram-EL5Y4UJY-BHP58V1Y.js} +1 -1
- package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D0EzECMT.js → gitGraphDiagram-WWUBYQGX-s1PkjMd4.js} +1 -1
- package/web-shell/assets/{index-ob2Iut7D.js → index-DZnv4pXI.js} +6 -6
- package/web-shell/assets/{index-C-YHF5xI.js → index-YpdTDWts.js} +1 -1
- package/web-shell/assets/{infoDiagram-RXCK75RN-6NnYMmcC.js → infoDiagram-RXCK75RN-DDaQbbGu.js} +1 -1
- package/web-shell/assets/{ishikawaDiagram-5VMMS53U-BnxsfuuS.js → ishikawaDiagram-5VMMS53U-FpQWCzWS.js} +1 -1
- package/web-shell/assets/{journeyDiagram-EYS64GPL-DduswigY.js → journeyDiagram-EYS64GPL-CC5YG1zk.js} +1 -1
- package/web-shell/assets/{kanban-definition-3QL26DDD-D0trNRAQ.js → kanban-definition-3QL26DDD-CsitCmSH.js} +1 -1
- package/web-shell/assets/{layout-nP-pCdd_.js → layout-DR8LNzXS.js} +1 -1
- package/web-shell/assets/{linear-DCw4lqG9.js → linear-Dt61H2xY.js} +1 -1
- package/web-shell/assets/{mermaid.core-DYjTp4Sk.js → mermaid.core-C3SdL30W.js} +6 -6
- package/web-shell/assets/{mindmap-definition-FBJOCRG2-BK9iSa2V.js → mindmap-definition-FBJOCRG2-BjxTLs9R.js} +1 -1
- package/web-shell/assets/{pegDiagram-XKGWAZYB-Dg0TQ1Ty.js → pegDiagram-XKGWAZYB-eBurSwq6.js} +1 -1
- package/web-shell/assets/{pieDiagram-E7YTZNPT-DKeqeVkg.js → pieDiagram-E7YTZNPT-BFWkbtZz.js} +1 -1
- package/web-shell/assets/{quadrantDiagram-AXDQQJYC-C4zBeQXd.js → quadrantDiagram-AXDQQJYC-SThzXP6T.js} +1 -1
- package/web-shell/assets/{railroadDiagram-O6MQD6OU-jDnAGU3z.js → railroadDiagram-O6MQD6OU-D73YId-T.js} +1 -1
- package/web-shell/assets/{requirementDiagram-EFPCY7ZU-D0sIdHq4.js → requirementDiagram-EFPCY7ZU-YecInWjM.js} +1 -1
- package/web-shell/assets/{sankeyDiagram-P5KCCOFB-BFz_QzXx.js → sankeyDiagram-P5KCCOFB-D4Gl35cC.js} +1 -1
- package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-DhDmjiCT.js → sequenceDiagram-WJ2MYXX4-C1JdJSRH.js} +1 -1
- package/web-shell/assets/{sizeCapture-X5ZJPWSS-D8Ov3K_0.js → sizeCapture-X5ZJPWSS-D3mHX34v.js} +1 -1
- package/web-shell/assets/{stateDiagram-HBIQ2CUA-Bb4f1ILo.js → stateDiagram-HBIQ2CUA-BR05d7ll.js} +1 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BBhqVmOU.js +1 -0
- package/web-shell/assets/{swimlanes-XN3QIQJK-CQyilPoS.js → swimlanes-XN3QIQJK-CENq9EQ7.js} +1 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DI8ON7to.js +8 -0
- package/web-shell/assets/{timeline-definition-24CTP7MA-B_CntdLT.js → timeline-definition-24CTP7MA-DFhKdLgc.js} +1 -1
- package/web-shell/assets/{vennDiagram-4TSXK5OY-BbuHkADM.js → vennDiagram-4TSXK5OY-C-p5h-ue.js} +1 -1
- package/web-shell/assets/{wardleyDiagram-VM6X3IG4-0mNKcB-T.js → wardleyDiagram-VM6X3IG4-BCWSjHZH.js} +1 -1
- package/web-shell/assets/{xychartDiagram-S5SC5T6Z-BL-rMOQs.js → xychartDiagram-S5SC5T6Z-DBvE_Y0y.js} +1 -1
- package/web-shell/index.html +1 -1
- package/web-shell/sw.js +1 -1
- package/web-shell/assets/channel-B31dxYCL.js +0 -1
- package/web-shell/assets/classDiagram-DTDB5LWJ-CxU_Ty2M.js +0 -1
- package/web-shell/assets/classDiagram-v2-JRS7N3AN-CxU_Ty2M.js +0 -1
- package/web-shell/assets/stateDiagram-v2-4QOOHH4V-xbht8Czs.js +0 -1
- package/web-shell/assets/swimlanesDiagram-VK2B7HYN-Dz34bASJ.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-DCUBMMWG.js";import{normalizeProjectRoot}from"./chunk-JDZ3UHK5.js";import{loadSettings}from"./chunk-E6XRNALG.js";import{getCurrentLanguage}from"./chunk-HRRQHZQE.js";import{require_strip_json_comments}from"./chunk-EKRCICRK.js";import{isWorkspaceTrusted}from"./chunk-SGUUOXLH.js";import{hashMcpServerConfig}from"./chunk-HXYHIEMH.js";import{Config,ExtensionManager,FileDiscoveryService,MCPOAuthTokenStorage,createMcpClient,createTransport,isGatedMcpScope,runWithTimeout}from"./chunk-XUB4JKSR.js";import{parseBooleanEnvFlag}from"./chunk-6NQMNEZN.js";import{getMCPServerLastError,getMCPServerStatus}from"./chunk-R5AA46IX.js";import{atomicWriteFile}from"./chunk-2GF3E5MI.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();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 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,modelCatalogRefreshEnabled:typeof settings.merged.model?.catalogRefresh==="boolean"?settings.merged.model.catalogRefresh:void 0,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,skipFileWatching:true,skipLlmInitialization: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-TQ6FKWSC.js";import{normalizeProjectRoot}from"./chunk-JDZ3UHK5.js";import{loadSettings}from"./chunk-AEX3XSTE.js";import{getCurrentLanguage}from"./chunk-73TSS7KS.js";import{require_strip_json_comments}from"./chunk-EKRCICRK.js";import{isWorkspaceTrusted}from"./chunk-WDO33SWR.js";import{hashMcpServerConfig}from"./chunk-CXPRHT3E.js";import{Config,ExtensionManager,FileDiscoveryService,MCPOAuthTokenStorage,createMcpClient,createTransport,isGatedMcpScope,runWithTimeout}from"./chunk-3NR3JBMA.js";import{parseBooleanEnvFlag}from"./chunk-6NQMNEZN.js";import{getMCPServerLastError,getMCPServerStatus}from"./chunk-R5AA46IX.js";import{atomicWriteFile}from"./chunk-2GF3E5MI.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();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 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,modelCatalogRefreshEnabled:typeof settings.merged.model?.catalogRefresh==="boolean"?settings.merged.model.catalogRefresh:void 0,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,skipFileWatching:true,skipLlmInitialization: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,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{redactMcpServersSetting,restoreRedactedMcpServersSetting}from"./chunk-44U2VNWI.js";import{safeLogValue}from"./chunk-SVGTUGV2.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeFromParam,sendGenerationClosedError}from"./chunk-J5W6P7QD.js";import{STATUS_SCHEMA_VERSION}from"./chunk-YCAEGUZI.js";import{isServeDebugMode}from"./chunk-CUNEBE5E.js";import{loadSettings}from"./chunk-E6XRNALG.js";import{BuiltinAgentRegistry,SubagentManager}from"./chunk-XUB4JKSR.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{SubagentError,SubagentErrorCode}from"./chunk-AAMQ5CMG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";import{isDeepStrictEqual}from"node:util";var AGENT_TYPE_PATTERN=/^[\p{L}\p{N}_-]+$/u;var AGENT_TYPE_MAX_LENGTH=64;var AGENT_TYPE_MIN_LENGTH=2;var MAX_DESCRIPTION_BYTES=256*1024;var MAX_SYSTEM_PROMPT_BYTES=256*1024;var MAX_TOOLS_ENTRIES=256;var MAX_TOOL_ID_LENGTH=256;var MAX_RECORD_ENTRIES=128;var SUBAGENT_APPROVAL_MODES=[...APPROVAL_MODES,"bubble"];var SUBAGENT_PERMISSION_MODES=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"];var SUBAGENT_COLORS=["auto","red","blue","green","yellow","purple","orange","pink","cyan"];function captureTrustedGeneration(deps,res){const assertGenerationOpen=deps.captureGenerationAssertion?.()??(()=>{});try{assertGenerationOpen()}catch{res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active.",code:"workspace_runtime_unavailable"});return null}if(deps.isWorkspaceTrusted?.()===false){res.status(403).json({error:"Workspace is not trusted.",code:"untrusted_workspace"});return null}return assertGenerationOpen}__name(captureTrustedGeneration,"captureTrustedGeneration");function mountWorkspaceAgentsRoutes(app,deps){const manager=createDaemonSubagentManager(deps.boundWorkspace);app.get("/workspace/agents",async(_req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;try{const agents=await manager.listSubagents({force:true});assertGenerationOpen();const status={v:STATUS_SCHEMA_VERSION,workspaceCwd:deps.boundWorkspace,agents:agents.map(toSummary)};res.status(200).json(status)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to list workspace agents",code:"agent_list_failed"})}});app.post("/workspace/agents",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const scope=body["scope"];if(scope!=="workspace"&&scope!=="global"){res.status(400).json({error:'`scope` must be "workspace" or "global"',code:"invalid_scope"});return}const level=scope==="workspace"?"project":"user";const config=parseAgentConfig(restoreAgentMcpServerSecrets(body,deps.boundWorkspace,level),level,res);if(!config)return;const collision=await manager.loadSubagent(config.name,level);if(collision){res.status(409).json({error:`Subagent "${config.name}" already exists at ${level} level`,code:"agent_already_exists",name:config.name,level});return}try{assertGenerationOpen();await manager.createSubagent(config,{level,assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.ALREADY_EXISTS){res.status(409).json({error:err.message,code:"agent_already_exists",name:err.subagentName??config.name});return}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_CONFIG||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??config.name});return}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??config.name});return}}writeStderrLine(`qwen serve: POST /workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to create workspace agent",code:"agent_create_failed"});return}const created=await manager.loadSubagent(config.name,level);try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!created){writeStderrLine(`qwen serve: agent_create_reload_failed (name=${safeLogValue(config.name)} level=${level}) \u2014 file likely persisted on disk; check \`GET /workspace/agents\` for a phantom entry`);res.status(500).json({error:"Agent creation succeeded but reload failed",code:"agent_create_reload_failed",name:config.name,level});return}deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"created",name:config.name,level},...originatorClientId?{originatorClientId}:{}});res.status(201).json({ok:true,agent:toDetail(created)})});app.post("/workspace/agents/generate",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const description=body["description"];if(typeof description!=="string"||description.trim().length===0){res.status(400).json({error:"`description` must be a non-empty string",code:"invalid_description"});return}if(Buffer.byteLength(description,"utf8")>4096){res.status(400).json({error:"`description` exceeds the 4096-byte limit",code:"invalid_description"});return}try{const generated=await deps.bridge.generateWorkspaceAgent(description.trim(),originatorClientId);assertGenerationOpen();res.status(200).json(generated)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST /workspace/agents/generate failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to generate workspace agent",code:"agent_generate_failed"})}});app.get("/workspace/agents/:agentType",async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;try{const scopedLevel=parseScopeQuery(req,res);if(scopedLevel===null)return;const config=await manager.loadSubagent(agentType,scopedLevel);assertGenerationOpen();if(!config){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}res.status(200).json(toDetail(config))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to read workspace agent",code:"agent_read_failed"})}});app.post("/workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const preferredLevel=parseScopeQuery(req,res);if(preferredLevel===null)return;const existing=await manager.loadSubagent(agentType,preferredLevel);if(!existing){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}if(assertMutableLevel(existing,agentType,res)){return}const body=restoreAgentMcpServerSecrets(deps.safeBody(req),deps.boundWorkspace,existing.level,existing.mcpServers);const updates=parseAgentUpdates(body,res);if(!updates)return;if(Object.keys(updates).length===0){res.status(400).json({error:"`POST /workspace/agents/:agentType` requires at least one updatable field in the body",code:"invalid_config",name:agentType});return}if(isNoOpUpdate(existing,updates)){res.status(200).json({ok:true,agent:toDetail(existing),changed:false});return}try{assertGenerationOpen();await manager.updateSubagent(agentType,updates,existing.level,{assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: POST /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to update workspace agent",code:"agent_update_failed"});return}const updated=await manager.loadSubagent(agentType,existing.level);try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!updated){writeStderrLine(`qwen serve: agent_update_reload_failed (name=${safeLogValue(agentType)} level=${existing.level}) \u2014 disk write completed; check \`GET /workspace/agents/${safeLogValue(agentType)}\` for the new state`);res.status(500).json({error:"Agent update succeeded but reload failed",code:"agent_update_reload_failed",name:agentType,level:existing.level});return}const eventLevel=existing.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"updated",name:existing.name,level:eventLevel},...originatorClientId?{originatorClientId}:{}});res.status(200).json({ok:true,agent:toDetail(updated),changed:true})});app.delete("/workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const scopedLevel=parseScopeQuery(req,res);if(scopedLevel===null)return;const levelsToCheck=scopedLevel?[scopedLevel]:["project","user"];const existingAtLevels=[];for(const lvl of levelsToCheck){const found=await manager.loadSubagent(agentType,lvl);if(found)existingAtLevels.push(found)}for(const found of existingAtLevels){if(assertMutableLevel(found,agentType,res))return}try{assertGenerationOpen();await manager.deleteSubagent(agentType,scopedLevel,void 0,{assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: DELETE /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to delete workspace agent",code:"agent_delete_failed"});return}const removed=[];const remaining=[];for(const found of existingAtLevels){if(!found.filePath){removed.push(found);continue}try{await fs.access(found.filePath);remaining.push(found)}catch{removed.push(found)}}try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(remaining.length>0){writeStderrLine(`qwen serve: DELETE /workspace/agents/${safeLogValue(agentType)} partial \u2014 removed=${removed.map(r=>r.level).join(",")||"none"} remaining=${remaining.map(r=>`${r.level}:${r.filePath}`).join(",")}`);for(const found of removed){const evtLevel=found.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:found.name,level:evtLevel},...originatorClientId?{originatorClientId}:{}})}res.status(500).json({error:`Failed to delete every level of subagent "${agentType}" \u2014 ${remaining.length} level(s) still have their file on disk`,code:"agent_delete_partial",name:agentType,removedLevels:removed.map(r=>r.level),remainingLevels:remaining.map(r=>r.level)});return}if(existingAtLevels.length===0){const fallbackLevel=scopedLevel==="user"?"user":"project";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:agentType,level:fallbackLevel},...originatorClientId?{originatorClientId}:{}})}else{for(const found of removed){const evtLevel=found.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:found.name,level:evtLevel},...originatorClientId?{originatorClientId}:{}})}}res.status(204).end()})}__name(mountWorkspaceAgentsRoutes,"mountWorkspaceAgentsRoutes");function mountWorkspaceQualifiedAgentsRoutes(app,deps){app.get("/workspaces/:workspace/agents",async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);try{const agents=await manager.listSubagents({force:true});runtime.generationGuard?.assertOpen();const status={v:STATUS_SCHEMA_VERSION,workspaceCwd:runtime.workspaceCwd,agents:agents.filter(agent=>agent.level==="project").map(toSummary)};res.status(200).json(status)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspaces/:workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to list workspace agents",code:"agent_list_failed"})}});app.post("/workspaces/:workspace/agents",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const level=parseWorkspaceOnlyAgentBodyScope(body,res);if(level===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const config=parseAgentConfig(restoreAgentMcpServerSecrets(body,runtime.workspaceCwd,level),level,res);if(!config)return;const collision=await manager.loadSubagent(config.name,level);if(collision){res.status(409).json({error:`Subagent "${config.name}" already exists at ${level} level`,code:"agent_already_exists",name:config.name,level});return}try{runtime.generationGuard?.assertOpen();await manager.createSubagent(config,{level,assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(sendCreateAgentError(res,err,config.name))return;writeStderrLine(`qwen serve: POST /workspaces/:workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to create workspace agent",code:"agent_create_failed"});return}const created=await manager.loadSubagent(config.name,level);try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!created){writeStderrLine(`qwen serve: agent_create_reload_failed (name=${safeLogValue(config.name)} level=${level}) \u2014 file likely persisted on disk; check \`GET /workspaces/:workspace/agents\` for a phantom entry`);res.status(500).json({error:"Agent creation succeeded but reload failed",code:"agent_create_reload_failed",name:config.name,level});return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"created",name:config.name,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(201).json({ok:true,agent:toDetail(created)})});app.get("/workspaces/:workspace/agents/:agentType",async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);try{const config=await manager.loadSubagent(agentType,scopedLevel);runtime.generationGuard?.assertOpen();if(!config){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}res.status(200).json(toDetail(config))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to read workspace agent",code:"agent_read_failed"})}});app.post("/workspaces/:workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const existing=await manager.loadSubagent(agentType,scopedLevel);if(!existing){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}if(assertMutableLevel(existing,agentType,res))return;const body=restoreAgentMcpServerSecrets(deps.safeBody(req),runtime.workspaceCwd,existing.level,existing.mcpServers);const updates=parseAgentUpdates(body,res);if(!updates)return;if(Object.keys(updates).length===0){res.status(400).json({error:"`POST /workspaces/:workspace/agents/:agentType` requires at least one updatable field in the body",code:"invalid_config",name:agentType});return}if(isNoOpUpdate(existing,updates)){res.status(200).json({ok:true,agent:toDetail(existing),changed:false});return}try{runtime.generationGuard?.assertOpen();await manager.updateSubagent(agentType,updates,existing.level,{assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(sendUpdateAgentError(res,err,agentType))return;writeStderrLine(`qwen serve: POST /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to update workspace agent",code:"agent_update_failed"});return}const updated=await manager.loadSubagent(agentType,existing.level);try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!updated){writeStderrLine(`qwen serve: agent_update_reload_failed (name=${safeLogValue(agentType)} level=${existing.level}) \u2014 disk write completed; check \`GET /workspaces/:workspace/agents/${safeLogValue(agentType)}\` for the new state`);res.status(500).json({error:"Agent update succeeded but reload failed",code:"agent_update_reload_failed",name:agentType,level:existing.level});return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"updated",name:existing.name,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(200).json({ok:true,agent:toDetail(updated),changed:true})});app.delete("/workspaces/:workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const existing=await manager.loadSubagent(agentType,scopedLevel);if(existing&&assertMutableLevel(existing,agentType,res))return;try{runtime.generationGuard?.assertOpen();await manager.deleteSubagent(agentType,scopedLevel,void 0,{assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to delete workspace agent",code:"agent_delete_failed"});return}if(existing?.filePath){try{await fs.access(existing.filePath);writeStderrLine(`qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} partial \u2014 remaining=${existing.level}:${existing.filePath}`);res.status(500).json({error:`Failed to delete subagent "${agentType}" \u2014 ${existing.level} level still has its file on disk`,code:"agent_delete_partial",name:agentType,removedLevels:[],remainingLevels:[existing.level]});return}catch{}}try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:existing?.name??agentType,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(204).end()})}__name(mountWorkspaceQualifiedAgentsRoutes,"mountWorkspaceQualifiedAgentsRoutes");function validateAgentType(req,res){const raw=req.params["agentType"];if(!raw||raw.length===0){res.status(400).json({error:"`agentType` path parameter is required",code:"invalid_agent_type"});return null}if(raw.length>AGENT_TYPE_MAX_LENGTH||!AGENT_TYPE_PATTERN.test(raw)){res.status(400).json({error:"`agentType` must contain only letters, numbers, hyphens, or underscores (max 64 chars)",code:"invalid_agent_type",agentType:raw});return null}return raw}__name(validateAgentType,"validateAgentType");function parseScopeQuery(req,res){const raw=req.query["scope"];if(raw===void 0)return void 0;if(typeof raw!=="string"){res.status(400).json({error:'`scope` query must be a single "workspace" or "global" value',code:"invalid_scope"});return null}if(raw!=="workspace"&&raw!=="global"){res.status(400).json({error:'`scope` query must be "workspace" or "global"',code:"invalid_scope"});return null}return raw==="workspace"?"project":"user"}__name(parseScopeQuery,"parseScopeQuery");function assertMutableLevel(found,agentType,res){if(found.isBuiltin||found.level==="builtin"||found.level==="extension"||found.level==="session"){res.status(403).json({error:`Cannot modify ${found.level}-level subagent "${agentType}"`,code:"agent_readonly",name:found.name,level:found.level});return true}return false}__name(assertMutableLevel,"assertMutableLevel");function resolveOriginatorClientId(deps,req,res){const clientId=deps.parseClientId(req,res);if(clientId===null)return null;if(clientId===void 0)return void 0;if(!deps.bridge.knownClientIds().has(clientId)){res.status(400).json({error:`Client id "${clientId}" is not registered for this workspace`,code:"invalid_client_id",clientId});return null}return clientId}__name(resolveOriginatorClientId,"resolveOriginatorClientId");function resolveTrustedWorkspaceAgentRuntime(deps,req,res){const runtime=resolveWorkspaceRuntimeFromParam(deps.workspaceRegistry,req,res);if(!runtime)return void 0;if(!requireTrustedWorkspaceRuntime(runtime,res))return void 0;return runtime}__name(resolveTrustedWorkspaceAgentRuntime,"resolveTrustedWorkspaceAgentRuntime");function workspaceAgentDepsForRuntime(runtime,deps){return{bridge:runtime.bridge,boundWorkspace:runtime.workspaceCwd,mutate:deps.mutate,parseClientId:deps.parseClientId,safeBody:deps.safeBody}}__name(workspaceAgentDepsForRuntime,"workspaceAgentDepsForRuntime");function parseWorkspaceOnlyAgentBodyScope(body,res){const scope=body["scope"];if(scope===void 0||scope==="workspace"||scope==="project"){return"project"}return rejectWorkspaceQualifiedAgentScope(scope,res)}__name(parseWorkspaceOnlyAgentBodyScope,"parseWorkspaceOnlyAgentBodyScope");function parseWorkspaceOnlyAgentScopeQuery(req,res){const raw=req.query["scope"];if(raw===void 0||raw==="workspace"||raw==="project"){return"project"}if(typeof raw!=="string"){res.status(400).json({error:"`scope` query must be a single workspace/project value",code:"invalid_scope"});return null}return rejectWorkspaceQualifiedAgentScope(raw,res)}__name(parseWorkspaceOnlyAgentScopeQuery,"parseWorkspaceOnlyAgentScopeQuery");function rejectWorkspaceQualifiedAgentScope(scope,res){if(scope==="global"||scope==="user"){res.status(400).json({error:"Workspace-qualified agents routes only support workspace/project scope",code:"global_scope_not_supported_for_workspace_route"});return null}res.status(400).json({error:'`scope` must be "workspace" or "project"',code:"invalid_scope"});return null}__name(rejectWorkspaceQualifiedAgentScope,"rejectWorkspaceQualifiedAgentScope");function restoreAgentMcpServerSecrets(body,workspace,level,currentAgentServers){const incoming=body["mcpServers"];if(typeof incoming!=="object"||incoming===null||Array.isArray(incoming)){return body}const settings=loadSettings(workspace);const configuredServers=level==="user"?settings.user.settings.mcpServers??{}:settings.merged.mcpServers??{};return{...body,mcpServers:restoreRedactedMcpServersSetting(incoming,{...configuredServers,...currentAgentServers})}}__name(restoreAgentMcpServerSecrets,"restoreAgentMcpServerSecrets");function sendCreateAgentError(res,err,name){if(!(err instanceof SubagentError))return false;if(err.code===SubagentErrorCode.ALREADY_EXISTS){res.status(409).json({error:err.message,code:"agent_already_exists",name:err.subagentName??name});return true}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_CONFIG||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??name});return true}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??name});return true}return false}__name(sendCreateAgentError,"sendCreateAgentError");function sendUpdateAgentError(res,err,agentType){if(!(err instanceof SubagentError))return false;if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??agentType});return true}return false}__name(sendUpdateAgentError,"sendUpdateAgentError");function parseAgentConfig(body,level,res){if("executionBackend"in body){return sendInvalidConfig(res,"Daemon agents do not support executionBackend.")}const rawName=body["name"];if(typeof rawName!=="string"||rawName.trim().length===0){res.status(422).json({error:"`name` is required and must be a non-empty string",code:"invalid_config"});return void 0}const name=rawName.trim();if(name.length<AGENT_TYPE_MIN_LENGTH||name.length>AGENT_TYPE_MAX_LENGTH||!AGENT_TYPE_PATTERN.test(name)){res.status(422).json({error:`\`name\` must be ${AGENT_TYPE_MIN_LENGTH}-${AGENT_TYPE_MAX_LENGTH} characters of letters, numbers, hyphens, or underscores`,code:"invalid_config",name});return void 0}if(BuiltinAgentRegistry.isBuiltinAgent(name)){res.status(422).json({error:`"${name}" shadows a built-in subagent and cannot be used as a project- or user-level agent name. Choose a different name.`,code:"invalid_config",name});return void 0}const description=body["description"];if(typeof description!=="string"||description.trim().length===0){res.status(422).json({error:"`description` is required and must be a non-empty string",code:"invalid_config"});return void 0}if(Buffer.byteLength(description,"utf8")>MAX_DESCRIPTION_BYTES){res.status(422).json({error:`\`description\` exceeds the ${MAX_DESCRIPTION_BYTES}-byte limit`,code:"invalid_config"});return void 0}const systemPrompt=body["systemPrompt"];if(typeof systemPrompt!=="string"||systemPrompt.trim().length===0){res.status(422).json({error:"`systemPrompt` is required and must be a non-empty string (whitespace only is rejected)",code:"invalid_config"});return void 0}if(Buffer.byteLength(systemPrompt,"utf8")>MAX_SYSTEM_PROMPT_BYTES){res.status(422).json({error:`\`systemPrompt\` exceeds the ${MAX_SYSTEM_PROMPT_BYTES}-byte limit`,code:"invalid_config"});return void 0}const tools=parseStringArray(body["tools"],"tools",res);if(tools===null)return void 0;const disallowedTools=parseStringArray(body["disallowedTools"],"disallowedTools",res);if(disallowedTools===null)return void 0;const config={name,description,systemPrompt,level};if(tools!==void 0)config.tools=tools;if(disallowedTools!==void 0)config.disallowedTools=disallowedTools;if(rejectIfPresentWrongType(body,"model","string",res))return void 0;if(typeof body["model"]==="string"){if(!body["model"].trim()){return sendInvalidConfig(res,"`model` must not be empty when provided")}config.model=body["model"].trim()}if(rejectIfPresentWrongType(body,"color","string",res))return void 0;if(typeof body["color"]==="string"){if(!SUBAGENT_COLORS.includes(body["color"])){return sendInvalidConfig(res,`\`color\` must be one of ${JSON.stringify(SUBAGENT_COLORS)}`)}config.color=body["color"]}if(rejectIfPresentWrongType(body,"approvalMode","string",res)){return void 0}if(typeof body["approvalMode"]==="string"){if(!SUBAGENT_APPROVAL_MODES.includes(body["approvalMode"])){return sendInvalidConfig(res,`\`approvalMode\` must be one of ${JSON.stringify(SUBAGENT_APPROVAL_MODES)}`)}config.approvalMode=body["approvalMode"]}if(rejectIfPresentWrongType(body,"permissionMode","string",res)){return void 0}if(typeof body["permissionMode"]==="string"){if(!SUBAGENT_PERMISSION_MODES.includes(body["permissionMode"])){return sendInvalidConfig(res,`\`permissionMode\` must be one of ${JSON.stringify(SUBAGENT_PERMISSION_MODES)}`)}config.permissionMode=body["permissionMode"]}if("maxTurns"in body){const maxTurns=parseMaxTurns(body["maxTurns"],res);if(maxTurns===null)return void 0;config.maxTurns=maxTurns}if("mcpServers"in body){const mcpServers=parseRecordField(body["mcpServers"],"mcpServers",value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"an object of server names to server configuration objects",res);if(mcpServers===null)return void 0;if(Object.keys(mcpServers).length>0)config.mcpServers=mcpServers}if("hooks"in body){const hooks=parseRecordField(body["hooks"],"hooks",Array.isArray,"an object of hook event names to matcher arrays",res);if(hooks===null)return void 0;if(Object.keys(hooks).length>0)config.hooks=hooks}if(rejectIfPresentWrongType(body,"background","boolean",res)){return void 0}if(typeof body["background"]==="boolean"){config.background=body["background"]}const runConfig=body["runConfig"];if(runConfig!==void 0){const sanitized=sanitizeRunConfig(runConfig,res);if(sanitized===null)return void 0;config.runConfig=sanitized}return config}__name(parseAgentConfig,"parseAgentConfig");function parseAgentUpdates(body,res){if("executionBackend"in body){return sendInvalidConfig(res,"Daemon agents do not support executionBackend.")}const updates={};if("description"in body){const value=body["description"];if(typeof value!=="string"||value.trim().length===0){res.status(422).json({error:"`description` must be a non-empty string (whitespace only is rejected) when provided",code:"invalid_config"});return void 0}if(Buffer.byteLength(value,"utf8")>MAX_DESCRIPTION_BYTES){res.status(422).json({error:`\`description\` exceeds the ${MAX_DESCRIPTION_BYTES}-byte limit`,code:"invalid_config"});return void 0}updates.description=value}if("systemPrompt"in body){const value=body["systemPrompt"];if(typeof value!=="string"||value.trim().length===0){res.status(422).json({error:"`systemPrompt` must be a non-empty string (whitespace only is rejected) when provided",code:"invalid_config"});return void 0}if(Buffer.byteLength(value,"utf8")>MAX_SYSTEM_PROMPT_BYTES){res.status(422).json({error:`\`systemPrompt\` exceeds the ${MAX_SYSTEM_PROMPT_BYTES}-byte limit`,code:"invalid_config"});return void 0}updates.systemPrompt=value}if("tools"in body){const tools=parseStringArray(body["tools"],"tools",res);if(tools===null)return void 0;if(tools!==void 0)updates.tools=tools}if("disallowedTools"in body){const disallowedTools=parseStringArray(body["disallowedTools"],"disallowedTools",res);if(disallowedTools===null)return void 0;if(disallowedTools!==void 0){updates.disallowedTools=disallowedTools}}if(body["model"]===null){updates.model=void 0}else if(rejectIfPresentWrongType(body,"model","string",res)){return void 0}else if(typeof body["model"]==="string"){if(!body["model"].trim()){return sendInvalidConfig(res,"`model` must not be empty when provided")}updates.model=body["model"].trim()}if(body["color"]===null){updates.color=void 0}else if(rejectIfPresentWrongType(body,"color","string",res)){return void 0}else if(typeof body["color"]==="string"){if(!SUBAGENT_COLORS.includes(body["color"])){return sendInvalidConfig(res,`\`color\` must be one of ${JSON.stringify(SUBAGENT_COLORS)}`)}updates.color=body["color"]}if(body["approvalMode"]===null){updates.approvalMode=void 0}else if(rejectIfPresentWrongType(body,"approvalMode","string",res)){return void 0}else if(typeof body["approvalMode"]==="string"){if(!SUBAGENT_APPROVAL_MODES.includes(body["approvalMode"])){return sendInvalidConfig(res,`\`approvalMode\` must be one of ${JSON.stringify(SUBAGENT_APPROVAL_MODES)}`)}updates.approvalMode=body["approvalMode"]}if(body["permissionMode"]===null){updates.permissionMode=void 0}else if(rejectIfPresentWrongType(body,"permissionMode","string",res)){return void 0}else if(typeof body["permissionMode"]==="string"){if(!SUBAGENT_PERMISSION_MODES.includes(body["permissionMode"])){return sendInvalidConfig(res,`\`permissionMode\` must be one of ${JSON.stringify(SUBAGENT_PERMISSION_MODES)}`)}updates.permissionMode=body["permissionMode"]}if("maxTurns"in body){if(body["maxTurns"]===null){updates.maxTurns=void 0}else{const maxTurns=parseMaxTurns(body["maxTurns"],res);if(maxTurns===null)return void 0;updates.maxTurns=maxTurns}}if("mcpServers"in body){const mcpServers=parseRecordField(body["mcpServers"],"mcpServers",value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"an object of server names to server configuration objects",res);if(mcpServers===null)return void 0;updates.mcpServers=mcpServers}if("hooks"in body){const hooks=parseRecordField(body["hooks"],"hooks",Array.isArray,"an object of hook event names to matcher arrays",res);if(hooks===null)return void 0;updates.hooks=hooks}if(rejectIfPresentWrongType(body,"background","boolean",res)){return void 0}if(typeof body["background"]==="boolean"){updates.background=body["background"]}if("runConfig"in body){const sanitized=sanitizeRunConfig(body["runConfig"],res);if(sanitized===null)return void 0;updates.runConfig=sanitized}return updates}__name(parseAgentUpdates,"parseAgentUpdates");function parseStringArray(value,field,res){if(value===void 0)return void 0;if(!Array.isArray(value)||value.some(v=>typeof v!=="string")){res.status(422).json({error:`\`${field}\` must be an array of strings when provided`,code:"invalid_config"});return null}if(value.length>MAX_TOOLS_ENTRIES){res.status(422).json({error:`\`${field}\` exceeds the ${MAX_TOOLS_ENTRIES}-entry limit`,code:"invalid_config"});return null}if(value.some(v=>v.length>MAX_TOOL_ID_LENGTH)){res.status(422).json({error:`\`${field}\` entries must be at most ${MAX_TOOL_ID_LENGTH} characters`,code:"invalid_config"});return null}return value}__name(parseStringArray,"parseStringArray");function sendInvalidConfig(res,error){res.status(422).json({error,code:"invalid_config"});return void 0}__name(sendInvalidConfig,"sendInvalidConfig");function parseMaxTurns(value,res){if(typeof value!=="number"||!Number.isFinite(value)||!Number.isInteger(value)||value<=0){sendInvalidConfig(res,"`maxTurns` must be a positive integer");return null}return value}__name(parseMaxTurns,"parseMaxTurns");function parseRecordField(value,field,isValidEntry,expected,res){if(typeof value!=="object"||value===null||Array.isArray(value)){sendInvalidConfig(res,`\`${field}\` must be ${expected}`);return null}const entries=Object.entries(value);if(entries.length>MAX_RECORD_ENTRIES){sendInvalidConfig(res,`\`${field}\` exceeds the ${MAX_RECORD_ENTRIES}-entry limit`);return null}const output={};for(const[key,entry]of entries){if(!key||key.length>MAX_TOOL_ID_LENGTH||key==="__proto__"||key==="constructor"||key==="prototype"||!isValidEntry(entry)){sendInvalidConfig(res,`\`${field}\` must be ${expected}`);return null}output[key]=entry}return output}__name(parseRecordField,"parseRecordField");function rejectIfPresentWrongType(body,key,expected,res){if(!(key in body))return false;if(typeof body[key]===expected)return false;res.status(422).json({error:`\`${key}\` must be a ${expected} when provided`,code:"invalid_config"});return true}__name(rejectIfPresentWrongType,"rejectIfPresentWrongType");function isNoOpUpdate(existing,updates){if(updates.description!==void 0&&updates.description!==existing.description){return false}if(updates.systemPrompt!==void 0&&updates.systemPrompt!==existing.systemPrompt){return false}if(updates.tools!==void 0&&!shallowArrayEqual(updates.tools,existing.tools)){return false}if(updates.disallowedTools!==void 0&&!shallowArrayEqual(updates.disallowedTools,existing.disallowedTools)){return false}if("model"in updates&&updates.model!==existing.model){return false}if("color"in updates&&updates.color!==existing.color){return false}if("approvalMode"in updates&&updates.approvalMode!==existing.approvalMode){return false}if("permissionMode"in updates&&updates.permissionMode!==existing.permissionMode){return false}if("maxTurns"in updates&&updates.maxTurns!==existing.maxTurns){return false}if(updates.mcpServers!==void 0&&!isDeepStrictEqual(normalizedRecord(updates.mcpServers),normalizedRecord(existing.mcpServers))){return false}if(updates.hooks!==void 0&&!isDeepStrictEqual(normalizedRecord(updates.hooks),normalizedRecord(existing.hooks))){return false}if(updates.background!==void 0&&updates.background!==existing.background){return false}if(updates.runConfig!==void 0){const e=existing.runConfig??{};const u=updates.runConfig;if("max_time_minutes"in u){if(u["max_time_minutes"]!==e["max_time_minutes"])return false}if("max_turns"in u){if(u["max_turns"]!==e["max_turns"])return false}}return true}__name(isNoOpUpdate,"isNoOpUpdate");function normalizedRecord(value){if(!value||Object.keys(value).length===0)return void 0;return normalizeRecordValue(value)}__name(normalizedRecord,"normalizedRecord");function normalizeRecordValue(value){if(Array.isArray(value))return value.map(normalizeRecordValue);if(typeof value!=="object"||value===null)return value;return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0).map(([key,entry])=>[key,normalizeRecordValue(entry)]))}__name(normalizeRecordValue,"normalizeRecordValue");function shallowArrayEqual(a,b){if(a===b)return true;if(!a||!b)return false;if(a.length!==b.length)return false;for(let i=0;i<a.length;i++)if(a[i]!==b[i])return false;return true}__name(shallowArrayEqual,"shallowArrayEqual");function sanitizeRunConfig(raw,res){if(typeof raw!=="object"||raw===null||Array.isArray(raw)){res.status(422).json({error:"`runConfig` must be an object when provided",code:"invalid_config"});return null}const input=raw;const out={};if("max_time_minutes"in input){const v=input["max_time_minutes"];if(typeof v!=="number"||!Number.isFinite(v)||v<=0){res.status(422).json({error:"`runConfig.max_time_minutes` must be a positive finite number when provided",code:"invalid_config"});return null}out["max_time_minutes"]=v}if("max_turns"in input){const v=input["max_turns"];if(typeof v!=="number"||!Number.isFinite(v)||v<=0||!Number.isInteger(v)){res.status(422).json({error:"`runConfig.max_turns` must be a positive integer when provided",code:"invalid_config"});return null}out["max_turns"]=v}return out}__name(sanitizeRunConfig,"sanitizeRunConfig");function toSummary(config){const summary={kind:"agent",name:config.name,description:config.description,level:config.level,isBuiltin:config.isBuiltin===true||config.level==="builtin",hasTools:Array.isArray(config.tools)&&config.tools.length>0};if(config.tools)summary.tools=[...config.tools];if(config.disallowedTools){summary.disallowedTools=[...config.disallowedTools]}if(config.model)summary.model=config.model;if(config.color)summary.color=config.color;if(config.background!==void 0)summary.background=config.background;if(config.approvalMode)summary.approvalMode=config.approvalMode;if(config.permissionMode)summary.permissionMode=config.permissionMode;if(config.maxTurns!==void 0)summary.maxTurns=config.maxTurns;if(config.mcpServers){summary.mcpServerNames=Object.keys(config.mcpServers)}if(config.hooks)summary.hookEvents=Object.keys(config.hooks);if(config.runConfig){const runConfig={};if(typeof config.runConfig.max_time_minutes==="number"){runConfig.max_time_minutes=config.runConfig.max_time_minutes}if(typeof config.runConfig.max_turns==="number"){runConfig.max_turns=config.runConfig.max_turns}summary.runConfig=runConfig}if(config.extensionName)summary.extensionName=config.extensionName;if(config.filePath)summary.filePath=config.filePath;return summary}__name(toSummary,"toSummary");function toDetail(config){const detail={...toSummary(config),systemPrompt:config.systemPrompt};if(config.mcpServers){detail.mcpServers=redactMcpServersSetting(config.mcpServers)}if(config.hooks)detail.hooks=config.hooks;return detail}__name(toDetail,"toDetail");function createDaemonSubagentManager(boundWorkspace,safeMode=false){const stub={getSdkMode:__name(()=>false,"getSdkMode"),getProjectRoot:__name(()=>boundWorkspace,"getProjectRoot"),getActiveExtensions:__name(()=>[],"getActiveExtensions"),isSafeMode:__name(()=>safeMode,"isSafeMode"),getAgentsSettings:__name(()=>({}),"getAgentsSettings")};const guarded=new Proxy(stub,{get(target,prop){if(prop in target){return target[prop]}if(prop==="then")return void 0;throw new Error(`qwen serve workspace agents: SubagentManager touched Config.${String(prop)} which the daemon stub does not implement. Add it to createDaemonSubagentManager and audit safety.`)},has(target,prop){if(prop in target)return true;if(prop==="then")return false;throw new Error(`qwen serve workspace agents: SubagentManager probed Config.${String(prop)} via 'in' check; the daemon stub does not implement it. Add it to createDaemonSubagentManager and audit safety.`)}});return new SubagentManager(guarded)}__name(createDaemonSubagentManager,"createDaemonSubagentManager");export{mountWorkspaceAgentsRoutes,mountWorkspaceQualifiedAgentsRoutes,toSummary,toDetail,createDaemonSubagentManager};
|
|
3
|
+
import{redactMcpServersSetting,restoreRedactedMcpServersSetting}from"./chunk-44U2VNWI.js";import{safeLogValue}from"./chunk-SVGTUGV2.js";import{requireTrustedWorkspaceRuntime,resolveWorkspaceRuntimeFromParam,sendGenerationClosedError}from"./chunk-ZF56DRDP.js";import{STATUS_SCHEMA_VERSION}from"./chunk-YCAEGUZI.js";import{isServeDebugMode}from"./chunk-CUNEBE5E.js";import{loadSettings}from"./chunk-AEX3XSTE.js";import{BuiltinAgentRegistry,SubagentManager}from"./chunk-3NR3JBMA.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{SubagentError,SubagentErrorCode}from"./chunk-AAMQ5CMG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";import{isDeepStrictEqual}from"node:util";var AGENT_TYPE_PATTERN=/^[\p{L}\p{N}_-]+$/u;var AGENT_TYPE_MAX_LENGTH=64;var AGENT_TYPE_MIN_LENGTH=2;var MAX_DESCRIPTION_BYTES=256*1024;var MAX_SYSTEM_PROMPT_BYTES=256*1024;var MAX_TOOLS_ENTRIES=256;var MAX_TOOL_ID_LENGTH=256;var MAX_RECORD_ENTRIES=128;var SUBAGENT_APPROVAL_MODES=[...APPROVAL_MODES,"bubble"];var SUBAGENT_PERMISSION_MODES=["acceptEdits","auto","bypassPermissions","default","dontAsk","plan"];var SUBAGENT_COLORS=["auto","red","blue","green","yellow","purple","orange","pink","cyan"];function captureTrustedGeneration(deps,res){const assertGenerationOpen=deps.captureGenerationAssertion?.()??(()=>{});try{assertGenerationOpen()}catch{res.set("Retry-After","1");res.status(503).json({error:"Workspace runtime is not active.",code:"workspace_runtime_unavailable"});return null}if(deps.isWorkspaceTrusted?.()===false){res.status(403).json({error:"Workspace is not trusted.",code:"untrusted_workspace"});return null}return assertGenerationOpen}__name(captureTrustedGeneration,"captureTrustedGeneration");function mountWorkspaceAgentsRoutes(app,deps){const manager=createDaemonSubagentManager(deps.boundWorkspace);app.get("/workspace/agents",async(_req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;try{const agents=await manager.listSubagents({force:true});assertGenerationOpen();const status={v:STATUS_SCHEMA_VERSION,workspaceCwd:deps.boundWorkspace,agents:agents.map(toSummary)};res.status(200).json(status)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to list workspace agents",code:"agent_list_failed"})}});app.post("/workspace/agents",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const scope=body["scope"];if(scope!=="workspace"&&scope!=="global"){res.status(400).json({error:'`scope` must be "workspace" or "global"',code:"invalid_scope"});return}const level=scope==="workspace"?"project":"user";const config=parseAgentConfig(restoreAgentMcpServerSecrets(body,deps.boundWorkspace,level),level,res);if(!config)return;const collision=await manager.loadSubagent(config.name,level);if(collision){res.status(409).json({error:`Subagent "${config.name}" already exists at ${level} level`,code:"agent_already_exists",name:config.name,level});return}try{assertGenerationOpen();await manager.createSubagent(config,{level,assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.ALREADY_EXISTS){res.status(409).json({error:err.message,code:"agent_already_exists",name:err.subagentName??config.name});return}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_CONFIG||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??config.name});return}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??config.name});return}}writeStderrLine(`qwen serve: POST /workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to create workspace agent",code:"agent_create_failed"});return}const created=await manager.loadSubagent(config.name,level);try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!created){writeStderrLine(`qwen serve: agent_create_reload_failed (name=${safeLogValue(config.name)} level=${level}) \u2014 file likely persisted on disk; check \`GET /workspace/agents\` for a phantom entry`);res.status(500).json({error:"Agent creation succeeded but reload failed",code:"agent_create_reload_failed",name:config.name,level});return}deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"created",name:config.name,level},...originatorClientId?{originatorClientId}:{}});res.status(201).json({ok:true,agent:toDetail(created)})});app.post("/workspace/agents/generate",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const description=body["description"];if(typeof description!=="string"||description.trim().length===0){res.status(400).json({error:"`description` must be a non-empty string",code:"invalid_description"});return}if(Buffer.byteLength(description,"utf8")>4096){res.status(400).json({error:"`description` exceeds the 4096-byte limit",code:"invalid_description"});return}try{const generated=await deps.bridge.generateWorkspaceAgent(description.trim(),originatorClientId);assertGenerationOpen();res.status(200).json(generated)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: POST /workspace/agents/generate failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to generate workspace agent",code:"agent_generate_failed"})}});app.get("/workspace/agents/:agentType",async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;try{const scopedLevel=parseScopeQuery(req,res);if(scopedLevel===null)return;const config=await manager.loadSubagent(agentType,scopedLevel);assertGenerationOpen();if(!config){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}res.status(200).json(toDetail(config))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to read workspace agent",code:"agent_read_failed"})}});app.post("/workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const preferredLevel=parseScopeQuery(req,res);if(preferredLevel===null)return;const existing=await manager.loadSubagent(agentType,preferredLevel);if(!existing){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}if(assertMutableLevel(existing,agentType,res)){return}const body=restoreAgentMcpServerSecrets(deps.safeBody(req),deps.boundWorkspace,existing.level,existing.mcpServers);const updates=parseAgentUpdates(body,res);if(!updates)return;if(Object.keys(updates).length===0){res.status(400).json({error:"`POST /workspace/agents/:agentType` requires at least one updatable field in the body",code:"invalid_config",name:agentType});return}if(isNoOpUpdate(existing,updates)){res.status(200).json({ok:true,agent:toDetail(existing),changed:false});return}try{assertGenerationOpen();await manager.updateSubagent(agentType,updates,existing.level,{assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: POST /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to update workspace agent",code:"agent_update_failed"});return}const updated=await manager.loadSubagent(agentType,existing.level);try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!updated){writeStderrLine(`qwen serve: agent_update_reload_failed (name=${safeLogValue(agentType)} level=${existing.level}) \u2014 disk write completed; check \`GET /workspace/agents/${safeLogValue(agentType)}\` for the new state`);res.status(500).json({error:"Agent update succeeded but reload failed",code:"agent_update_reload_failed",name:agentType,level:existing.level});return}const eventLevel=existing.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"updated",name:existing.name,level:eventLevel},...originatorClientId?{originatorClientId}:{}});res.status(200).json({ok:true,agent:toDetail(updated),changed:true})});app.delete("/workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const assertGenerationOpen=captureTrustedGeneration(deps,res);if(!assertGenerationOpen)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const clientIdResult=resolveOriginatorClientId(deps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const scopedLevel=parseScopeQuery(req,res);if(scopedLevel===null)return;const levelsToCheck=scopedLevel?[scopedLevel]:["project","user"];const existingAtLevels=[];for(const lvl of levelsToCheck){const found=await manager.loadSubagent(agentType,lvl);if(found)existingAtLevels.push(found)}for(const found of existingAtLevels){if(assertMutableLevel(found,agentType,res))return}try{assertGenerationOpen();await manager.deleteSubagent(agentType,scopedLevel,void 0,{assertCanCommit:assertGenerationOpen});assertGenerationOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: DELETE /workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to delete workspace agent",code:"agent_delete_failed"});return}const removed=[];const remaining=[];for(const found of existingAtLevels){if(!found.filePath){removed.push(found);continue}try{await fs.access(found.filePath);remaining.push(found)}catch{removed.push(found)}}try{assertGenerationOpen()}catch(err){sendGenerationClosedError(res,err);return}if(remaining.length>0){writeStderrLine(`qwen serve: DELETE /workspace/agents/${safeLogValue(agentType)} partial \u2014 removed=${removed.map(r=>r.level).join(",")||"none"} remaining=${remaining.map(r=>`${r.level}:${r.filePath}`).join(",")}`);for(const found of removed){const evtLevel=found.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:found.name,level:evtLevel},...originatorClientId?{originatorClientId}:{}})}res.status(500).json({error:`Failed to delete every level of subagent "${agentType}" \u2014 ${remaining.length} level(s) still have their file on disk`,code:"agent_delete_partial",name:agentType,removedLevels:removed.map(r=>r.level),remainingLevels:remaining.map(r=>r.level)});return}if(existingAtLevels.length===0){const fallbackLevel=scopedLevel==="user"?"user":"project";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:agentType,level:fallbackLevel},...originatorClientId?{originatorClientId}:{}})}else{for(const found of removed){const evtLevel=found.level==="project"?"project":"user";deps.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:found.name,level:evtLevel},...originatorClientId?{originatorClientId}:{}})}}res.status(204).end()})}__name(mountWorkspaceAgentsRoutes,"mountWorkspaceAgentsRoutes");function mountWorkspaceQualifiedAgentsRoutes(app,deps){app.get("/workspaces/:workspace/agents",async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);try{const agents=await manager.listSubagents({force:true});runtime.generationGuard?.assertOpen();const status={v:STATUS_SCHEMA_VERSION,workspaceCwd:runtime.workspaceCwd,agents:agents.filter(agent=>agent.level==="project").map(toSummary)};res.status(200).json(status)}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspaces/:workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to list workspace agents",code:"agent_list_failed"})}});app.post("/workspaces/:workspace/agents",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const body=deps.safeBody(req);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const level=parseWorkspaceOnlyAgentBodyScope(body,res);if(level===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const config=parseAgentConfig(restoreAgentMcpServerSecrets(body,runtime.workspaceCwd,level),level,res);if(!config)return;const collision=await manager.loadSubagent(config.name,level);if(collision){res.status(409).json({error:`Subagent "${config.name}" already exists at ${level} level`,code:"agent_already_exists",name:config.name,level});return}try{runtime.generationGuard?.assertOpen();await manager.createSubagent(config,{level,assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(sendCreateAgentError(res,err,config.name))return;writeStderrLine(`qwen serve: POST /workspaces/:workspace/agents failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to create workspace agent",code:"agent_create_failed"});return}const created=await manager.loadSubagent(config.name,level);try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!created){writeStderrLine(`qwen serve: agent_create_reload_failed (name=${safeLogValue(config.name)} level=${level}) \u2014 file likely persisted on disk; check \`GET /workspaces/:workspace/agents\` for a phantom entry`);res.status(500).json({error:"Agent creation succeeded but reload failed",code:"agent_create_reload_failed",name:config.name,level});return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"created",name:config.name,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(201).json({ok:true,agent:toDetail(created)})});app.get("/workspaces/:workspace/agents/:agentType",async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const manager=createDaemonSubagentManager(runtime.workspaceCwd);try{const config=await manager.loadSubagent(agentType,scopedLevel);runtime.generationGuard?.assertOpen();if(!config){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}res.status(200).json(toDetail(config))}catch(err){if(sendGenerationClosedError(res,err))return;writeStderrLine(`qwen serve: GET /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to read workspace agent",code:"agent_read_failed"})}});app.post("/workspaces/:workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const existing=await manager.loadSubagent(agentType,scopedLevel);if(!existing){res.status(404).json({error:`Subagent "${agentType}" not found`,code:"agent_not_found",name:agentType});return}if(assertMutableLevel(existing,agentType,res))return;const body=restoreAgentMcpServerSecrets(deps.safeBody(req),runtime.workspaceCwd,existing.level,existing.mcpServers);const updates=parseAgentUpdates(body,res);if(!updates)return;if(Object.keys(updates).length===0){res.status(400).json({error:"`POST /workspaces/:workspace/agents/:agentType` requires at least one updatable field in the body",code:"invalid_config",name:agentType});return}if(isNoOpUpdate(existing,updates)){res.status(200).json({ok:true,agent:toDetail(existing),changed:false});return}try{runtime.generationGuard?.assertOpen();await manager.updateSubagent(agentType,updates,existing.level,{assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(sendUpdateAgentError(res,err,agentType))return;writeStderrLine(`qwen serve: POST /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to update workspace agent",code:"agent_update_failed"});return}const updated=await manager.loadSubagent(agentType,existing.level);try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}if(!updated){writeStderrLine(`qwen serve: agent_update_reload_failed (name=${safeLogValue(agentType)} level=${existing.level}) \u2014 disk write completed; check \`GET /workspaces/:workspace/agents/${safeLogValue(agentType)}\` for the new state`);res.status(500).json({error:"Agent update succeeded but reload failed",code:"agent_update_reload_failed",name:agentType,level:existing.level});return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"updated",name:existing.name,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(200).json({ok:true,agent:toDetail(updated),changed:true})});app.delete("/workspaces/:workspace/agents/:agentType",deps.mutate({strict:true}),async(req,res)=>{const runtime=resolveTrustedWorkspaceAgentRuntime(deps,req,res);if(!runtime)return;const agentType=validateAgentType(req,res);if(agentType===null)return;const scopedLevel=parseWorkspaceOnlyAgentScopeQuery(req,res);if(scopedLevel===null)return;const routeDeps=workspaceAgentDepsForRuntime(runtime,deps);const clientIdResult=resolveOriginatorClientId(routeDeps,req,res);if(clientIdResult===null)return;const originatorClientId=clientIdResult;const manager=createDaemonSubagentManager(runtime.workspaceCwd);const existing=await manager.loadSubagent(agentType,scopedLevel);if(existing&&assertMutableLevel(existing,agentType,res))return;try{runtime.generationGuard?.assertOpen();await manager.deleteSubagent(agentType,scopedLevel,void 0,{assertCanCommit:__name(()=>runtime.generationGuard?.assertOpen(),"assertCanCommit")});runtime.generationGuard?.assertOpen()}catch(err){if(sendGenerationClosedError(res,err))return;if(err instanceof SubagentError){if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return}}writeStderrLine(`qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} failed: ${err instanceof Error?err.stack??err.message:String(err)}`);res.status(500).json({error:"Failed to delete workspace agent",code:"agent_delete_failed"});return}if(existing?.filePath){try{await fs.access(existing.filePath);writeStderrLine(`qwen serve: DELETE /workspaces/:workspace/agents/${safeLogValue(agentType)} partial \u2014 remaining=${existing.level}:${existing.filePath}`);res.status(500).json({error:`Failed to delete subagent "${agentType}" \u2014 ${existing.level} level still has its file on disk`,code:"agent_delete_partial",name:agentType,removedLevels:[],remainingLevels:[existing.level]});return}catch{}}try{runtime.generationGuard?.assertOpen()}catch(err){sendGenerationClosedError(res,err);return}runtime.bridge.publishWorkspaceEvent({type:"agent_changed",data:{change:"deleted",name:existing?.name??agentType,level:"project"},...originatorClientId?{originatorClientId}:{}});res.status(204).end()})}__name(mountWorkspaceQualifiedAgentsRoutes,"mountWorkspaceQualifiedAgentsRoutes");function validateAgentType(req,res){const raw=req.params["agentType"];if(!raw||raw.length===0){res.status(400).json({error:"`agentType` path parameter is required",code:"invalid_agent_type"});return null}if(raw.length>AGENT_TYPE_MAX_LENGTH||!AGENT_TYPE_PATTERN.test(raw)){res.status(400).json({error:"`agentType` must contain only letters, numbers, hyphens, or underscores (max 64 chars)",code:"invalid_agent_type",agentType:raw});return null}return raw}__name(validateAgentType,"validateAgentType");function parseScopeQuery(req,res){const raw=req.query["scope"];if(raw===void 0)return void 0;if(typeof raw!=="string"){res.status(400).json({error:'`scope` query must be a single "workspace" or "global" value',code:"invalid_scope"});return null}if(raw!=="workspace"&&raw!=="global"){res.status(400).json({error:'`scope` query must be "workspace" or "global"',code:"invalid_scope"});return null}return raw==="workspace"?"project":"user"}__name(parseScopeQuery,"parseScopeQuery");function assertMutableLevel(found,agentType,res){if(found.isBuiltin||found.level==="builtin"||found.level==="extension"||found.level==="session"){res.status(403).json({error:`Cannot modify ${found.level}-level subagent "${agentType}"`,code:"agent_readonly",name:found.name,level:found.level});return true}return false}__name(assertMutableLevel,"assertMutableLevel");function resolveOriginatorClientId(deps,req,res){const clientId=deps.parseClientId(req,res);if(clientId===null)return null;if(clientId===void 0)return void 0;if(!deps.bridge.knownClientIds().has(clientId)){res.status(400).json({error:`Client id "${clientId}" is not registered for this workspace`,code:"invalid_client_id",clientId});return null}return clientId}__name(resolveOriginatorClientId,"resolveOriginatorClientId");function resolveTrustedWorkspaceAgentRuntime(deps,req,res){const runtime=resolveWorkspaceRuntimeFromParam(deps.workspaceRegistry,req,res);if(!runtime)return void 0;if(!requireTrustedWorkspaceRuntime(runtime,res))return void 0;return runtime}__name(resolveTrustedWorkspaceAgentRuntime,"resolveTrustedWorkspaceAgentRuntime");function workspaceAgentDepsForRuntime(runtime,deps){return{bridge:runtime.bridge,boundWorkspace:runtime.workspaceCwd,mutate:deps.mutate,parseClientId:deps.parseClientId,safeBody:deps.safeBody}}__name(workspaceAgentDepsForRuntime,"workspaceAgentDepsForRuntime");function parseWorkspaceOnlyAgentBodyScope(body,res){const scope=body["scope"];if(scope===void 0||scope==="workspace"||scope==="project"){return"project"}return rejectWorkspaceQualifiedAgentScope(scope,res)}__name(parseWorkspaceOnlyAgentBodyScope,"parseWorkspaceOnlyAgentBodyScope");function parseWorkspaceOnlyAgentScopeQuery(req,res){const raw=req.query["scope"];if(raw===void 0||raw==="workspace"||raw==="project"){return"project"}if(typeof raw!=="string"){res.status(400).json({error:"`scope` query must be a single workspace/project value",code:"invalid_scope"});return null}return rejectWorkspaceQualifiedAgentScope(raw,res)}__name(parseWorkspaceOnlyAgentScopeQuery,"parseWorkspaceOnlyAgentScopeQuery");function rejectWorkspaceQualifiedAgentScope(scope,res){if(scope==="global"||scope==="user"){res.status(400).json({error:"Workspace-qualified agents routes only support workspace/project scope",code:"global_scope_not_supported_for_workspace_route"});return null}res.status(400).json({error:'`scope` must be "workspace" or "project"',code:"invalid_scope"});return null}__name(rejectWorkspaceQualifiedAgentScope,"rejectWorkspaceQualifiedAgentScope");function restoreAgentMcpServerSecrets(body,workspace,level,currentAgentServers){const incoming=body["mcpServers"];if(typeof incoming!=="object"||incoming===null||Array.isArray(incoming)){return body}const settings=loadSettings(workspace);const configuredServers=level==="user"?settings.user.settings.mcpServers??{}:settings.merged.mcpServers??{};return{...body,mcpServers:restoreRedactedMcpServersSetting(incoming,{...configuredServers,...currentAgentServers})}}__name(restoreAgentMcpServerSecrets,"restoreAgentMcpServerSecrets");function sendCreateAgentError(res,err,name){if(!(err instanceof SubagentError))return false;if(err.code===SubagentErrorCode.ALREADY_EXISTS){res.status(409).json({error:err.message,code:"agent_already_exists",name:err.subagentName??name});return true}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_CONFIG||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??name});return true}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??name});return true}return false}__name(sendCreateAgentError,"sendCreateAgentError");function sendUpdateAgentError(res,err,agentType){if(!(err instanceof SubagentError))return false;if(err.code===SubagentErrorCode.NOT_FOUND){res.status(404).json({error:err.message,code:"agent_not_found",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.INVALID_CONFIG){res.status(403).json({error:err.message,code:"agent_readonly",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.VALIDATION_ERROR||err.code===SubagentErrorCode.INVALID_NAME||err.code===SubagentErrorCode.TOOL_NOT_FOUND){res.status(422).json({error:err.message,code:"invalid_config",name:err.subagentName??agentType});return true}if(err.code===SubagentErrorCode.FILE_ERROR){const debug=isServeDebugMode();res.status(500).json({error:debug?err.message:"Failed to write workspace agent file",code:"file_error",name:err.subagentName??agentType});return true}return false}__name(sendUpdateAgentError,"sendUpdateAgentError");function parseAgentConfig(body,level,res){if("executionBackend"in body){return sendInvalidConfig(res,"Daemon agents do not support executionBackend.")}const rawName=body["name"];if(typeof rawName!=="string"||rawName.trim().length===0){res.status(422).json({error:"`name` is required and must be a non-empty string",code:"invalid_config"});return void 0}const name=rawName.trim();if(name.length<AGENT_TYPE_MIN_LENGTH||name.length>AGENT_TYPE_MAX_LENGTH||!AGENT_TYPE_PATTERN.test(name)){res.status(422).json({error:`\`name\` must be ${AGENT_TYPE_MIN_LENGTH}-${AGENT_TYPE_MAX_LENGTH} characters of letters, numbers, hyphens, or underscores`,code:"invalid_config",name});return void 0}if(BuiltinAgentRegistry.isBuiltinAgent(name)){res.status(422).json({error:`"${name}" shadows a built-in subagent and cannot be used as a project- or user-level agent name. Choose a different name.`,code:"invalid_config",name});return void 0}const description=body["description"];if(typeof description!=="string"||description.trim().length===0){res.status(422).json({error:"`description` is required and must be a non-empty string",code:"invalid_config"});return void 0}if(Buffer.byteLength(description,"utf8")>MAX_DESCRIPTION_BYTES){res.status(422).json({error:`\`description\` exceeds the ${MAX_DESCRIPTION_BYTES}-byte limit`,code:"invalid_config"});return void 0}const systemPrompt=body["systemPrompt"];if(typeof systemPrompt!=="string"||systemPrompt.trim().length===0){res.status(422).json({error:"`systemPrompt` is required and must be a non-empty string (whitespace only is rejected)",code:"invalid_config"});return void 0}if(Buffer.byteLength(systemPrompt,"utf8")>MAX_SYSTEM_PROMPT_BYTES){res.status(422).json({error:`\`systemPrompt\` exceeds the ${MAX_SYSTEM_PROMPT_BYTES}-byte limit`,code:"invalid_config"});return void 0}const tools=parseStringArray(body["tools"],"tools",res);if(tools===null)return void 0;const disallowedTools=parseStringArray(body["disallowedTools"],"disallowedTools",res);if(disallowedTools===null)return void 0;const config={name,description,systemPrompt,level};if(tools!==void 0)config.tools=tools;if(disallowedTools!==void 0)config.disallowedTools=disallowedTools;if(rejectIfPresentWrongType(body,"model","string",res))return void 0;if(typeof body["model"]==="string"){if(!body["model"].trim()){return sendInvalidConfig(res,"`model` must not be empty when provided")}config.model=body["model"].trim()}if(rejectIfPresentWrongType(body,"color","string",res))return void 0;if(typeof body["color"]==="string"){if(!SUBAGENT_COLORS.includes(body["color"])){return sendInvalidConfig(res,`\`color\` must be one of ${JSON.stringify(SUBAGENT_COLORS)}`)}config.color=body["color"]}if(rejectIfPresentWrongType(body,"approvalMode","string",res)){return void 0}if(typeof body["approvalMode"]==="string"){if(!SUBAGENT_APPROVAL_MODES.includes(body["approvalMode"])){return sendInvalidConfig(res,`\`approvalMode\` must be one of ${JSON.stringify(SUBAGENT_APPROVAL_MODES)}`)}config.approvalMode=body["approvalMode"]}if(rejectIfPresentWrongType(body,"permissionMode","string",res)){return void 0}if(typeof body["permissionMode"]==="string"){if(!SUBAGENT_PERMISSION_MODES.includes(body["permissionMode"])){return sendInvalidConfig(res,`\`permissionMode\` must be one of ${JSON.stringify(SUBAGENT_PERMISSION_MODES)}`)}config.permissionMode=body["permissionMode"]}if("maxTurns"in body){const maxTurns=parseMaxTurns(body["maxTurns"],res);if(maxTurns===null)return void 0;config.maxTurns=maxTurns}if("mcpServers"in body){const mcpServers=parseRecordField(body["mcpServers"],"mcpServers",value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"an object of server names to server configuration objects",res);if(mcpServers===null)return void 0;if(Object.keys(mcpServers).length>0)config.mcpServers=mcpServers}if("hooks"in body){const hooks=parseRecordField(body["hooks"],"hooks",Array.isArray,"an object of hook event names to matcher arrays",res);if(hooks===null)return void 0;if(Object.keys(hooks).length>0)config.hooks=hooks}if(rejectIfPresentWrongType(body,"background","boolean",res)){return void 0}if(typeof body["background"]==="boolean"){config.background=body["background"]}const runConfig=body["runConfig"];if(runConfig!==void 0){const sanitized=sanitizeRunConfig(runConfig,res);if(sanitized===null)return void 0;config.runConfig=sanitized}return config}__name(parseAgentConfig,"parseAgentConfig");function parseAgentUpdates(body,res){if("executionBackend"in body){return sendInvalidConfig(res,"Daemon agents do not support executionBackend.")}const updates={};if("description"in body){const value=body["description"];if(typeof value!=="string"||value.trim().length===0){res.status(422).json({error:"`description` must be a non-empty string (whitespace only is rejected) when provided",code:"invalid_config"});return void 0}if(Buffer.byteLength(value,"utf8")>MAX_DESCRIPTION_BYTES){res.status(422).json({error:`\`description\` exceeds the ${MAX_DESCRIPTION_BYTES}-byte limit`,code:"invalid_config"});return void 0}updates.description=value}if("systemPrompt"in body){const value=body["systemPrompt"];if(typeof value!=="string"||value.trim().length===0){res.status(422).json({error:"`systemPrompt` must be a non-empty string (whitespace only is rejected) when provided",code:"invalid_config"});return void 0}if(Buffer.byteLength(value,"utf8")>MAX_SYSTEM_PROMPT_BYTES){res.status(422).json({error:`\`systemPrompt\` exceeds the ${MAX_SYSTEM_PROMPT_BYTES}-byte limit`,code:"invalid_config"});return void 0}updates.systemPrompt=value}if("tools"in body){const tools=parseStringArray(body["tools"],"tools",res);if(tools===null)return void 0;if(tools!==void 0)updates.tools=tools}if("disallowedTools"in body){const disallowedTools=parseStringArray(body["disallowedTools"],"disallowedTools",res);if(disallowedTools===null)return void 0;if(disallowedTools!==void 0){updates.disallowedTools=disallowedTools}}if(body["model"]===null){updates.model=void 0}else if(rejectIfPresentWrongType(body,"model","string",res)){return void 0}else if(typeof body["model"]==="string"){if(!body["model"].trim()){return sendInvalidConfig(res,"`model` must not be empty when provided")}updates.model=body["model"].trim()}if(body["color"]===null){updates.color=void 0}else if(rejectIfPresentWrongType(body,"color","string",res)){return void 0}else if(typeof body["color"]==="string"){if(!SUBAGENT_COLORS.includes(body["color"])){return sendInvalidConfig(res,`\`color\` must be one of ${JSON.stringify(SUBAGENT_COLORS)}`)}updates.color=body["color"]}if(body["approvalMode"]===null){updates.approvalMode=void 0}else if(rejectIfPresentWrongType(body,"approvalMode","string",res)){return void 0}else if(typeof body["approvalMode"]==="string"){if(!SUBAGENT_APPROVAL_MODES.includes(body["approvalMode"])){return sendInvalidConfig(res,`\`approvalMode\` must be one of ${JSON.stringify(SUBAGENT_APPROVAL_MODES)}`)}updates.approvalMode=body["approvalMode"]}if(body["permissionMode"]===null){updates.permissionMode=void 0}else if(rejectIfPresentWrongType(body,"permissionMode","string",res)){return void 0}else if(typeof body["permissionMode"]==="string"){if(!SUBAGENT_PERMISSION_MODES.includes(body["permissionMode"])){return sendInvalidConfig(res,`\`permissionMode\` must be one of ${JSON.stringify(SUBAGENT_PERMISSION_MODES)}`)}updates.permissionMode=body["permissionMode"]}if("maxTurns"in body){if(body["maxTurns"]===null){updates.maxTurns=void 0}else{const maxTurns=parseMaxTurns(body["maxTurns"],res);if(maxTurns===null)return void 0;updates.maxTurns=maxTurns}}if("mcpServers"in body){const mcpServers=parseRecordField(body["mcpServers"],"mcpServers",value=>typeof value==="object"&&value!==null&&!Array.isArray(value),"an object of server names to server configuration objects",res);if(mcpServers===null)return void 0;updates.mcpServers=mcpServers}if("hooks"in body){const hooks=parseRecordField(body["hooks"],"hooks",Array.isArray,"an object of hook event names to matcher arrays",res);if(hooks===null)return void 0;updates.hooks=hooks}if(rejectIfPresentWrongType(body,"background","boolean",res)){return void 0}if(typeof body["background"]==="boolean"){updates.background=body["background"]}if("runConfig"in body){const sanitized=sanitizeRunConfig(body["runConfig"],res);if(sanitized===null)return void 0;updates.runConfig=sanitized}return updates}__name(parseAgentUpdates,"parseAgentUpdates");function parseStringArray(value,field,res){if(value===void 0)return void 0;if(!Array.isArray(value)||value.some(v=>typeof v!=="string")){res.status(422).json({error:`\`${field}\` must be an array of strings when provided`,code:"invalid_config"});return null}if(value.length>MAX_TOOLS_ENTRIES){res.status(422).json({error:`\`${field}\` exceeds the ${MAX_TOOLS_ENTRIES}-entry limit`,code:"invalid_config"});return null}if(value.some(v=>v.length>MAX_TOOL_ID_LENGTH)){res.status(422).json({error:`\`${field}\` entries must be at most ${MAX_TOOL_ID_LENGTH} characters`,code:"invalid_config"});return null}return value}__name(parseStringArray,"parseStringArray");function sendInvalidConfig(res,error){res.status(422).json({error,code:"invalid_config"});return void 0}__name(sendInvalidConfig,"sendInvalidConfig");function parseMaxTurns(value,res){if(typeof value!=="number"||!Number.isFinite(value)||!Number.isInteger(value)||value<=0){sendInvalidConfig(res,"`maxTurns` must be a positive integer");return null}return value}__name(parseMaxTurns,"parseMaxTurns");function parseRecordField(value,field,isValidEntry,expected,res){if(typeof value!=="object"||value===null||Array.isArray(value)){sendInvalidConfig(res,`\`${field}\` must be ${expected}`);return null}const entries=Object.entries(value);if(entries.length>MAX_RECORD_ENTRIES){sendInvalidConfig(res,`\`${field}\` exceeds the ${MAX_RECORD_ENTRIES}-entry limit`);return null}const output={};for(const[key,entry]of entries){if(!key||key.length>MAX_TOOL_ID_LENGTH||key==="__proto__"||key==="constructor"||key==="prototype"||!isValidEntry(entry)){sendInvalidConfig(res,`\`${field}\` must be ${expected}`);return null}output[key]=entry}return output}__name(parseRecordField,"parseRecordField");function rejectIfPresentWrongType(body,key,expected,res){if(!(key in body))return false;if(typeof body[key]===expected)return false;res.status(422).json({error:`\`${key}\` must be a ${expected} when provided`,code:"invalid_config"});return true}__name(rejectIfPresentWrongType,"rejectIfPresentWrongType");function isNoOpUpdate(existing,updates){if(updates.description!==void 0&&updates.description!==existing.description){return false}if(updates.systemPrompt!==void 0&&updates.systemPrompt!==existing.systemPrompt){return false}if(updates.tools!==void 0&&!shallowArrayEqual(updates.tools,existing.tools)){return false}if(updates.disallowedTools!==void 0&&!shallowArrayEqual(updates.disallowedTools,existing.disallowedTools)){return false}if("model"in updates&&updates.model!==existing.model){return false}if("color"in updates&&updates.color!==existing.color){return false}if("approvalMode"in updates&&updates.approvalMode!==existing.approvalMode){return false}if("permissionMode"in updates&&updates.permissionMode!==existing.permissionMode){return false}if("maxTurns"in updates&&updates.maxTurns!==existing.maxTurns){return false}if(updates.mcpServers!==void 0&&!isDeepStrictEqual(normalizedRecord(updates.mcpServers),normalizedRecord(existing.mcpServers))){return false}if(updates.hooks!==void 0&&!isDeepStrictEqual(normalizedRecord(updates.hooks),normalizedRecord(existing.hooks))){return false}if(updates.background!==void 0&&updates.background!==existing.background){return false}if(updates.runConfig!==void 0){const e=existing.runConfig??{};const u=updates.runConfig;if("max_time_minutes"in u){if(u["max_time_minutes"]!==e["max_time_minutes"])return false}if("max_turns"in u){if(u["max_turns"]!==e["max_turns"])return false}}return true}__name(isNoOpUpdate,"isNoOpUpdate");function normalizedRecord(value){if(!value||Object.keys(value).length===0)return void 0;return normalizeRecordValue(value)}__name(normalizedRecord,"normalizedRecord");function normalizeRecordValue(value){if(Array.isArray(value))return value.map(normalizeRecordValue);if(typeof value!=="object"||value===null)return value;return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0).map(([key,entry])=>[key,normalizeRecordValue(entry)]))}__name(normalizeRecordValue,"normalizeRecordValue");function shallowArrayEqual(a,b){if(a===b)return true;if(!a||!b)return false;if(a.length!==b.length)return false;for(let i=0;i<a.length;i++)if(a[i]!==b[i])return false;return true}__name(shallowArrayEqual,"shallowArrayEqual");function sanitizeRunConfig(raw,res){if(typeof raw!=="object"||raw===null||Array.isArray(raw)){res.status(422).json({error:"`runConfig` must be an object when provided",code:"invalid_config"});return null}const input=raw;const out={};if("max_time_minutes"in input){const v=input["max_time_minutes"];if(typeof v!=="number"||!Number.isFinite(v)||v<=0){res.status(422).json({error:"`runConfig.max_time_minutes` must be a positive finite number when provided",code:"invalid_config"});return null}out["max_time_minutes"]=v}if("max_turns"in input){const v=input["max_turns"];if(typeof v!=="number"||!Number.isFinite(v)||v<=0||!Number.isInteger(v)){res.status(422).json({error:"`runConfig.max_turns` must be a positive integer when provided",code:"invalid_config"});return null}out["max_turns"]=v}return out}__name(sanitizeRunConfig,"sanitizeRunConfig");function toSummary(config){const summary={kind:"agent",name:config.name,description:config.description,level:config.level,isBuiltin:config.isBuiltin===true||config.level==="builtin",hasTools:Array.isArray(config.tools)&&config.tools.length>0};if(config.tools)summary.tools=[...config.tools];if(config.disallowedTools){summary.disallowedTools=[...config.disallowedTools]}if(config.model)summary.model=config.model;if(config.color)summary.color=config.color;if(config.background!==void 0)summary.background=config.background;if(config.approvalMode)summary.approvalMode=config.approvalMode;if(config.permissionMode)summary.permissionMode=config.permissionMode;if(config.maxTurns!==void 0)summary.maxTurns=config.maxTurns;if(config.mcpServers){summary.mcpServerNames=Object.keys(config.mcpServers)}if(config.hooks)summary.hookEvents=Object.keys(config.hooks);if(config.runConfig){const runConfig={};if(typeof config.runConfig.max_time_minutes==="number"){runConfig.max_time_minutes=config.runConfig.max_time_minutes}if(typeof config.runConfig.max_turns==="number"){runConfig.max_turns=config.runConfig.max_turns}summary.runConfig=runConfig}if(config.extensionName)summary.extensionName=config.extensionName;if(config.filePath)summary.filePath=config.filePath;return summary}__name(toSummary,"toSummary");function toDetail(config){const detail={...toSummary(config),systemPrompt:config.systemPrompt};if(config.mcpServers){detail.mcpServers=redactMcpServersSetting(config.mcpServers)}if(config.hooks)detail.hooks=config.hooks;return detail}__name(toDetail,"toDetail");function createDaemonSubagentManager(boundWorkspace,safeMode=false){const stub={getSdkMode:__name(()=>false,"getSdkMode"),getProjectRoot:__name(()=>boundWorkspace,"getProjectRoot"),getActiveExtensions:__name(()=>[],"getActiveExtensions"),isSafeMode:__name(()=>safeMode,"isSafeMode"),getAgentsSettings:__name(()=>({}),"getAgentsSettings")};const guarded=new Proxy(stub,{get(target,prop){if(prop in target){return target[prop]}if(prop==="then")return void 0;throw new Error(`qwen serve workspace agents: SubagentManager touched Config.${String(prop)} which the daemon stub does not implement. Add it to createDaemonSubagentManager and audit safety.`)},has(target,prop){if(prop in target)return true;if(prop==="then")return false;throw new Error(`qwen serve workspace agents: SubagentManager probed Config.${String(prop)} via 'in' check; the daemon stub does not implement it. Add it to createDaemonSubagentManager and audit safety.`)}});return new SubagentManager(guarded)}__name(createDaemonSubagentManager,"createDaemonSubagentManager");export{mountWorkspaceAgentsRoutes,mountWorkspaceQualifiedAgentsRoutes,toSummary,toDetail,createDaemonSubagentManager};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{t}from"./chunk-
|
|
3
|
+
import{t}from"./chunk-73TSS7KS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function formatHistoryGapNotice(_gap){return t("\u26A0\uFE0F History gap: earlier conversation was lost before this point (storage interruption) and could not be recovered.")}__name(formatHistoryGapNotice,"formatHistoryGapNotice");function indexGapsByChild(gaps){const byChild=new Map;for(const gap of gaps??[]){byChild.set(gap.childUuid,gap)}return byChild}__name(indexGapsByChild,"indexGapsByChild");export{formatHistoryGapNotice,indexGapsByChild};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Code
|