@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{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-ACKQAOX7.js";import{t}from"./chunk-HRRQHZQE.js";import{So}from"./chunk-XUB4JKSR.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
|
|
3
|
+
import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-ACKQAOX7.js";import{t}from"./chunk-73TSS7KS.js";import{So}from"./chunk-3NR3JBMA.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
|
|
4
4
|
Original error: ${promoteErr.message}
|
|
5
5
|
Rollback error: ${rollbackErr.message}
|
|
6
6
|
Manual recovery: mv "${oldDir}" "${standaloneDir}"`;throw new Error(detail)}throw promoteErr}return"done"}}__name(atomicReplace,"atomicReplace");function ensureBinWrapper(standaloneDir,target,runtime="node"){const binDir=path.join(path.dirname(standaloneDir),"..","bin");const artifacts={wrapperCreated:false};const{launcher,interpreter,entryPoint}=standaloneRuntimePaths(standaloneDir,target,runtime);const hasLauncher=fs.existsSync(launcher);try{fs.mkdirSync(binDir,{recursive:true});if(target.startsWith("win")){if(UNSAFE_CMD_CHARS.test(standaloneDir)){throw new Error("standaloneDir contains characters unsafe for cmd.exe wrapper")}const wrapperPath=path.join(binDir,"qwen.cmd");artifacts.wrapperPath=wrapperPath;const content=hasLauncher?`@echo off\r
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{getInstallationInfo,getNpmCliPath,getNpmNodePath}from"./chunk-ACKQAOX7.js";import{t}from"./chunk-HRRQHZQE.js";import{getPackageJson}from"./chunk-6KMPLONS.js";import{isBunRuntime}from"./chunk-WGNF7FPC.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);import{execFile}from"node:child_process";import{promisify}from"node:util";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";function npmrcValue(raw){const value=raw.trim();if(value.startsWith('"')&&value.endsWith('"')){try{const parsed=JSON.parse(value);if(typeof parsed==="string")return parsed}catch{return value}}if(value.startsWith("'")&&value.endsWith("'"))return value.slice(1,-1);return value.replace(/\\([\\;#])|[;#].*$/g,(_match,escaped)=>escaped??"").trim()}__name(npmrcValue,"npmrcValue");function expandEnv(value){return value.replace(/(\\*)\$\{([^}]+)\}/g,(match,escapes,name)=>{if(escapes.length%2)return match.slice(1);return escapes+(process.env[name]??`\${${name}}`)})}__name(expandEnv,"expandEnv");function readNpmrc(filename){let content;try{content=fs.readFileSync(filename,"utf8")}catch(error){if(error.code==="ENOENT")return new Map;throw new Error("Unable to read npm registry configuration")}const config=new Map;let inSection=false;for(const line of content.split(/\r?\n/)){if(/^\s*\[/.test(line))inSection=true;if(inSection||/^\s*[;#]/.test(line))continue;const match=line.match(/^\s*([^=]+?)\s*=(.*)$/);if(!match)continue;config.set(expandEnv(npmrcValue(match[1])),expandEnv(npmrcValue(match[2])))}return config}__name(readNpmrc,"readNpmrc");function getGlobalNpmRegistryConfig(packageName){const env=new Map;for(const[key,value]of Object.entries(process.env)){if(!/^npm_config_/i.test(key)||!value)continue;const suffix=key.slice("npm_config_".length);const name=suffix.startsWith("//")?suffix:suffix.toLowerCase().replace(/(?!^)_/g,"-");env.set(expandEnv(name),expandEnv(value.trim()))}const home=os.homedir();const configPath=__name(value=>{if(/^~(?=\/|$)/.test(value)){if(!path.isAbsolute(home)){throw new Error("Cannot resolve npm configuration without an absolute home directory")}value=value.replace(/^~/,home)}return path.resolve(value)},"configPath");const builtin=readNpmrc(path.join(path.dirname(process.execPath),...process.platform==="win32"?["node_modules","npm","npmrc"]:["..","lib","node_modules","npm","npmrc"]));const userConfig=env.get("userconfig")??builtin.get("userconfig")??(path.isAbsolute(home)?path.join(home,".npmrc"):void 0);const user=userConfig?readNpmrc(configPath(userConfig)):new Map;let defaultPrefix=path.dirname(process.execPath);if(process.platform!=="win32"){defaultPrefix=path.dirname(defaultPrefix);if(process.env["DESTDIR"]){defaultPrefix=path.join(process.env["DESTDIR"],defaultPrefix)}}if(process.env["PREFIX"])defaultPrefix=process.env["PREFIX"];const prefix=env.get("prefix")??user.get("prefix")??builtin.get("prefix")??defaultPrefix;const global=readNpmrc(configPath(env.get("globalconfig")??user.get("globalconfig")??builtin.get("globalconfig")??path.join(prefix,"etc","npmrc")));const config=new Map([...builtin,...global,...user,...env]);const scope=packageName.startsWith("@")?packageName.split("/")[0]:void 0;let registry;try{registry=new URL(scope&&config.get(`${scope}:registry`)||config.get("registry")||"https://registry.npmjs.org/")}catch{throw new Error("Invalid npm registry configuration")}if(!["https:","http:"].includes(registry.protocol)||registry.username||registry.password){throw new Error("Invalid npm registry configuration")}if(!registry.pathname.endsWith("/"))registry.pathname+="/";registry.search="";registry.hash="";let authPath=registry.pathname;for(;;){const key=`//${registry.host}${authPath}:`;const token=config.get(`${key}_authToken`);const auth=config.get(`${key}_auth`);const username=config.get(`${key}username`);const password=config.get(`${key}_password`);let authorization;if(token)authorization=`Bearer ${token}`;else if(auth)authorization=`Basic ${auth}`;else if(username&&password){const decodedPassword=Buffer.from(password,"base64").toString("utf8");authorization=`Basic ${Buffer.from(`${username}:${decodedPassword}`).toString("base64")}`}if(authorization){try{new Headers({Authorization:authorization})}catch{throw new Error("Invalid npm registry authentication configuration")}return{registry,authorization}}if(authPath==="")break;authPath=authPath.replace(/([^/]+|\/)$/,"")}return{registry}}__name(getGlobalNpmRegistryConfig,"getGlobalNpmRegistryConfig");var debugLogger=createDebugLogger("UPDATE_CHECK");var FETCH_TIMEOUT_MS=5e3;var UpdateCheckTimeoutError=class extends Error{static{__name(this,"UpdateCheckTimeoutError")}distTag;constructor(timeoutMs,distTag){const suffix=distTag?` for ${distTag}`:"";super(`update check timed out after ${timeoutMs}ms${suffix}`);this.name="UpdateCheckTimeoutError";this.distTag=distTag}};var NETWORK_ERROR_CODES=["ENOTFOUND","ECONNREFUSED","EAI_AGAIN","ETIMEDOUT","ENETUNREACH"];function classifyUpdateCheckError(error){if(error instanceof UpdateCheckTimeoutError)return"timeout";if(error instanceof Error){if(error.name==="TimeoutError")return"timeout";if("killed"in error&&error.killed===true&&"signal"in error&&error.signal==="SIGTERM"){return"timeout"}const errors=[error];if(error.cause instanceof Error)errors.push(error.cause);const matchesCode=__name(code=>errors.some(error2=>error2.code===code||error2.message.includes(code)),"matchesCode");if(NETWORK_ERROR_CODES.some(matchesCode))return"offline"}return"registry"}__name(classifyUpdateCheckError,"classifyUpdateCheckError");function describeUpdateCheckFailure(error,timeoutMs=FETCH_TIMEOUT_MS){switch(classifyUpdateCheckError(error)){case"timeout":return t("registry did not respond within {{seconds}}s",{seconds:String(Math.round(timeoutMs/1e3))});case"offline":return t("registry unreachable");default:return t("registry error")}}__name(describeUpdateCheckFailure,"describeUpdateCheckFailure");async function fetchInfoWithTimeout(notifier,timeoutMs,distTag){let timer;try{return await Promise.race([Promise.resolve(notifier.fetchInfo()),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new UpdateCheckTimeoutError(timeoutMs,distTag)),timeoutMs)})])}finally{if(timer!==void 0)clearTimeout(timer)}}__name(fetchInfoWithTimeout,"fetchInfoWithTimeout");var execFileAsync=promisify(execFile);async function runGlobalNpm(args,run=execFileAsync,platform=process.platform,nodePath=getNpmNodePath(),resolveNpmCliPath=getNpmCliPath){const{stdout}=await run(nodePath,[resolveNpmCliPath(nodePath,platform),...args],{encoding:"utf8",timeout:FETCH_TIMEOUT_MS});return String(stdout).trim()}__name(runGlobalNpm,"runGlobalNpm");async function fetchGlobalNpmUpdateInfo(packageName,currentVersion,distTag,run=execFileAsync){if(isBunRuntime()&&getInstallationInfo("",false).isStandalone){const{registry,authorization}=getGlobalNpmRegistryConfig(packageName);let url=new URL(`-/package/${encodeURIComponent(packageName)}/dist-tags`,registry);const signal=AbortSignal.timeout(FETCH_TIMEOUT_MS);let auth=authorization;let response;for(let redirects=0;;redirects++){response=await fetch(url,{signal,headers:auth?{Authorization:auth}:void 0,redirect:"manual"});if(![301,302,303,307,308].includes(response.status))break;const location=response.headers.get("location");await response.body?.cancel();if(!location||redirects===5){throw new Error("Invalid npm registry redirect")}let next;try{next=new URL(location,url)}catch{throw new Error("Invalid npm registry redirect")}if(!["https:","http:"].includes(next.protocol)||next.username||next.password){throw new Error("Invalid npm registry redirect")}if(next.origin!==url.origin)auth=void 0;url=next}if(!response.ok)throw new Error(`Registry returned HTTP ${response.status}`);const tags=await response.json();if(typeof tags!=="object"||tags===null||Array.isArray(tags)){throw new Error("Invalid registry dist-tags response")}const latest2=Reflect.get(tags,distTag);if(latest2!==void 0&&typeof latest2!=="string"){throw new Error(`Invalid registry ${distTag} version response`)}return{latest:latest2??currentVersion,current:currentVersion,type:"latest",name:packageName}}const output=await runGlobalNpm(["view",packageName,`dist-tags.${distTag}`,"--json","--global"],run);if(output===""){return{latest:currentVersion,current:currentVersion,type:"latest",name:packageName}}const parsed=JSON.parse(output);const latest=typeof parsed==="string"?parsed:Array.isArray(parsed)&&parsed.length===1&&typeof parsed[0]==="string"?parsed[0]:void 0;if(latest===void 0){throw new Error(`Invalid npm ${distTag} version response`)}return{latest,current:currentVersion,type:"latest",name:packageName}}__name(fetchGlobalNpmUpdateInfo,"fetchGlobalNpmUpdateInfo");function getBestAvailableUpdate(nightly,stable){if(!nightly)return stable||null;if(!stable)return nightly||null;const nightlyVer=nightly.latest;const stableVer=stable.latest;if(import_semver.default.coerce(stableVer)?.version===import_semver.default.coerce(nightlyVer)?.version){return nightly}return import_semver.default.gt(stableVer,nightlyVer)?stable:nightly}__name(getBestAvailableUpdate,"getBestAvailableUpdate");async function checkForUpdatesDetailed(fetchGlobalNpm=fetchGlobalNpmUpdateInfo){let currentVersion;try{if(process.env["DEV"]==="true"){return{status:"skipped",reason:"development mode"}}const packageJson=await getPackageJson();if(!packageJson||!packageJson.name||!packageJson.version){return{status:"skipped",reason:"package metadata unavailable"}}const{name,version}=packageJson;currentVersion=version;const isNightly=version.includes("nightly");const createNotifier=__name(distTag=>({fetchInfo:__name(()=>fetchGlobalNpm(name,version,distTag),"fetchInfo")}),"createNotifier");if(isNightly){const[nightlyUpdateInfo,latestUpdateInfo]=await Promise.all([fetchInfoWithTimeout(createNotifier("nightly"),FETCH_TIMEOUT_MS,"nightly"),fetchInfoWithTimeout(createNotifier("latest"),FETCH_TIMEOUT_MS,"latest")]);debugLogger.debug(`fetchInfo returned nightly=${JSON.stringify(nightlyUpdateInfo)} latest=${JSON.stringify(latestUpdateInfo)} for current=${version}`);const bestUpdate=getBestAvailableUpdate(nightlyUpdateInfo,latestUpdateInfo);if(bestUpdate&&import_semver.default.gt(bestUpdate.latest,version)){return{status:"update",info:{message:t("A new version of Qwen Code is available! {{current}} \u2192 {{latest}}",{current:version,latest:bestUpdate.latest}),update:{...bestUpdate,current:version}}}}}else{const updateInfo=await fetchInfoWithTimeout(createNotifier("latest"),FETCH_TIMEOUT_MS,"latest");debugLogger.debug(`fetchInfo returned ${JSON.stringify(updateInfo)} for current=${version}`);if(updateInfo&&import_semver.default.gt(updateInfo.latest,version)){return{status:"update",info:{message:t("Qwen Code update available! {{current}} \u2192 {{latest}}",{current:version,latest:updateInfo.latest}),update:{...updateInfo,current:version}}}}}return{status:"up-to-date",currentVersion:version}}catch(e){const error=e instanceof Error?e:new Error(String(e));debugLogger.warn("Failed to check for updates: "+error);return{status:"error",error,currentVersion}}}__name(checkForUpdatesDetailed,"checkForUpdatesDetailed");async function checkForUpdates(fetchGlobalNpm=fetchGlobalNpmUpdateInfo){const result=await checkForUpdatesDetailed(fetchGlobalNpm);return result.status==="update"?result.info:null}__name(checkForUpdates,"checkForUpdates");export{FETCH_TIMEOUT_MS,UpdateCheckTimeoutError,classifyUpdateCheckError,describeUpdateCheckFailure,runGlobalNpm,fetchGlobalNpmUpdateInfo,checkForUpdatesDetailed,checkForUpdates};
|
|
3
|
+
import{getInstallationInfo,getNpmCliPath,getNpmNodePath}from"./chunk-ACKQAOX7.js";import{t}from"./chunk-73TSS7KS.js";import{getPackageJson}from"./chunk-6KMPLONS.js";import{isBunRuntime}from"./chunk-WGNF7FPC.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_semver=__toESM(require_semver(),1);import{execFile}from"node:child_process";import{promisify}from"node:util";init_esbuild_shims();import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";function npmrcValue(raw){const value=raw.trim();if(value.startsWith('"')&&value.endsWith('"')){try{const parsed=JSON.parse(value);if(typeof parsed==="string")return parsed}catch{return value}}if(value.startsWith("'")&&value.endsWith("'"))return value.slice(1,-1);return value.replace(/\\([\\;#])|[;#].*$/g,(_match,escaped)=>escaped??"").trim()}__name(npmrcValue,"npmrcValue");function expandEnv(value){return value.replace(/(\\*)\$\{([^}]+)\}/g,(match,escapes,name)=>{if(escapes.length%2)return match.slice(1);return escapes+(process.env[name]??`\${${name}}`)})}__name(expandEnv,"expandEnv");function readNpmrc(filename){let content;try{content=fs.readFileSync(filename,"utf8")}catch(error){if(error.code==="ENOENT")return new Map;throw new Error("Unable to read npm registry configuration")}const config=new Map;let inSection=false;for(const line of content.split(/\r?\n/)){if(/^\s*\[/.test(line))inSection=true;if(inSection||/^\s*[;#]/.test(line))continue;const match=line.match(/^\s*([^=]+?)\s*=(.*)$/);if(!match)continue;config.set(expandEnv(npmrcValue(match[1])),expandEnv(npmrcValue(match[2])))}return config}__name(readNpmrc,"readNpmrc");function getGlobalNpmRegistryConfig(packageName){const env=new Map;for(const[key,value]of Object.entries(process.env)){if(!/^npm_config_/i.test(key)||!value)continue;const suffix=key.slice("npm_config_".length);const name=suffix.startsWith("//")?suffix:suffix.toLowerCase().replace(/(?!^)_/g,"-");env.set(expandEnv(name),expandEnv(value.trim()))}const home=os.homedir();const configPath=__name(value=>{if(/^~(?=\/|$)/.test(value)){if(!path.isAbsolute(home)){throw new Error("Cannot resolve npm configuration without an absolute home directory")}value=value.replace(/^~/,home)}return path.resolve(value)},"configPath");const builtin=readNpmrc(path.join(path.dirname(process.execPath),...process.platform==="win32"?["node_modules","npm","npmrc"]:["..","lib","node_modules","npm","npmrc"]));const userConfig=env.get("userconfig")??builtin.get("userconfig")??(path.isAbsolute(home)?path.join(home,".npmrc"):void 0);const user=userConfig?readNpmrc(configPath(userConfig)):new Map;let defaultPrefix=path.dirname(process.execPath);if(process.platform!=="win32"){defaultPrefix=path.dirname(defaultPrefix);if(process.env["DESTDIR"]){defaultPrefix=path.join(process.env["DESTDIR"],defaultPrefix)}}if(process.env["PREFIX"])defaultPrefix=process.env["PREFIX"];const prefix=env.get("prefix")??user.get("prefix")??builtin.get("prefix")??defaultPrefix;const global=readNpmrc(configPath(env.get("globalconfig")??user.get("globalconfig")??builtin.get("globalconfig")??path.join(prefix,"etc","npmrc")));const config=new Map([...builtin,...global,...user,...env]);const scope=packageName.startsWith("@")?packageName.split("/")[0]:void 0;let registry;try{registry=new URL(scope&&config.get(`${scope}:registry`)||config.get("registry")||"https://registry.npmjs.org/")}catch{throw new Error("Invalid npm registry configuration")}if(!["https:","http:"].includes(registry.protocol)||registry.username||registry.password){throw new Error("Invalid npm registry configuration")}if(!registry.pathname.endsWith("/"))registry.pathname+="/";registry.search="";registry.hash="";let authPath=registry.pathname;for(;;){const key=`//${registry.host}${authPath}:`;const token=config.get(`${key}_authToken`);const auth=config.get(`${key}_auth`);const username=config.get(`${key}username`);const password=config.get(`${key}_password`);let authorization;if(token)authorization=`Bearer ${token}`;else if(auth)authorization=`Basic ${auth}`;else if(username&&password){const decodedPassword=Buffer.from(password,"base64").toString("utf8");authorization=`Basic ${Buffer.from(`${username}:${decodedPassword}`).toString("base64")}`}if(authorization){try{new Headers({Authorization:authorization})}catch{throw new Error("Invalid npm registry authentication configuration")}return{registry,authorization}}if(authPath==="")break;authPath=authPath.replace(/([^/]+|\/)$/,"")}return{registry}}__name(getGlobalNpmRegistryConfig,"getGlobalNpmRegistryConfig");var debugLogger=createDebugLogger("UPDATE_CHECK");var FETCH_TIMEOUT_MS=5e3;var UpdateCheckTimeoutError=class extends Error{static{__name(this,"UpdateCheckTimeoutError")}distTag;constructor(timeoutMs,distTag){const suffix=distTag?` for ${distTag}`:"";super(`update check timed out after ${timeoutMs}ms${suffix}`);this.name="UpdateCheckTimeoutError";this.distTag=distTag}};var NETWORK_ERROR_CODES=["ENOTFOUND","ECONNREFUSED","EAI_AGAIN","ETIMEDOUT","ENETUNREACH"];function classifyUpdateCheckError(error){if(error instanceof UpdateCheckTimeoutError)return"timeout";if(error instanceof Error){if(error.name==="TimeoutError")return"timeout";if("killed"in error&&error.killed===true&&"signal"in error&&error.signal==="SIGTERM"){return"timeout"}const errors=[error];if(error.cause instanceof Error)errors.push(error.cause);const matchesCode=__name(code=>errors.some(error2=>error2.code===code||error2.message.includes(code)),"matchesCode");if(NETWORK_ERROR_CODES.some(matchesCode))return"offline"}return"registry"}__name(classifyUpdateCheckError,"classifyUpdateCheckError");function describeUpdateCheckFailure(error,timeoutMs=FETCH_TIMEOUT_MS){switch(classifyUpdateCheckError(error)){case"timeout":return t("registry did not respond within {{seconds}}s",{seconds:String(Math.round(timeoutMs/1e3))});case"offline":return t("registry unreachable");default:return t("registry error")}}__name(describeUpdateCheckFailure,"describeUpdateCheckFailure");async function fetchInfoWithTimeout(notifier,timeoutMs,distTag){let timer;try{return await Promise.race([Promise.resolve(notifier.fetchInfo()),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new UpdateCheckTimeoutError(timeoutMs,distTag)),timeoutMs)})])}finally{if(timer!==void 0)clearTimeout(timer)}}__name(fetchInfoWithTimeout,"fetchInfoWithTimeout");var execFileAsync=promisify(execFile);async function runGlobalNpm(args,run=execFileAsync,platform=process.platform,nodePath=getNpmNodePath(),resolveNpmCliPath=getNpmCliPath){const{stdout}=await run(nodePath,[resolveNpmCliPath(nodePath,platform),...args],{encoding:"utf8",timeout:FETCH_TIMEOUT_MS});return String(stdout).trim()}__name(runGlobalNpm,"runGlobalNpm");async function fetchGlobalNpmUpdateInfo(packageName,currentVersion,distTag,run=execFileAsync){if(isBunRuntime()&&getInstallationInfo("",false).isStandalone){const{registry,authorization}=getGlobalNpmRegistryConfig(packageName);let url=new URL(`-/package/${encodeURIComponent(packageName)}/dist-tags`,registry);const signal=AbortSignal.timeout(FETCH_TIMEOUT_MS);let auth=authorization;let response;for(let redirects=0;;redirects++){response=await fetch(url,{signal,headers:auth?{Authorization:auth}:void 0,redirect:"manual"});if(![301,302,303,307,308].includes(response.status))break;const location=response.headers.get("location");await response.body?.cancel();if(!location||redirects===5){throw new Error("Invalid npm registry redirect")}let next;try{next=new URL(location,url)}catch{throw new Error("Invalid npm registry redirect")}if(!["https:","http:"].includes(next.protocol)||next.username||next.password){throw new Error("Invalid npm registry redirect")}if(next.origin!==url.origin)auth=void 0;url=next}if(!response.ok)throw new Error(`Registry returned HTTP ${response.status}`);const tags=await response.json();if(typeof tags!=="object"||tags===null||Array.isArray(tags)){throw new Error("Invalid registry dist-tags response")}const latest2=Reflect.get(tags,distTag);if(latest2!==void 0&&typeof latest2!=="string"){throw new Error(`Invalid registry ${distTag} version response`)}return{latest:latest2??currentVersion,current:currentVersion,type:"latest",name:packageName}}const output=await runGlobalNpm(["view",packageName,`dist-tags.${distTag}`,"--json","--global"],run);if(output===""){return{latest:currentVersion,current:currentVersion,type:"latest",name:packageName}}const parsed=JSON.parse(output);const latest=typeof parsed==="string"?parsed:Array.isArray(parsed)&&parsed.length===1&&typeof parsed[0]==="string"?parsed[0]:void 0;if(latest===void 0){throw new Error(`Invalid npm ${distTag} version response`)}return{latest,current:currentVersion,type:"latest",name:packageName}}__name(fetchGlobalNpmUpdateInfo,"fetchGlobalNpmUpdateInfo");function getBestAvailableUpdate(nightly,stable){if(!nightly)return stable||null;if(!stable)return nightly||null;const nightlyVer=nightly.latest;const stableVer=stable.latest;if(import_semver.default.coerce(stableVer)?.version===import_semver.default.coerce(nightlyVer)?.version){return nightly}return import_semver.default.gt(stableVer,nightlyVer)?stable:nightly}__name(getBestAvailableUpdate,"getBestAvailableUpdate");async function checkForUpdatesDetailed(fetchGlobalNpm=fetchGlobalNpmUpdateInfo){let currentVersion;try{if(process.env["DEV"]==="true"){return{status:"skipped",reason:"development mode"}}const packageJson=await getPackageJson();if(!packageJson||!packageJson.name||!packageJson.version){return{status:"skipped",reason:"package metadata unavailable"}}const{name,version}=packageJson;currentVersion=version;const isNightly=version.includes("nightly");const createNotifier=__name(distTag=>({fetchInfo:__name(()=>fetchGlobalNpm(name,version,distTag),"fetchInfo")}),"createNotifier");if(isNightly){const[nightlyUpdateInfo,latestUpdateInfo]=await Promise.all([fetchInfoWithTimeout(createNotifier("nightly"),FETCH_TIMEOUT_MS,"nightly"),fetchInfoWithTimeout(createNotifier("latest"),FETCH_TIMEOUT_MS,"latest")]);debugLogger.debug(`fetchInfo returned nightly=${JSON.stringify(nightlyUpdateInfo)} latest=${JSON.stringify(latestUpdateInfo)} for current=${version}`);const bestUpdate=getBestAvailableUpdate(nightlyUpdateInfo,latestUpdateInfo);if(bestUpdate&&import_semver.default.gt(bestUpdate.latest,version)){return{status:"update",info:{message:t("A new version of Qwen Code is available! {{current}} \u2192 {{latest}}",{current:version,latest:bestUpdate.latest}),update:{...bestUpdate,current:version}}}}}else{const updateInfo=await fetchInfoWithTimeout(createNotifier("latest"),FETCH_TIMEOUT_MS,"latest");debugLogger.debug(`fetchInfo returned ${JSON.stringify(updateInfo)} for current=${version}`);if(updateInfo&&import_semver.default.gt(updateInfo.latest,version)){return{status:"update",info:{message:t("Qwen Code update available! {{current}} \u2192 {{latest}}",{current:version,latest:updateInfo.latest}),update:{...updateInfo,current:version}}}}}return{status:"up-to-date",currentVersion:version}}catch(e){const error=e instanceof Error?e:new Error(String(e));debugLogger.warn("Failed to check for updates: "+error);return{status:"error",error,currentVersion}}}__name(checkForUpdatesDetailed,"checkForUpdatesDetailed");async function checkForUpdates(fetchGlobalNpm=fetchGlobalNpmUpdateInfo){const result=await checkForUpdatesDetailed(fetchGlobalNpm);return result.status==="update"?result.info:null}__name(checkForUpdates,"checkForUpdates");export{FETCH_TIMEOUT_MS,UpdateCheckTimeoutError,classifyUpdateCheckError,describeUpdateCheckFailure,runGlobalNpm,fetchGlobalNpmUpdateInfo,checkForUpdatesDetailed,checkForUpdates};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Alibaba Inc.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{getCliVersion}from"./chunk-ESXBBANA.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync,spawn}from"node:child_process";import{createHash as createHash3,createHmac,randomUUID}from"node:crypto";import{constants as constants3,promises as fs3}from"node:fs";import path3 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var MAX_WORKSPACE_UPLOAD_BYTES=8*1024*1024;var WorkspaceFileError=class extends Error{constructor(code){super("Workspace file request is unavailable.");this.code=code}static{__name(this,"WorkspaceFileError")}};function refuse(code="unavailable"){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse,"refuse");function workspaceFilePath(value){if(value===".")return".";if(typeof value!=="string"||value.length>1024||/[\\\p{Cc}\p{Cs}]/u.test(value)||value.split("/").some(part=>!part||part==="."||part===".."||part===".git"||part===".qwen-child-workspaces"||part.startsWith(".qwen-managed-")))refuse("invalid_path");return value}__name(workspaceFilePath,"workspaceFilePath");function sessionWorkspaceFileScope(value,cwdRelative){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const scope=value;const keys=["sessionId","contextDigest","worktreeId","worktreeRevision","cwdRelative","worktreeRootIdentity"];if(Object.keys(scope).length!==keys.length||keys.some(key=>!(key in scope))||typeof scope["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(scope["sessionId"])||typeof scope["contextDigest"]!=="string"||!/^sha256:[a-f0-9]{64}$/.test(scope["contextDigest"])||typeof scope["worktreeId"]!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(scope["worktreeId"])||!Number.isSafeInteger(scope["worktreeRevision"])||Number(scope["worktreeRevision"])<1||typeof cwdRelative!=="string"||scope["cwdRelative"]!==cwdRelative)refuse("invalid_request");const prefix=`.qwen-managed-worktrees/${scope["worktreeId"]}`;if(cwdRelative!==prefix&&!cwdRelative.startsWith(`${prefix}/`))refuse("invalid_path");workspaceFilePath(cwdRelative.slice(prefix.length+1)||".");const identity=scope["worktreeRootIdentity"];if(!identity||typeof identity!=="object"||Array.isArray(identity))refuse("invalid_request");const fields=identity;if(Object.keys(fields).length!==2||!["device","inode"].every(key=>typeof fields[key]==="string"&&/^\d+$/.test(fields[key])))refuse("invalid_request");return scope}__name(sessionWorkspaceFileScope,"sessionWorkspaceFileScope");function signature(stat){return[stat.dev,stat.ino,stat.birthtimeNs,stat.size,stat.mtimeNs,stat.ctimeNs].join(":")}__name(signature,"signature");async function workspaceFileDirectories(root,cwdRelative,expected,sessionScope){const scope=sessionWorkspaceFileScope(sessionScope,cwdRelative);const cwd=scope?.cwdRelative??workspaceFilePath(cwdRelative);const worktreeRoot=scope?path.join(root,".qwen-managed-worktrees",scope.worktreeId):void 0;const anchors=new Map;async function directory(relative){const segments=relative==="."?[]:relative.split("/");let current=root;for(const segment of["",...segments]){if(segment)current=path.join(current,segment);const stat=await fs.lstat(current,{bigint:true});if(!stat.isDirectory()||await fs.realpath(current)!==current)refuse();if(current===root&&(String(stat.dev)!==expected.device||String(stat.ino)!==expected.inode))refuse();if(scope&¤t===worktreeRoot&&(String(stat.dev)!==scope.worktreeRootIdentity.device||String(stat.ino)!==scope.worktreeRootIdentity.inode))refuse("changed");const prior=anchors.get(current);const identity=[stat.dev,stat.ino,stat.birthtimeNs].join(":");if(prior&&prior!==identity)refuse("changed");anchors.set(current,identity)}return current}__name(directory,"directory");async function verify(){for(const[name,identity]of anchors){const stat=await fs.lstat(name,{bigint:true});if(!stat.isDirectory()||await fs.realpath(name)!==name||[stat.dev,stat.ino,stat.birthtimeNs].join(":")!==identity)refuse("changed")}}__name(verify,"verify");const base=await directory(cwd);const rooted=__name(relative=>cwd==="."?relative:relative==="."?cwd:`${cwd}/${relative}`,"rooted");return{base,directory:__name(relative=>directory(rooted(relative)),"directory"),verify}}__name(workspaceFileDirectories,"workspaceFileDirectories");async function readWorkspaceFiles(root,cwdRelative,value,expected,sessionScope){if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const request=value;if(request["protocolVersion"]!==1)refuse("unsupported");const{base,directory,verify}=await workspaceFileDirectories(root,cwdRelative,expected,sessionScope);if(request["operation"]==="read"){const relative2=workspaceFilePath(request["path"]);if(relative2===".")refuse("invalid_path");const parent=path.posix.dirname(relative2);await directory(parent);const filename=path.join(base,relative2);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(!before.isFile()||before.size===0n||before.size>24n*1024n)refuse("unsupported_content");const bytes=Buffer.alloc(24*1024+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}if(BigInt(size)!==before.size||signature(before)!==signature(await handle.stat({bigint:true}))||signature(before)!==signature(await fs.lstat(filename,{bigint:true})))refuse("changed");let text2;try{text2=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,size))}catch{return refuse("unsupported_content")}if(!text2||text2.includes("\0"))refuse("unsupported_content");await verify();const result={protocolVersion:1,path:relative2,name:path.posix.basename(relative2),mimeType:"text/plain",text:text2,byteLength:size,sha256:createHash("sha256").update(bytes.subarray(0,size)).digest("hex")};if(Buffer.byteLength(JSON.stringify(result))>48*1024)refuse("too_large");return result}finally{await handle.close()}}if(request["operation"]!=="query")refuse("invalid_request");const relative=workspaceFilePath(request["directory"]??".");const query=request["query"]??"";if(typeof query!=="string"||query.length>256||/[\p{Cc}\p{Cs}]/u.test(query))refuse("invalid_request");const entries=[];let scanned=0;let truncated=false;const deadline=Date.now()+2e3;const queue=[{relative,depth:0}];while(queue.length){const next=queue.shift();const dir=await directory(next.relative);const stream=await fs.opendir(dir);for await(const entry of stream){if(++scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}const name=next.relative==="."?entry.name:`${next.relative}/${entry.name}`;try{workspaceFilePath(name)}catch{continue}if(!entry.isFile()&&!entry.isDirectory())continue;if(query&&entry.isDirectory()){if(next.depth<32)queue.push({relative:name,depth:next.depth+1});else truncated=true}if(query&&(entry.isDirectory()||!name.toLowerCase().includes(query.toLowerCase())))continue;const item={path:name,name:entry.name,kind:entry.isDirectory()?"directory":"file"};if(Buffer.byteLength(JSON.stringify([...entries,item]))>24*1024){truncated=true;break}entries.push(item)}if(scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}}await verify();return{protocolVersion:1,directory:relative,entries,truncated,maxUploadBytes:MAX_WORKSPACE_UPLOAD_BYTES}}__name(readWorkspaceFiles,"readWorkspaceFiles");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{constants as constants2,promises as fs2}from"node:fs";import path2 from"node:path";function refuse2(code){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse2,"refuse");function failed(metadata,error){return workspaceUploadResult(metadata,"failed",error instanceof WorkspaceFileError?error.code:error.code==="EEXIST"?"ssh_runtime_file_exists":"ssh_runtime_file_unavailable")}__name(failed,"failed");function workspaceUploadRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))refuse2("invalid_request");const request=value;if(request["protocolVersion"]!==1||!["upload","upload-status"].includes(String(request["operation"]))||typeof request["uploadId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(request["uploadId"])||!Number.isSafeInteger(request["sizeBytes"])||Number(request["sizeBytes"])<0||Number(request["sizeBytes"])>MAX_WORKSPACE_UPLOAD_BYTES||typeof request["sha256"]!=="string"||!/^[0-9a-f]{64}$/.test(request["sha256"]))refuse2("invalid_request");const relative=workspaceFilePath(request["path"]);if(relative===".")refuse2("invalid_path");const metadata={uploadId:request["uploadId"],path:relative,sizeBytes:Number(request["sizeBytes"]),sha256:request["sha256"]};if(request["operation"]==="upload-status"){if(request["data"]!==void 0)refuse2("invalid_request");return{metadata}}const data=request["data"];if(typeof data!=="string"||data.length!==Math.ceil(metadata.sizeBytes/3)*4)refuse2("invalid_content");const bytes=Buffer.from(data,"base64");if(bytes.length!==metadata.sizeBytes||bytes.toString("base64")!==data||createHash2("sha256").update(bytes).digest("hex")!==metadata.sha256)refuse2("invalid_content");return{metadata,bytes}}__name(workspaceUploadRequest,"workspaceUploadRequest");function workspaceUploadResult(metadata,state,code){return{protocolVersion:1,...metadata,state,...code===void 0?{}:{code}}}__name(workspaceUploadResult,"workspaceUploadResult");function temporaryPath(directory,metadata){return path2.join(directory,`.qwen-managed-upload-${metadata.uploadId}.tmp`)}__name(temporaryPath,"temporaryPath");async function removeTemporary(temporary){try{await fs2.unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}}__name(removeTemporary,"removeTemporary");async function syncDirectory(directory){const handle=await fs2.open(directory,"r");try{await handle.sync()}finally{await handle.close()}}__name(syncDirectory,"syncDirectory");async function writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope){let directories;let parent;try{await verifyStorage();directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);parent=await directories.directory(path2.posix.dirname(metadata.path))}catch(error){return failed(metadata,error)}const destination=path2.join(directories.base,metadata.path);const temporary=temporaryPath(parent,metadata);let ownsTemporary=false;let result;try{const handle=await fs2.open(temporary,"wx",384);ownsTemporary=true;try{await handle.writeFile(bytes);await handle.sync()}finally{await handle.close()}await directories.verify();await verifyStorage();await fs2.link(temporary,destination);await directories.verify();await verifyStorage();result=workspaceUploadResult(metadata,"completed")}catch(error){result=failed(metadata,error)}finally{if(ownsTemporary){await directories.verify();await removeTemporary(temporary);await syncDirectory(parent)}}return result}__name(writeWorkspaceUpload,"writeWorkspaceUpload");async function inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope){await verifyStorage();const directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);const parent=await directories.directory(path2.posix.dirname(metadata.path));const destination=path2.join(directories.base,metadata.path);let completed=false;try{const handle=await fs2.open(destination,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(before.isFile()&&before.size===BigInt(metadata.sizeBytes)){const bytes=Buffer.alloc(metadata.sizeBytes+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}const after=await handle.stat({bigint:true});const current=await fs2.lstat(destination,{bigint:true});completed=size===metadata.sizeBytes&&before.dev===current.dev&&before.ino===current.ino&&before.mtimeNs===after.mtimeNs&&before.ctimeNs===after.ctimeNs&&before.size===after.size&&after.ctimeNs===current.ctimeNs&&createHash2("sha256").update(bytes.subarray(0,size)).digest("hex")===metadata.sha256}}finally{await handle.close()}}catch(error){if(!["ENOENT","ELOOP"].includes(error.code??""))throw error}await directories.verify();await verifyStorage();await removeTemporary(temporaryPath(parent,metadata));await syncDirectory(parent);return workspaceUploadResult(metadata,completed?"completed":"failed",completed?void 0:"ssh_runtime_file_upload_incomplete")}__name(inspectWorkspaceUpload,"inspectWorkspaceUpload");var MARKER=".qwen-managed-storage.json";var MAX_BYTES=64*1024;var MAX_UPLOAD_REQUEST_BYTES=12*1024*1024;var ID=/^[a-zA-Z0-9_.:-]{1,512}$/;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var hostId;var SSH_RETIRE_PATH="/internal/managed-runtime/v3/retire";var SshBootstrapError=class extends Error{constructor(code,message,retryable=false){super(message);this.code=code;this.retryable=retryable}static{__name(this,"SshBootstrapError")}};function refuse3(message){throw new SshBootstrapError("ssh_runtime_identity_conflict",message)}__name(refuse3,"refuse");function object(value){if(!value||typeof value!=="object"||Array.isArray(value))return refuse3("Runtime bootstrap document is invalid.");return value}__name(object,"object");function text(value){if(typeof value!=="string"||!value||value.includes("\0"))return refuse3("Runtime bootstrap text is invalid.");return value}__name(text,"text");function absolute(value){const directory=text(value);if(!path3.isAbsolute(directory)||path3.resolve(directory)!==directory)return refuse3("Runtime path must be absolute and normalized.");return directory}__name(absolute,"absolute");function within(root,candidate){const relative=path3.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path3.sep}`)&&!path3.isAbsolute(relative)}__name(within,"within");function exact(value,fields){if(Object.keys(value).length!==fields.length||fields.some(field=>!(field in value)))refuse3("Runtime bootstrap document has unexpected fields.")}__name(exact,"exact");async function readSshPrivateJson(file){const stat=await fs3.lstat(file);if(!stat.isFile()||stat.size>MAX_BYTES||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state file is not owner-private.");return JSON.parse(await fs3.readFile(file,"utf8"))}__name(readSshPrivateJson,"readSshPrivateJson");async function syncParentDirectory(file){const directory=await fs3.open(path3.dirname(file),"r");try{await directory.sync()}finally{await directory.close()}}__name(syncParentDirectory,"syncParentDirectory");async function writeSshPrivateJson(file,value){if(!await createSshPrivateJson(file,value)&&!isDeepStrictEqual(await readSshPrivateJson(file),value))refuse3("Runtime state conflicts with an earlier operation.")}__name(writeSshPrivateJson,"writeSshPrivateJson");async function createSshPrivateJson(file,value){const temporary=path3.join(path3.dirname(file),`.${path3.basename(file)}.${randomUUID()}.tmp`);const handle=await fs3.open(temporary,"wx",384);let created=true;try{try{await handle.writeFile(JSON.stringify(value),"utf8");await handle.sync()}finally{await handle.close()}try{await fs3.link(temporary,file)}catch(error){if(error.code!=="EEXIST")throw error;created=false}}finally{await fs3.unlink(temporary)}await syncParentDirectory(file);return created}__name(createSshPrivateJson,"createSshPrivateJson");async function privateDirectory(directory){const created=await fs3.mkdir(directory,{recursive:true,mode:448});const stat=await fs3.lstat(directory);if(!stat.isDirectory()||await fs3.realpath(directory)!==directory||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state directory must be canonical and owner-private.");for(let current=directory;;current=path3.dirname(current)){await syncParentDirectory(current);if(created===void 0||current===created)break}}__name(privateDirectory,"privateDirectory");function identityDocument(value){const identity=object(value);exact(identity,["root","hostId","device","inode","birthTime"]);absolute(identity["root"]);if(!/^[0-9a-f]{64}$/.test(text(identity["hostId"]))||!/^\d+$/.test(text(identity["device"]))||!/^\d+$/.test(text(identity["inode"]))||!Number.isFinite(Date.parse(text(identity["birthTime"]))))refuse3("Storage identity is invalid.");return identity}__name(identityDocument,"identityDocument");function markerDocument(value,identity){const marker=object(value);exact(marker,["version","tenantId","storageId","root","hostId","device","inode","birthTime","registrationId"]);if(marker["version"]!==2||!UUID.test(text(marker["registrationId"]))||!ID.test(text(marker["tenantId"]))||!ID.test(text(marker["storageId"]))||Object.entries(identity).some(([key,item])=>marker[key]!==item))refuse3("Storage marker does not bind the registered identity.");return marker}__name(markerDocument,"markerDocument");async function inspectSshStorage(root){if(!["linux","darwin"].includes(process.platform))throw new SshBootstrapError("ssh_runtime_platform_unsupported","Runtime requires Linux or macOS.");if(absolute(root)!==await fs3.realpath(root))refuse3("Storage root is not canonical.");const stat=await fs3.lstat(root,{bigint:true});if(!stat.isDirectory()||stat.birthtimeNs<=0n)refuse3("Storage directory has no independent birth identity.");await fs3.access(root,constants3.R_OK|constants3.W_OK|constants3.X_OK);const machine=hostId?void 0:process.platform==="linux"?(await fs3.readFile("/etc/machine-id","utf8")).trim():/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(execFileSync("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:MAX_BYTES}))?.[1];if(!hostId){if(!machine||machine.length>256)refuse3("Stable host identity is unavailable.");hostId=createHmac("sha256",machine).update("Qwen-Code/verified-workspace/v2").digest("hex")}const seconds=stat.birthtimeNs/1000000000n;const nanos=(stat.birthtimeNs%1000000000n).toString().padStart(9,"0");const fraction=nanos==="000000000"?"":`.${nanos.endsWith("000000")?nanos.slice(0,3):nanos.endsWith("000")?nanos.slice(0,6):nanos}`;return{root,hostId,device:BigInt.asUintN(64,stat.dev).toString(),inode:BigInt.asUintN(64,stat.ino).toString(),birthTime:new Date(Number(seconds)*1e3).toISOString().replace(/\.000Z$/,`${fraction}Z`)}}__name(inspectSshStorage,"inspectSshStorage");async function verifySshStorage(identity,marker){if(!isDeepStrictEqual(await inspectSshStorage(identity.root),identity))refuse3("Registered storage identity changed.");if(marker&&!isDeepStrictEqual(await readSshPrivateJson(path3.join(identity.root,MARKER)),marker))refuse3("Registered storage marker changed.")}__name(verifySshStorage,"verifySshStorage");function resourceDirectory(stateDirectory,resourceId){if(!UUID.test(resourceId))refuse3("Runtime resource identity is invalid.");return path3.join(stateDirectory,"resources",resourceId)}__name(resourceDirectory,"resourceDirectory");async function readSshRuntimeRecord(directory){const value=object(await readSshPrivateJson(path3.join(directory,"intent.json")));exact(value,["version","nodeId","stateDirectory","resourceId","bindingId","bindingGeneration","boot","identity","marker","workerEntry","expectedQwenVersion"]);const identity=identityDocument(value["identity"]);const boot=parseManagedContextBoot(value["boot"]);const marker=markerDocument(value["marker"],identity);if(value["version"]!==1||!ID.test(text(value["nodeId"]))||!ID.test(text(value["bindingId"]))||!Number.isSafeInteger(value["bindingGeneration"])||Number(value["bindingGeneration"])<=0||boot.isolationClass!=="session"||boot.mountRoot!==identity.root||boot.tenantId!==marker.tenantId||boot.storageId!==marker.storageId||resourceDirectory(absolute(value["stateDirectory"]),text(value["resourceId"]))!==directory)refuse3("Runtime intent identity is invalid.");absolute(value["workerEntry"]);text(value["expectedQwenVersion"]);return value}__name(readSshRuntimeRecord,"readSshRuntimeRecord");function sshCleanProof(record,retirementId,retiredAt){return{version:record.boot.managedExtensions?2:1,...record.boot.managedExtensions?{executionMode:record.boot.managedExtensions.mode,scope:record.boot.managedExtensions.mode==="linux-cgroup"?"process_tree":"process_group"}:{},resourceId:record.resourceId,bindingId:record.bindingId,bindingGeneration:record.bindingGeneration,provisionRequestId:record.boot.provisionRequestId,runtimeInstanceId:record.boot.runtimeInstanceId,runtimeIncarnation:record.boot.runtimeIncarnation,leaseId:record.boot.leaseId,epoch:record.boot.epoch,retirementId,retiredAt}}__name(sshCleanProof,"sshCleanProof");function alive(pid){try{process.kill(pid,0);return true}catch(error){if(error.code==="ESRCH")return false;throw new SshBootstrapError("ssh_runtime_stop_unverified","Original process liveness is unverified.")}}__name(alive,"alive");async function optionalJson(file){try{return await readSshPrivateJson(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(optionalJson,"optionalJson");async function observe(record){await verifySshStorage(record.identity,record.marker);const directory=resourceDirectory(record.stateDirectory,record.resourceId);const pidRecord=await optionalJson(path3.join(directory,"pid.json"));const pid=pidRecord===void 0?null:object(pidRecord)["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Runtime process record is invalid.");const result={resourceId:record.resourceId,state:"INTENT",pid,ready:null};const claim=await optionalJson(path3.join(directory,"launch.claim"));if(claim===void 0){for(const file of["pid.json","ready.json","clean.json","stdout.log","stderr.log","launch-failed.json"]){try{await fs3.lstat(path3.join(directory,file))}catch(error){if(error.code==="ENOENT")continue;throw error}refuse3("Runtime launch claim is missing from an existing resource.")}return result}const claimedRetirement=object(claim)["retirementId"];const neverStarted=typeof claimedRetirement==="string"&&UUID.test(claimedRetirement);if(!isDeepStrictEqual(claim,neverStarted?{provisionRequestId:record.boot.provisionRequestId,retirementId:claimedRetirement}:{provisionRequestId:record.boot.provisionRequestId}))refuse3("Runtime launch claim conflicts.");if(neverStarted&&pid!==null)refuse3("A retired launch claim cannot own a worker process.");const failed2=await optionalJson(path3.join(directory,"launch-failed.json"));if(failed2!==void 0&&(!isDeepStrictEqual(failed2,{provisionRequestId:record.boot.provisionRequestId})||pid!==null||await optionalJson(path3.join(directory,"ready.json"))!==void 0))refuse3("Runtime failed-launch evidence conflicts.");const clean=await optionalJson(path3.join(directory,"clean.json"));if(clean!==void 0){const proof=object(clean);const retiredAt=text(proof["retiredAt"]);const stop=object(await readSshPrivateJson(path3.join(directory,"stop.json")));if(!Number.isFinite(Date.parse(retiredAt))||!isDeepStrictEqual(clean,sshCleanProof(record,text(stop["retirementId"]),retiredAt)))refuse3("Runtime clean proof conflicts.");if((neverStarted||failed2!==void 0)&&pid===null&&(failed2!==void 0||claimedRetirement===stop["retirementId"])||pid!==null&&!alive(Number(pid)))return{...result,state:"RETIRED",cleanProof:clean};return{...result,state:"BLOCKED"}}if(failed2!==void 0)return{...result,state:"FAILED"};if(neverStarted&&pid===null)return result;if(pid===null||!alive(Number(pid)))return{...result,state:"BLOCKED"};const ready=await optionalJson(path3.join(directory,"ready.json"));if(ready===void 0)return{...result,state:"STARTING"};const value=object(ready);if(!isManagedContextReady(value,record.boot))refuse3("Runtime ready identity conflicts.");return{...result,state:"READY",ready:value}}__name(observe,"observe");async function attest(record,ready){const expected=createManagedContextAttestationResponse(record.boot);const{runtimeInstanceId:_runtime,runtimeIncarnation:_incarnation,leaseId:_lease,epoch:_epoch,...request}=expected;const response=await fetch(`${ready.url}/internal/managed-runtime/v3/attest`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify(request),redirect:"error",signal:AbortSignal.timeout(5e3)});if(!response.ok||!isDeepStrictEqual(await response.json(),expected))refuse3("Original Runtime attestation failed.")}__name(attest,"attest");function sshRuntimeHeaders(boot){return{Authorization:`Bearer ${boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","X-Qwen-Managed-Lease-Id":boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(boot.epoch)}}__name(sshRuntimeHeaders,"sshRuntimeHeaders");async function ensure(request,nodeId,stateDirectory){const resourceId=text(request["resourceId"]);const expectedQwenVersion=text(request["expectedQwenVersion"]);if(expectedQwenVersion!==await getCliVersion()){throw new SshBootstrapError("ssh_runtime_version_conflict","Pinned Qwen version does not match this installation.")}const directory=resourceDirectory(stateDirectory,resourceId);const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity,marker);await privateDirectory(directory);const record={version:1,nodeId,stateDirectory,resourceId,bindingId:request["bindingId"],bindingGeneration:request["bindingGeneration"],boot:request["boot"],identity,marker,workerEntry:absolute(request["workerEntry"]),expectedQwenVersion};await writeSshPrivateJson(path3.join(directory,"intent.json"),record);const saved=await readSshRuntimeRecord(directory);if(typeof request["launch"]!=="boolean")refuse3("Runtime launch phase is required.");if(!request["launch"])return observe(saved);if(await optionalJson(path3.join(directory,"stop.json"))!==void 0)return observe(saved);const original=await observe(saved);if(original["state"]!=="INTENT")return original;if(!await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:saved.boot.provisionRequestId}))return observe(saved);let spawned=false;try{const output=await fs3.open(path3.join(directory,"stdout.log"),"ax",384);try{const errors=await fs3.open(path3.join(directory,"stderr.log"),"ax",384);try{const env={};for(const key of["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TMP","TEMP","TZ"]){if(process.env[key]!==void 0)env[key]=process.env[key]}const child=spawn(process.execPath,[saved.workerEntry,"managed-runtime-bootstrap-worker",directory],{cwd:path3.dirname(saved.workerEntry),detached:true,stdio:["ignore",output.fd,errors.fd],env});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});spawned=true;child.unref();await writeSshPrivateJson(path3.join(directory,"pid.json"),{pid:child.pid})}finally{await errors.close()}}finally{await output.close()}}catch{if(!spawned){await writeSshPrivateJson(path3.join(directory,"launch-failed.json"),{provisionRequestId:saved.boot.provisionRequestId});return observe(saved)}}for(let attempt=0;attempt<100;attempt++){const observed=await observe(saved);if(observed["state"]!=="STARTING"&&!(observed["state"]==="BLOCKED"&&observed["pid"]===null))return observed;await new Promise(resolve=>setTimeout(resolve,50))}return observe(saved)}__name(ensure,"ensure");async function workspaceUpload(request,expected,verifyStorage,sessionScope){const{metadata,bytes}=workspaceUploadRequest(request["files"]);const root=absolute(request["root"]);const cwd=sessionScope?.cwdRelative??workspaceFilePath(request["cwdRelative"]);const target={nodeId:request["nodeId"],root,cwd,expected,identity:request["identity"]??null,marker:request["marker"]??null,...sessionScope?{sessionFileScope:sessionScope}:{},...metadata};const canonical=__name(value=>value&&typeof value==="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>[key,canonical(item)])):value,"canonical");const requestDigest=createHash3("sha256").update(JSON.stringify(canonical(target))).digest("hex");const stateDirectory=absolute(request["stateDirectory"]);await privateDirectory(stateDirectory);const directory=path3.join(stateDirectory,"workspace-uploads",metadata.uploadId);await privateDirectory(directory);const claimPath=path3.join(directory,"claim.json");const receiptPath=path3.join(directory,"receipt.json");let claim=await optionalJson(claimPath);let started=false;if(claim===void 0){if(await optionalJson(receiptPath)!==void 0)refuse3("Workspace upload claim is unavailable.");const proposed={version:1,target,requestDigest,pid:bytes===void 0?null:process.pid};started=await createSshPrivateJson(claimPath,proposed);claim=started?proposed:await readSshPrivateJson(claimPath)}const saved=object(claim);exact(saved,["version","target","requestDigest","pid"]);if(saved["version"]!==1||saved["requestDigest"]!==requestDigest||!isDeepStrictEqual(saved["target"],target))throw new WorkspaceFileError("ssh_runtime_file_upload_conflict");const pid=saved["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Workspace upload process identity is invalid.");const receipt=await optionalJson(receiptPath);if(receipt!==void 0){const result2=object(receipt);if(!["completed","failed"].includes(String(result2["state"]))||result2["state"]==="failed"&&typeof result2["code"]!=="string"||!isDeepStrictEqual(receipt,workspaceUploadResult(metadata,result2["state"],result2["code"])))refuse3("Workspace upload receipt is invalid.");return receipt}let result;if(pid===null){result=workspaceUploadResult(metadata,"failed","ssh_runtime_file_upload_not_started")}else if(started&&bytes!==void 0){result=await writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope)}else{let live=true;try{live=alive(Number(pid))}catch{}if(live)return workspaceUploadResult(metadata,"pending");result=await inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope)}await writeSshPrivateJson(receiptPath,result);return result}__name(workspaceUpload,"workspaceUpload");async function executeSshBootstrap(value){const request=object(value);if(request["protocolVersion"]!==1||!ID.test(text(request["nodeId"])))refuse3("Runtime bootstrap protocol is invalid.");const nodeId=text(request["nodeId"]);const stateDirectory=absolute(request["stateDirectory"]);const operation=text(request["operation"]);if(operation==="probe"||operation==="ensure"){if(Number(process.versions.node.split(".")[0])<22){throw new SshBootstrapError("ssh_runtime_node_unsupported","Runtime requires Node.js 22 or later.")}}if(operation==="probe"){const root=absolute(request["root"]);const roots=request["allowedRoots"];if(!Array.isArray(roots)||roots.length===0||!roots.some(candidate=>within(absolute(candidate),root)))refuse3("Directory is outside the configured roots.");if(within(root,stateDirectory)||within(stateDirectory,root))refuse3("Runtime state and Workspace roots must not overlap.");if(request["files"]!==void 0){const fileOperation=object(request["files"])["operation"];const uploading=["upload","upload-status"].includes(String(fileOperation));const identity2=request["identity"]===void 0?void 0:identityDocument(request["identity"]);const marker=identity2?markerDocument(request["marker"],identity2):void 0;if(identity2&&identity2.root!==root)refuse3("Storage root conflicts.");if(identity2&&!uploading)await verifySshStorage(identity2,marker);const expected=identity2??object(request["localRootIdentity"]);try{if(request["sessionFileScope"]!==void 0&&identity2)refuse3("Session file scopes require local storage.");const sessionScope=sessionWorkspaceFileScope(request["sessionFileScope"],request["cwdRelative"]);const fileIdentity={device:text(expected.device),inode:text(expected.inode)};const files=uploading?await workspaceUpload(request,fileIdentity,async()=>{if(identity2)await verifySshStorage(identity2,marker)},sessionScope):await readWorkspaceFiles(root,text(request["cwdRelative"]),request["files"],fileIdentity,sessionScope);if(identity2&&!uploading)await verifySshStorage(identity2,marker);return{qwenVersion:await getCliVersion(),files}}catch(error){if(error instanceof WorkspaceFileError)throw new SshBootstrapError(error.code,error.message);throw error}}const identity=await inspectSshStorage(root);if(request["cwdRelative"]!==void 0){const relative=text(request["cwdRelative"]);const cwd=path3.resolve(root,relative);if(path3.isAbsolute(relative)||!within(root,cwd)||cwd!==await fs3.realpath(cwd)||!(await fs3.stat(cwd)).isDirectory())refuse3("Working directory is unavailable.");await fs3.access(cwd,constants3.R_OK|constants3.W_OK|constants3.X_OK)}return{platform:process.platform,nodeVersion:process.version,qwenVersion:await getCliVersion(),identity,marker:await optionalJson(path3.join(root,MARKER))??null}}if(operation==="register-storage"){const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity);await writeSshPrivateJson(path3.join(identity.root,MARKER),marker);await verifySshStorage(identity,marker);return{identity,marker}}await privateDirectory(stateDirectory);if(operation==="ensure")return ensure(request,nodeId,stateDirectory);const directory=resourceDirectory(stateDirectory,text(request["resourceId"]));const record=await readSshRuntimeRecord(directory);if(record.nodeId!==nodeId||record.stateDirectory!==stateDirectory)refuse3("Runtime node identity conflicts.");let observed=await observe(record);if(operation==="observe")return observed;if(operation!=="stop")refuse3("Runtime bootstrap operation is unsupported.");const retirementId=text(request["retirementId"]);if(!UUID.test(retirementId))refuse3("Runtime retirement identity is invalid.");if(observed["state"]==="INTENT"){await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:record.boot.provisionRequestId,retirementId});observed=await observe(record)}const claim=object(await readSshPrivateJson(path3.join(directory,"launch.claim")));if(claim["retirementId"]!==void 0&&claim["retirementId"]!==retirementId)refuse3("Runtime retirement identity conflicts.");if(observed["state"]==="RETIRED"){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});return observed}if(observed["state"]==="FAILED"||claim["retirementId"]===retirementId){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path3.join(directory,"clean.json"),sshCleanProof(record,retirementId,new Date().toISOString()));return observe(record)}if(observed["state"]==="STARTING"||observed["state"]==="BLOCKED"&&observed["pid"]===null)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime startup has not completed.",true);if(observed["state"]!=="READY")throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime is not reachable for clean retirement.");await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});const ready=observed["ready"];try{await attest(record,ready);const response=await fetch(`${ready.url}${SSH_RETIRE_PATH}`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify({protocolVersion:1,resourceId:record.resourceId,retirementId}),redirect:"error",signal:AbortSignal.timeout(15e3)});if(!response.ok)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement is not proven.",true);await response.arrayBuffer()}catch(error){if(error instanceof SshBootstrapError)throw error;if((await observe(record))["state"]!=="RETIRED")throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement response is unavailable.",true)}for(let attempt=0;attempt<100;attempt++){const result=await observe(record);if(result["state"]==="RETIRED")return result;await new Promise(resolve=>setTimeout(resolve,50))}throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime process has not exited.",true)}__name(executeSshBootstrap,"executeSshBootstrap");async function runManagedRuntimeBootstrap(help=false,workspaceFileUpload=false){if(help){process.stdout.write(`${JSON.stringify({protocolVersion:1,capabilities:{workspaceFiles:1,workspaceFileUpload:1}})}
|
|
3
|
+
import{createManagedContextAttestationResponse,isManagedContextReady,parseManagedContextBoot}from"./chunk-36TKFM4Z.js";import{getCliVersion}from"./chunk-OPBSEVFC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{execFileSync,spawn}from"node:child_process";import{createHash as createHash3,createHmac,randomUUID}from"node:crypto";import{constants as constants3,promises as fs3}from"node:fs";import path3 from"node:path";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";import{constants,promises as fs}from"node:fs";import path from"node:path";var MAX_WORKSPACE_UPLOAD_BYTES=8*1024*1024;var WorkspaceFileError=class extends Error{constructor(code){super("Workspace file request is unavailable.");this.code=code}static{__name(this,"WorkspaceFileError")}};function refuse(code="unavailable"){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse,"refuse");function workspaceFilePath(value){if(value===".")return".";if(typeof value!=="string"||value.length>1024||/[\\\p{Cc}\p{Cs}]/u.test(value)||value.split("/").some(part=>!part||part==="."||part===".."||part===".git"||part===".qwen-child-workspaces"||part.startsWith(".qwen-managed-")))refuse("invalid_path");return value}__name(workspaceFilePath,"workspaceFilePath");function sessionWorkspaceFileScope(value,cwdRelative){if(value===void 0)return void 0;if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const scope=value;const keys=["sessionId","contextDigest","worktreeId","worktreeRevision","cwdRelative","worktreeRootIdentity"];if(Object.keys(scope).length!==keys.length||keys.some(key=>!(key in scope))||typeof scope["sessionId"]!=="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(scope["sessionId"])||typeof scope["contextDigest"]!=="string"||!/^sha256:[a-f0-9]{64}$/.test(scope["contextDigest"])||typeof scope["worktreeId"]!=="string"||!/^[A-Za-z0-9_-]{1,128}$/.test(scope["worktreeId"])||!Number.isSafeInteger(scope["worktreeRevision"])||Number(scope["worktreeRevision"])<1||typeof cwdRelative!=="string"||scope["cwdRelative"]!==cwdRelative)refuse("invalid_request");const prefix=`.qwen-managed-worktrees/${scope["worktreeId"]}`;if(cwdRelative!==prefix&&!cwdRelative.startsWith(`${prefix}/`))refuse("invalid_path");workspaceFilePath(cwdRelative.slice(prefix.length+1)||".");const identity=scope["worktreeRootIdentity"];if(!identity||typeof identity!=="object"||Array.isArray(identity))refuse("invalid_request");const fields=identity;if(Object.keys(fields).length!==2||!["device","inode"].every(key=>typeof fields[key]==="string"&&/^\d+$/.test(fields[key])))refuse("invalid_request");return scope}__name(sessionWorkspaceFileScope,"sessionWorkspaceFileScope");function signature(stat){return[stat.dev,stat.ino,stat.birthtimeNs,stat.size,stat.mtimeNs,stat.ctimeNs].join(":")}__name(signature,"signature");async function workspaceFileDirectories(root,cwdRelative,expected,sessionScope){const scope=sessionWorkspaceFileScope(sessionScope,cwdRelative);const cwd=scope?.cwdRelative??workspaceFilePath(cwdRelative);const worktreeRoot=scope?path.join(root,".qwen-managed-worktrees",scope.worktreeId):void 0;const anchors=new Map;async function directory(relative){const segments=relative==="."?[]:relative.split("/");let current=root;for(const segment of["",...segments]){if(segment)current=path.join(current,segment);const stat=await fs.lstat(current,{bigint:true});if(!stat.isDirectory()||await fs.realpath(current)!==current)refuse();if(current===root&&(String(stat.dev)!==expected.device||String(stat.ino)!==expected.inode))refuse();if(scope&¤t===worktreeRoot&&(String(stat.dev)!==scope.worktreeRootIdentity.device||String(stat.ino)!==scope.worktreeRootIdentity.inode))refuse("changed");const prior=anchors.get(current);const identity=[stat.dev,stat.ino,stat.birthtimeNs].join(":");if(prior&&prior!==identity)refuse("changed");anchors.set(current,identity)}return current}__name(directory,"directory");async function verify(){for(const[name,identity]of anchors){const stat=await fs.lstat(name,{bigint:true});if(!stat.isDirectory()||await fs.realpath(name)!==name||[stat.dev,stat.ino,stat.birthtimeNs].join(":")!==identity)refuse("changed")}}__name(verify,"verify");const base=await directory(cwd);const rooted=__name(relative=>cwd==="."?relative:relative==="."?cwd:`${cwd}/${relative}`,"rooted");return{base,directory:__name(relative=>directory(rooted(relative)),"directory"),verify}}__name(workspaceFileDirectories,"workspaceFileDirectories");async function readWorkspaceFiles(root,cwdRelative,value,expected,sessionScope){if(!value||typeof value!=="object"||Array.isArray(value))refuse("invalid_request");const request=value;if(request["protocolVersion"]!==1)refuse("unsupported");const{base,directory,verify}=await workspaceFileDirectories(root,cwdRelative,expected,sessionScope);if(request["operation"]==="read"){const relative2=workspaceFilePath(request["path"]);if(relative2===".")refuse("invalid_path");const parent=path.posix.dirname(relative2);await directory(parent);const filename=path.join(base,relative2);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(!before.isFile()||before.size===0n||before.size>24n*1024n)refuse("unsupported_content");const bytes=Buffer.alloc(24*1024+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}if(BigInt(size)!==before.size||signature(before)!==signature(await handle.stat({bigint:true}))||signature(before)!==signature(await fs.lstat(filename,{bigint:true})))refuse("changed");let text2;try{text2=new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(bytes.subarray(0,size))}catch{return refuse("unsupported_content")}if(!text2||text2.includes("\0"))refuse("unsupported_content");await verify();const result={protocolVersion:1,path:relative2,name:path.posix.basename(relative2),mimeType:"text/plain",text:text2,byteLength:size,sha256:createHash("sha256").update(bytes.subarray(0,size)).digest("hex")};if(Buffer.byteLength(JSON.stringify(result))>48*1024)refuse("too_large");return result}finally{await handle.close()}}if(request["operation"]!=="query")refuse("invalid_request");const relative=workspaceFilePath(request["directory"]??".");const query=request["query"]??"";if(typeof query!=="string"||query.length>256||/[\p{Cc}\p{Cs}]/u.test(query))refuse("invalid_request");const entries=[];let scanned=0;let truncated=false;const deadline=Date.now()+2e3;const queue=[{relative,depth:0}];while(queue.length){const next=queue.shift();const dir=await directory(next.relative);const stream=await fs.opendir(dir);for await(const entry of stream){if(++scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}const name=next.relative==="."?entry.name:`${next.relative}/${entry.name}`;try{workspaceFilePath(name)}catch{continue}if(!entry.isFile()&&!entry.isDirectory())continue;if(query&&entry.isDirectory()){if(next.depth<32)queue.push({relative:name,depth:next.depth+1});else truncated=true}if(query&&(entry.isDirectory()||!name.toLowerCase().includes(query.toLowerCase())))continue;const item={path:name,name:entry.name,kind:entry.isDirectory()?"directory":"file"};if(Buffer.byteLength(JSON.stringify([...entries,item]))>24*1024){truncated=true;break}entries.push(item)}if(scanned>4096||Date.now()>deadline||entries.length>=50){truncated=true;break}}await verify();return{protocolVersion:1,directory:relative,entries,truncated,maxUploadBytes:MAX_WORKSPACE_UPLOAD_BYTES}}__name(readWorkspaceFiles,"readWorkspaceFiles");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{constants as constants2,promises as fs2}from"node:fs";import path2 from"node:path";function refuse2(code){throw new WorkspaceFileError(`ssh_runtime_file_${code}`)}__name(refuse2,"refuse");function failed(metadata,error){return workspaceUploadResult(metadata,"failed",error instanceof WorkspaceFileError?error.code:error.code==="EEXIST"?"ssh_runtime_file_exists":"ssh_runtime_file_unavailable")}__name(failed,"failed");function workspaceUploadRequest(value){if(!value||typeof value!=="object"||Array.isArray(value))refuse2("invalid_request");const request=value;if(request["protocolVersion"]!==1||!["upload","upload-status"].includes(String(request["operation"]))||typeof request["uploadId"]!=="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(request["uploadId"])||!Number.isSafeInteger(request["sizeBytes"])||Number(request["sizeBytes"])<0||Number(request["sizeBytes"])>MAX_WORKSPACE_UPLOAD_BYTES||typeof request["sha256"]!=="string"||!/^[0-9a-f]{64}$/.test(request["sha256"]))refuse2("invalid_request");const relative=workspaceFilePath(request["path"]);if(relative===".")refuse2("invalid_path");const metadata={uploadId:request["uploadId"],path:relative,sizeBytes:Number(request["sizeBytes"]),sha256:request["sha256"]};if(request["operation"]==="upload-status"){if(request["data"]!==void 0)refuse2("invalid_request");return{metadata}}const data=request["data"];if(typeof data!=="string"||data.length!==Math.ceil(metadata.sizeBytes/3)*4)refuse2("invalid_content");const bytes=Buffer.from(data,"base64");if(bytes.length!==metadata.sizeBytes||bytes.toString("base64")!==data||createHash2("sha256").update(bytes).digest("hex")!==metadata.sha256)refuse2("invalid_content");return{metadata,bytes}}__name(workspaceUploadRequest,"workspaceUploadRequest");function workspaceUploadResult(metadata,state,code){return{protocolVersion:1,...metadata,state,...code===void 0?{}:{code}}}__name(workspaceUploadResult,"workspaceUploadResult");function temporaryPath(directory,metadata){return path2.join(directory,`.qwen-managed-upload-${metadata.uploadId}.tmp`)}__name(temporaryPath,"temporaryPath");async function removeTemporary(temporary){try{await fs2.unlink(temporary)}catch(error){if(error.code!=="ENOENT")throw error}}__name(removeTemporary,"removeTemporary");async function syncDirectory(directory){const handle=await fs2.open(directory,"r");try{await handle.sync()}finally{await handle.close()}}__name(syncDirectory,"syncDirectory");async function writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope){let directories;let parent;try{await verifyStorage();directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);parent=await directories.directory(path2.posix.dirname(metadata.path))}catch(error){return failed(metadata,error)}const destination=path2.join(directories.base,metadata.path);const temporary=temporaryPath(parent,metadata);let ownsTemporary=false;let result;try{const handle=await fs2.open(temporary,"wx",384);ownsTemporary=true;try{await handle.writeFile(bytes);await handle.sync()}finally{await handle.close()}await directories.verify();await verifyStorage();await fs2.link(temporary,destination);await directories.verify();await verifyStorage();result=workspaceUploadResult(metadata,"completed")}catch(error){result=failed(metadata,error)}finally{if(ownsTemporary){await directories.verify();await removeTemporary(temporary);await syncDirectory(parent)}}return result}__name(writeWorkspaceUpload,"writeWorkspaceUpload");async function inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope){await verifyStorage();const directories=await workspaceFileDirectories(root,cwd,expected,sessionScope);const parent=await directories.directory(path2.posix.dirname(metadata.path));const destination=path2.join(directories.base,metadata.path);let completed=false;try{const handle=await fs2.open(destination,constants2.O_RDONLY|constants2.O_NOFOLLOW|constants2.O_NONBLOCK);try{const before=await handle.stat({bigint:true});if(before.isFile()&&before.size===BigInt(metadata.sizeBytes)){const bytes=Buffer.alloc(metadata.sizeBytes+1);let size=0;while(size<bytes.length){const read=await handle.read(bytes,size,bytes.length-size,size);if(!read.bytesRead)break;size+=read.bytesRead}const after=await handle.stat({bigint:true});const current=await fs2.lstat(destination,{bigint:true});completed=size===metadata.sizeBytes&&before.dev===current.dev&&before.ino===current.ino&&before.mtimeNs===after.mtimeNs&&before.ctimeNs===after.ctimeNs&&before.size===after.size&&after.ctimeNs===current.ctimeNs&&createHash2("sha256").update(bytes.subarray(0,size)).digest("hex")===metadata.sha256}}finally{await handle.close()}}catch(error){if(!["ENOENT","ELOOP"].includes(error.code??""))throw error}await directories.verify();await verifyStorage();await removeTemporary(temporaryPath(parent,metadata));await syncDirectory(parent);return workspaceUploadResult(metadata,completed?"completed":"failed",completed?void 0:"ssh_runtime_file_upload_incomplete")}__name(inspectWorkspaceUpload,"inspectWorkspaceUpload");var MARKER=".qwen-managed-storage.json";var MAX_BYTES=64*1024;var MAX_UPLOAD_REQUEST_BYTES=12*1024*1024;var ID=/^[a-zA-Z0-9_.:-]{1,512}$/;var UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;var hostId;var SSH_RETIRE_PATH="/internal/managed-runtime/v3/retire";var SshBootstrapError=class extends Error{constructor(code,message,retryable=false){super(message);this.code=code;this.retryable=retryable}static{__name(this,"SshBootstrapError")}};function refuse3(message){throw new SshBootstrapError("ssh_runtime_identity_conflict",message)}__name(refuse3,"refuse");function object(value){if(!value||typeof value!=="object"||Array.isArray(value))return refuse3("Runtime bootstrap document is invalid.");return value}__name(object,"object");function text(value){if(typeof value!=="string"||!value||value.includes("\0"))return refuse3("Runtime bootstrap text is invalid.");return value}__name(text,"text");function absolute(value){const directory=text(value);if(!path3.isAbsolute(directory)||path3.resolve(directory)!==directory)return refuse3("Runtime path must be absolute and normalized.");return directory}__name(absolute,"absolute");function within(root,candidate){const relative=path3.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path3.sep}`)&&!path3.isAbsolute(relative)}__name(within,"within");function exact(value,fields){if(Object.keys(value).length!==fields.length||fields.some(field=>!(field in value)))refuse3("Runtime bootstrap document has unexpected fields.")}__name(exact,"exact");async function readSshPrivateJson(file){const stat=await fs3.lstat(file);if(!stat.isFile()||stat.size>MAX_BYTES||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state file is not owner-private.");return JSON.parse(await fs3.readFile(file,"utf8"))}__name(readSshPrivateJson,"readSshPrivateJson");async function syncParentDirectory(file){const directory=await fs3.open(path3.dirname(file),"r");try{await directory.sync()}finally{await directory.close()}}__name(syncParentDirectory,"syncParentDirectory");async function writeSshPrivateJson(file,value){if(!await createSshPrivateJson(file,value)&&!isDeepStrictEqual(await readSshPrivateJson(file),value))refuse3("Runtime state conflicts with an earlier operation.")}__name(writeSshPrivateJson,"writeSshPrivateJson");async function createSshPrivateJson(file,value){const temporary=path3.join(path3.dirname(file),`.${path3.basename(file)}.${randomUUID()}.tmp`);const handle=await fs3.open(temporary,"wx",384);let created=true;try{try{await handle.writeFile(JSON.stringify(value),"utf8");await handle.sync()}finally{await handle.close()}try{await fs3.link(temporary,file)}catch(error){if(error.code!=="EEXIST")throw error;created=false}}finally{await fs3.unlink(temporary)}await syncParentDirectory(file);return created}__name(createSshPrivateJson,"createSshPrivateJson");async function privateDirectory(directory){const created=await fs3.mkdir(directory,{recursive:true,mode:448});const stat=await fs3.lstat(directory);if(!stat.isDirectory()||await fs3.realpath(directory)!==directory||(stat.mode&63)!==0||stat.uid!==process.getuid?.())refuse3("Runtime state directory must be canonical and owner-private.");for(let current=directory;;current=path3.dirname(current)){await syncParentDirectory(current);if(created===void 0||current===created)break}}__name(privateDirectory,"privateDirectory");function identityDocument(value){const identity=object(value);exact(identity,["root","hostId","device","inode","birthTime"]);absolute(identity["root"]);if(!/^[0-9a-f]{64}$/.test(text(identity["hostId"]))||!/^\d+$/.test(text(identity["device"]))||!/^\d+$/.test(text(identity["inode"]))||!Number.isFinite(Date.parse(text(identity["birthTime"]))))refuse3("Storage identity is invalid.");return identity}__name(identityDocument,"identityDocument");function markerDocument(value,identity){const marker=object(value);exact(marker,["version","tenantId","storageId","root","hostId","device","inode","birthTime","registrationId"]);if(marker["version"]!==2||!UUID.test(text(marker["registrationId"]))||!ID.test(text(marker["tenantId"]))||!ID.test(text(marker["storageId"]))||Object.entries(identity).some(([key,item])=>marker[key]!==item))refuse3("Storage marker does not bind the registered identity.");return marker}__name(markerDocument,"markerDocument");async function inspectSshStorage(root){if(!["linux","darwin"].includes(process.platform))throw new SshBootstrapError("ssh_runtime_platform_unsupported","Runtime requires Linux or macOS.");if(absolute(root)!==await fs3.realpath(root))refuse3("Storage root is not canonical.");const stat=await fs3.lstat(root,{bigint:true});if(!stat.isDirectory()||stat.birthtimeNs<=0n)refuse3("Storage directory has no independent birth identity.");await fs3.access(root,constants3.R_OK|constants3.W_OK|constants3.X_OK);const machine=hostId?void 0:process.platform==="linux"?(await fs3.readFile("/etc/machine-id","utf8")).trim():/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(execFileSync("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:MAX_BYTES}))?.[1];if(!hostId){if(!machine||machine.length>256)refuse3("Stable host identity is unavailable.");hostId=createHmac("sha256",machine).update("Qwen-Code/verified-workspace/v2").digest("hex")}const seconds=stat.birthtimeNs/1000000000n;const nanos=(stat.birthtimeNs%1000000000n).toString().padStart(9,"0");const fraction=nanos==="000000000"?"":`.${nanos.endsWith("000000")?nanos.slice(0,3):nanos.endsWith("000")?nanos.slice(0,6):nanos}`;return{root,hostId,device:BigInt.asUintN(64,stat.dev).toString(),inode:BigInt.asUintN(64,stat.ino).toString(),birthTime:new Date(Number(seconds)*1e3).toISOString().replace(/\.000Z$/,`${fraction}Z`)}}__name(inspectSshStorage,"inspectSshStorage");async function verifySshStorage(identity,marker){if(!isDeepStrictEqual(await inspectSshStorage(identity.root),identity))refuse3("Registered storage identity changed.");if(marker&&!isDeepStrictEqual(await readSshPrivateJson(path3.join(identity.root,MARKER)),marker))refuse3("Registered storage marker changed.")}__name(verifySshStorage,"verifySshStorage");function resourceDirectory(stateDirectory,resourceId){if(!UUID.test(resourceId))refuse3("Runtime resource identity is invalid.");return path3.join(stateDirectory,"resources",resourceId)}__name(resourceDirectory,"resourceDirectory");async function readSshRuntimeRecord(directory){const value=object(await readSshPrivateJson(path3.join(directory,"intent.json")));exact(value,["version","nodeId","stateDirectory","resourceId","bindingId","bindingGeneration","boot","identity","marker","workerEntry","expectedQwenVersion"]);const identity=identityDocument(value["identity"]);const boot=parseManagedContextBoot(value["boot"]);const marker=markerDocument(value["marker"],identity);if(value["version"]!==1||!ID.test(text(value["nodeId"]))||!ID.test(text(value["bindingId"]))||!Number.isSafeInteger(value["bindingGeneration"])||Number(value["bindingGeneration"])<=0||boot.isolationClass!=="session"||boot.mountRoot!==identity.root||boot.tenantId!==marker.tenantId||boot.storageId!==marker.storageId||resourceDirectory(absolute(value["stateDirectory"]),text(value["resourceId"]))!==directory)refuse3("Runtime intent identity is invalid.");absolute(value["workerEntry"]);text(value["expectedQwenVersion"]);return value}__name(readSshRuntimeRecord,"readSshRuntimeRecord");function sshCleanProof(record,retirementId,retiredAt){return{version:record.boot.managedExtensions?2:1,...record.boot.managedExtensions?{executionMode:record.boot.managedExtensions.mode,scope:record.boot.managedExtensions.mode==="linux-cgroup"?"process_tree":"process_group"}:{},resourceId:record.resourceId,bindingId:record.bindingId,bindingGeneration:record.bindingGeneration,provisionRequestId:record.boot.provisionRequestId,runtimeInstanceId:record.boot.runtimeInstanceId,runtimeIncarnation:record.boot.runtimeIncarnation,leaseId:record.boot.leaseId,epoch:record.boot.epoch,retirementId,retiredAt}}__name(sshCleanProof,"sshCleanProof");function alive(pid){try{process.kill(pid,0);return true}catch(error){if(error.code==="ESRCH")return false;throw new SshBootstrapError("ssh_runtime_stop_unverified","Original process liveness is unverified.")}}__name(alive,"alive");async function optionalJson(file){try{return await readSshPrivateJson(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}__name(optionalJson,"optionalJson");async function observe(record){await verifySshStorage(record.identity,record.marker);const directory=resourceDirectory(record.stateDirectory,record.resourceId);const pidRecord=await optionalJson(path3.join(directory,"pid.json"));const pid=pidRecord===void 0?null:object(pidRecord)["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Runtime process record is invalid.");const result={resourceId:record.resourceId,state:"INTENT",pid,ready:null};const claim=await optionalJson(path3.join(directory,"launch.claim"));if(claim===void 0){for(const file of["pid.json","ready.json","clean.json","stdout.log","stderr.log","launch-failed.json"]){try{await fs3.lstat(path3.join(directory,file))}catch(error){if(error.code==="ENOENT")continue;throw error}refuse3("Runtime launch claim is missing from an existing resource.")}return result}const claimedRetirement=object(claim)["retirementId"];const neverStarted=typeof claimedRetirement==="string"&&UUID.test(claimedRetirement);if(!isDeepStrictEqual(claim,neverStarted?{provisionRequestId:record.boot.provisionRequestId,retirementId:claimedRetirement}:{provisionRequestId:record.boot.provisionRequestId}))refuse3("Runtime launch claim conflicts.");if(neverStarted&&pid!==null)refuse3("A retired launch claim cannot own a worker process.");const failed2=await optionalJson(path3.join(directory,"launch-failed.json"));if(failed2!==void 0&&(!isDeepStrictEqual(failed2,{provisionRequestId:record.boot.provisionRequestId})||pid!==null||await optionalJson(path3.join(directory,"ready.json"))!==void 0))refuse3("Runtime failed-launch evidence conflicts.");const clean=await optionalJson(path3.join(directory,"clean.json"));if(clean!==void 0){const proof=object(clean);const retiredAt=text(proof["retiredAt"]);const stop=object(await readSshPrivateJson(path3.join(directory,"stop.json")));if(!Number.isFinite(Date.parse(retiredAt))||!isDeepStrictEqual(clean,sshCleanProof(record,text(stop["retirementId"]),retiredAt)))refuse3("Runtime clean proof conflicts.");if((neverStarted||failed2!==void 0)&&pid===null&&(failed2!==void 0||claimedRetirement===stop["retirementId"])||pid!==null&&!alive(Number(pid)))return{...result,state:"RETIRED",cleanProof:clean};return{...result,state:"BLOCKED"}}if(failed2!==void 0)return{...result,state:"FAILED"};if(neverStarted&&pid===null)return result;if(pid===null||!alive(Number(pid)))return{...result,state:"BLOCKED"};const ready=await optionalJson(path3.join(directory,"ready.json"));if(ready===void 0)return{...result,state:"STARTING"};const value=object(ready);if(!isManagedContextReady(value,record.boot))refuse3("Runtime ready identity conflicts.");return{...result,state:"READY",ready:value}}__name(observe,"observe");async function attest(record,ready){const expected=createManagedContextAttestationResponse(record.boot);const{runtimeInstanceId:_runtime,runtimeIncarnation:_incarnation,leaseId:_lease,epoch:_epoch,...request}=expected;const response=await fetch(`${ready.url}/internal/managed-runtime/v3/attest`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify(request),redirect:"error",signal:AbortSignal.timeout(5e3)});if(!response.ok||!isDeepStrictEqual(await response.json(),expected))refuse3("Original Runtime attestation failed.")}__name(attest,"attest");function sshRuntimeHeaders(boot){return{Authorization:`Bearer ${boot.token}`,"Cache-Control":"no-store","Content-Type":"application/json","X-Qwen-Managed-Lease-Id":boot.leaseId,"X-Qwen-Managed-Lease-Epoch":String(boot.epoch)}}__name(sshRuntimeHeaders,"sshRuntimeHeaders");async function ensure(request,nodeId,stateDirectory){const resourceId=text(request["resourceId"]);const expectedQwenVersion=text(request["expectedQwenVersion"]);if(expectedQwenVersion!==await getCliVersion()){throw new SshBootstrapError("ssh_runtime_version_conflict","Pinned Qwen version does not match this installation.")}const directory=resourceDirectory(stateDirectory,resourceId);const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity,marker);await privateDirectory(directory);const record={version:1,nodeId,stateDirectory,resourceId,bindingId:request["bindingId"],bindingGeneration:request["bindingGeneration"],boot:request["boot"],identity,marker,workerEntry:absolute(request["workerEntry"]),expectedQwenVersion};await writeSshPrivateJson(path3.join(directory,"intent.json"),record);const saved=await readSshRuntimeRecord(directory);if(typeof request["launch"]!=="boolean")refuse3("Runtime launch phase is required.");if(!request["launch"])return observe(saved);if(await optionalJson(path3.join(directory,"stop.json"))!==void 0)return observe(saved);const original=await observe(saved);if(original["state"]!=="INTENT")return original;if(!await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:saved.boot.provisionRequestId}))return observe(saved);let spawned=false;try{const output=await fs3.open(path3.join(directory,"stdout.log"),"ax",384);try{const errors=await fs3.open(path3.join(directory,"stderr.log"),"ax",384);try{const env={};for(const key of["PATH","HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","TMPDIR","TMP","TEMP","TZ"]){if(process.env[key]!==void 0)env[key]=process.env[key]}const child=spawn(process.execPath,[saved.workerEntry,"managed-runtime-bootstrap-worker",directory],{cwd:path3.dirname(saved.workerEntry),detached:true,stdio:["ignore",output.fd,errors.fd],env});await new Promise((resolve,reject)=>{child.once("spawn",resolve);child.once("error",reject)});spawned=true;child.unref();await writeSshPrivateJson(path3.join(directory,"pid.json"),{pid:child.pid})}finally{await errors.close()}}finally{await output.close()}}catch{if(!spawned){await writeSshPrivateJson(path3.join(directory,"launch-failed.json"),{provisionRequestId:saved.boot.provisionRequestId});return observe(saved)}}for(let attempt=0;attempt<100;attempt++){const observed=await observe(saved);if(observed["state"]!=="STARTING"&&!(observed["state"]==="BLOCKED"&&observed["pid"]===null))return observed;await new Promise(resolve=>setTimeout(resolve,50))}return observe(saved)}__name(ensure,"ensure");async function workspaceUpload(request,expected,verifyStorage,sessionScope){const{metadata,bytes}=workspaceUploadRequest(request["files"]);const root=absolute(request["root"]);const cwd=sessionScope?.cwdRelative??workspaceFilePath(request["cwdRelative"]);const target={nodeId:request["nodeId"],root,cwd,expected,identity:request["identity"]??null,marker:request["marker"]??null,...sessionScope?{sessionFileScope:sessionScope}:{},...metadata};const canonical=__name(value=>value&&typeof value==="object"&&!Array.isArray(value)?Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,item])=>[key,canonical(item)])):value,"canonical");const requestDigest=createHash3("sha256").update(JSON.stringify(canonical(target))).digest("hex");const stateDirectory=absolute(request["stateDirectory"]);await privateDirectory(stateDirectory);const directory=path3.join(stateDirectory,"workspace-uploads",metadata.uploadId);await privateDirectory(directory);const claimPath=path3.join(directory,"claim.json");const receiptPath=path3.join(directory,"receipt.json");let claim=await optionalJson(claimPath);let started=false;if(claim===void 0){if(await optionalJson(receiptPath)!==void 0)refuse3("Workspace upload claim is unavailable.");const proposed={version:1,target,requestDigest,pid:bytes===void 0?null:process.pid};started=await createSshPrivateJson(claimPath,proposed);claim=started?proposed:await readSshPrivateJson(claimPath)}const saved=object(claim);exact(saved,["version","target","requestDigest","pid"]);if(saved["version"]!==1||saved["requestDigest"]!==requestDigest||!isDeepStrictEqual(saved["target"],target))throw new WorkspaceFileError("ssh_runtime_file_upload_conflict");const pid=saved["pid"];if(pid!==null&&(!Number.isSafeInteger(pid)||Number(pid)<=1))refuse3("Workspace upload process identity is invalid.");const receipt=await optionalJson(receiptPath);if(receipt!==void 0){const result2=object(receipt);if(!["completed","failed"].includes(String(result2["state"]))||result2["state"]==="failed"&&typeof result2["code"]!=="string"||!isDeepStrictEqual(receipt,workspaceUploadResult(metadata,result2["state"],result2["code"])))refuse3("Workspace upload receipt is invalid.");return receipt}let result;if(pid===null){result=workspaceUploadResult(metadata,"failed","ssh_runtime_file_upload_not_started")}else if(started&&bytes!==void 0){result=await writeWorkspaceUpload(root,cwd,metadata,bytes,expected,verifyStorage,sessionScope)}else{let live=true;try{live=alive(Number(pid))}catch{}if(live)return workspaceUploadResult(metadata,"pending");result=await inspectWorkspaceUpload(root,cwd,metadata,expected,verifyStorage,sessionScope)}await writeSshPrivateJson(receiptPath,result);return result}__name(workspaceUpload,"workspaceUpload");async function executeSshBootstrap(value){const request=object(value);if(request["protocolVersion"]!==1||!ID.test(text(request["nodeId"])))refuse3("Runtime bootstrap protocol is invalid.");const nodeId=text(request["nodeId"]);const stateDirectory=absolute(request["stateDirectory"]);const operation=text(request["operation"]);if(operation==="probe"||operation==="ensure"){if(Number(process.versions.node.split(".")[0])<22){throw new SshBootstrapError("ssh_runtime_node_unsupported","Runtime requires Node.js 22 or later.")}}if(operation==="probe"){const root=absolute(request["root"]);const roots=request["allowedRoots"];if(!Array.isArray(roots)||roots.length===0||!roots.some(candidate=>within(absolute(candidate),root)))refuse3("Directory is outside the configured roots.");if(within(root,stateDirectory)||within(stateDirectory,root))refuse3("Runtime state and Workspace roots must not overlap.");if(request["files"]!==void 0){const fileOperation=object(request["files"])["operation"];const uploading=["upload","upload-status"].includes(String(fileOperation));const identity2=request["identity"]===void 0?void 0:identityDocument(request["identity"]);const marker=identity2?markerDocument(request["marker"],identity2):void 0;if(identity2&&identity2.root!==root)refuse3("Storage root conflicts.");if(identity2&&!uploading)await verifySshStorage(identity2,marker);const expected=identity2??object(request["localRootIdentity"]);try{if(request["sessionFileScope"]!==void 0&&identity2)refuse3("Session file scopes require local storage.");const sessionScope=sessionWorkspaceFileScope(request["sessionFileScope"],request["cwdRelative"]);const fileIdentity={device:text(expected.device),inode:text(expected.inode)};const files=uploading?await workspaceUpload(request,fileIdentity,async()=>{if(identity2)await verifySshStorage(identity2,marker)},sessionScope):await readWorkspaceFiles(root,text(request["cwdRelative"]),request["files"],fileIdentity,sessionScope);if(identity2&&!uploading)await verifySshStorage(identity2,marker);return{qwenVersion:await getCliVersion(),files}}catch(error){if(error instanceof WorkspaceFileError)throw new SshBootstrapError(error.code,error.message);throw error}}const identity=await inspectSshStorage(root);if(request["cwdRelative"]!==void 0){const relative=text(request["cwdRelative"]);const cwd=path3.resolve(root,relative);if(path3.isAbsolute(relative)||!within(root,cwd)||cwd!==await fs3.realpath(cwd)||!(await fs3.stat(cwd)).isDirectory())refuse3("Working directory is unavailable.");await fs3.access(cwd,constants3.R_OK|constants3.W_OK|constants3.X_OK)}return{platform:process.platform,nodeVersion:process.version,qwenVersion:await getCliVersion(),identity,marker:await optionalJson(path3.join(root,MARKER))??null}}if(operation==="register-storage"){const identity=identityDocument(request["identity"]);const marker=markerDocument(request["marker"],identity);if(within(identity.root,stateDirectory)||within(stateDirectory,identity.root))refuse3("Runtime state and Workspace roots must not overlap.");await verifySshStorage(identity);await writeSshPrivateJson(path3.join(identity.root,MARKER),marker);await verifySshStorage(identity,marker);return{identity,marker}}await privateDirectory(stateDirectory);if(operation==="ensure")return ensure(request,nodeId,stateDirectory);const directory=resourceDirectory(stateDirectory,text(request["resourceId"]));const record=await readSshRuntimeRecord(directory);if(record.nodeId!==nodeId||record.stateDirectory!==stateDirectory)refuse3("Runtime node identity conflicts.");let observed=await observe(record);if(operation==="observe")return observed;if(operation!=="stop")refuse3("Runtime bootstrap operation is unsupported.");const retirementId=text(request["retirementId"]);if(!UUID.test(retirementId))refuse3("Runtime retirement identity is invalid.");if(observed["state"]==="INTENT"){await createSshPrivateJson(path3.join(directory,"launch.claim"),{provisionRequestId:record.boot.provisionRequestId,retirementId});observed=await observe(record)}const claim=object(await readSshPrivateJson(path3.join(directory,"launch.claim")));if(claim["retirementId"]!==void 0&&claim["retirementId"]!==retirementId)refuse3("Runtime retirement identity conflicts.");if(observed["state"]==="RETIRED"){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});return observed}if(observed["state"]==="FAILED"||claim["retirementId"]===retirementId){await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});await verifySshStorage(record.identity,record.marker);await writeSshPrivateJson(path3.join(directory,"clean.json"),sshCleanProof(record,retirementId,new Date().toISOString()));return observe(record)}if(observed["state"]==="STARTING"||observed["state"]==="BLOCKED"&&observed["pid"]===null)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime startup has not completed.",true);if(observed["state"]!=="READY")throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime is not reachable for clean retirement.");await writeSshPrivateJson(path3.join(directory,"stop.json"),{retirementId});const ready=observed["ready"];try{await attest(record,ready);const response=await fetch(`${ready.url}${SSH_RETIRE_PATH}`,{method:"POST",headers:sshRuntimeHeaders(record.boot),body:JSON.stringify({protocolVersion:1,resourceId:record.resourceId,retirementId}),redirect:"error",signal:AbortSignal.timeout(15e3)});if(!response.ok)throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement is not proven.",true);await response.arrayBuffer()}catch(error){if(error instanceof SshBootstrapError)throw error;if((await observe(record))["state"]!=="RETIRED")throw new SshBootstrapError("ssh_runtime_retirement_pending","Original Runtime retirement response is unavailable.",true)}for(let attempt=0;attempt<100;attempt++){const result=await observe(record);if(result["state"]==="RETIRED")return result;await new Promise(resolve=>setTimeout(resolve,50))}throw new SshBootstrapError("ssh_runtime_stop_unverified","Original Runtime process has not exited.",true)}__name(executeSshBootstrap,"executeSshBootstrap");async function runManagedRuntimeBootstrap(help=false,workspaceFileUpload=false){if(help){process.stdout.write(`${JSON.stringify({protocolVersion:1,capabilities:{workspaceFiles:1,workspaceFileUpload:1}})}
|
|
4
4
|
`);return}let response;try{const chunks=[];let size=0;for await(const chunk of process.stdin){const bytes=Buffer.from(chunk);size+=bytes.length;if(size>(workspaceFileUpload?MAX_UPLOAD_REQUEST_BYTES:MAX_BYTES))refuse3("Runtime bootstrap request exceeds its limit.");chunks.push(bytes)}const source=new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks));const request=object(JSON.parse(source));const files=request["files"];const upload=files&&typeof files==="object"&&!Array.isArray(files)?["upload","upload-status"].includes(String(files["operation"])):false;if(workspaceFileUpload!==upload||upload&&request["operation"]!=="probe")refuse3("Workspace upload requires its dedicated bootstrap entry.");response={protocolVersion:1,ok:true,result:await executeSshBootstrap(request)}}catch(error){const known=error instanceof SshBootstrapError?error:new SshBootstrapError("ssh_runtime_state_unavailable","Runtime bootstrap state is unavailable.");response={protocolVersion:1,ok:false,error:{code:known.code,message:known.message,retryable:known.retryable}}}process.stdout.write(`${JSON.stringify(response)}
|
|
5
5
|
`)}__name(runManagedRuntimeBootstrap,"runManagedRuntimeBootstrap");function sshResourcePath(record){return resourceDirectory(record.stateDirectory,record.resourceId)}__name(sshResourcePath,"sshResourcePath");export{SSH_RETIRE_PATH,SshBootstrapError,readSshPrivateJson,writeSshPrivateJson,inspectSshStorage,verifySshStorage,readSshRuntimeRecord,sshCleanProof,sshRuntimeHeaders,executeSshBootstrap,runManagedRuntimeBootstrap,sshResourcePath};
|
|
6
6
|
/**
|