gerege-cli 0.26.6 → 0.26.7
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-QCIXIS4P.js → MaxSizedBox-LSNOJEKM.js} +1 -1
- package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-KSYGPMEV.js} +1 -1
- package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-NSW2MFUI.js} +1 -1
- package/chunks/{acpAgent-67UN66PB.js → acpAgent-3DTOHTDM.js} +3 -3
- package/chunks/{advisor-SAXMI4QZ.js → advisor-7JGQPS7X.js} +1 -1
- package/chunks/{agent-KV7BXY6C.js → agent-PNKQJGDO.js} +1 -1
- package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-7D33X7QQ.js} +1 -1
- package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-3R2MAUVE.js} +1 -1
- package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-2D7DECAE.js} +1 -1
- package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-MGTJJGEQ.js} +1 -1
- package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-OIHHZSPQ.js} +1 -1
- package/chunks/{batch-XFVQ4BLM.js → batch-6UDAMPAA.js} +1 -1
- package/chunks/{bridge-AE7AFEXB.js → bridge-QXVXPNJ6.js} +1 -1
- package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-P4W4R5SJ.js} +1 -1
- package/chunks/{chunk-RXN7DUMP.js → chunk-2J2BQ3PL.js} +2 -2
- package/chunks/{chunk-7453BHJO.js → chunk-2LMSDH6P.js} +1 -1
- package/chunks/{chunk-32XHDDIA.js → chunk-3EZ5GCUT.js} +1 -1
- package/chunks/{chunk-AYVCT5FF.js → chunk-3ICJI5KW.js} +1 -1
- package/chunks/{chunk-VRKYBH5G.js → chunk-4A663FE6.js} +5 -5
- package/chunks/{chunk-DA6LOBSB.js → chunk-4AKTP4MM.js} +1 -1
- package/chunks/{chunk-T53VMDXH.js → chunk-4LC4INFI.js} +1 -1
- package/chunks/{chunk-65ME4BOH.js → chunk-4QOVM2LL.js} +1 -1
- package/chunks/{chunk-MYV7GY3H.js → chunk-4VR4DUUD.js} +1 -1
- package/chunks/{chunk-GRAECADD.js → chunk-4W27Z3OL.js} +1 -1
- package/chunks/{chunk-B37YY4XU.js → chunk-53IB4U4E.js} +1 -1
- package/chunks/{chunk-OK7LBM5G.js → chunk-5R2JIZID.js} +1 -1
- package/chunks/{chunk-I6PUY2T3.js → chunk-5TWAP4OG.js} +1 -1
- package/chunks/{chunk-CBE6ZIHU.js → chunk-6JAXAFX7.js} +1 -1
- package/chunks/{chunk-OOJ2AQT3.js → chunk-6WV5RKYB.js} +1 -1
- package/chunks/{chunk-ELDZ4MNL.js → chunk-6YFNUVJR.js} +1 -1
- package/chunks/{chunk-3W32X2DH.js → chunk-7HFFTOAD.js} +1 -1
- package/chunks/{chunk-YH2XRWRF.js → chunk-ATTJQLQV.js} +1 -1
- package/chunks/{chunk-T5DKF33F.js → chunk-BIPPD7W6.js} +1 -1
- package/chunks/{chunk-CF6SZJNP.js → chunk-BVV7UXES.js} +1 -1
- package/chunks/{chunk-CGDFZEER.js → chunk-BY46PCWY.js} +1 -1
- package/chunks/{chunk-AEZYXPFS.js → chunk-CDKBM72V.js} +1 -1
- package/chunks/{chunk-OU7CEG7Q.js → chunk-CK3OKTTL.js} +1 -1
- package/chunks/{chunk-FKL3V5BO.js → chunk-DEJ47KJE.js} +1 -1
- package/chunks/{chunk-FEP6W4NJ.js → chunk-DQQN2HOP.js} +1 -1
- package/chunks/{chunk-SKGJ26HQ.js → chunk-DTX2OVQW.js} +1 -1
- package/chunks/{chunk-EXIFPXMB.js → chunk-DVUKYOCJ.js} +1 -1
- package/chunks/{chunk-FKZ46GKL.js → chunk-E3KWSRJN.js} +1 -1
- package/chunks/{chunk-BAUMVH4Q.js → chunk-EEPNACXJ.js} +1 -1
- package/chunks/{chunk-76FSYQTG.js → chunk-F5SLLEJY.js} +1 -1
- package/chunks/{chunk-IZ5MWA6E.js → chunk-F7622ZRQ.js} +1 -1
- package/chunks/{chunk-TB4AUC2L.js → chunk-FKUDVIME.js} +1 -1
- package/chunks/{chunk-SP6CQ3MO.js → chunk-FRVXSKL4.js} +1 -1
- package/chunks/{chunk-XISR37DQ.js → chunk-FTF2NFLB.js} +1 -1
- package/chunks/{chunk-NONBHCXP.js → chunk-G4MWPXNY.js} +1 -1
- package/chunks/{chunk-JRTOPEM3.js → chunk-GA35LMSX.js} +1 -1
- package/chunks/{chunk-GHIFIXNX.js → chunk-H34KVVI4.js} +1 -1
- package/chunks/{chunk-AFO5ER23.js → chunk-H5EXNXGW.js} +1 -1
- package/chunks/{chunk-ZENMAISJ.js → chunk-HJLRKM3W.js} +1 -1
- package/chunks/{chunk-BCI62WSL.js → chunk-HVP4UF2Q.js} +1 -1
- package/chunks/{chunk-AEKEZRIU.js → chunk-HXTYFGSQ.js} +1 -1
- package/chunks/{chunk-KJGRCIVY.js → chunk-IIHUDJX7.js} +1 -1
- package/chunks/{chunk-RSLTOIG5.js → chunk-IQMKQKKD.js} +2 -2
- package/chunks/{chunk-JWNKPINR.js → chunk-ISQMHOCC.js} +1 -1
- package/chunks/{chunk-OJ4K62S2.js → chunk-IY7M5HKF.js} +1 -1
- package/chunks/{chunk-LBLLWAKK.js → chunk-IZXHCHJD.js} +1 -1
- package/chunks/{chunk-NVOI6UDQ.js → chunk-JHC22BZH.js} +1 -1
- package/chunks/{chunk-BPFFRPWE.js → chunk-K7GN4CMV.js} +6 -6
- package/chunks/{chunk-N7PWZBXV.js → chunk-L7LO3YRT.js} +1 -1
- package/chunks/{chunk-MGATL4OA.js → chunk-LY4XTBL4.js} +1 -1
- package/chunks/{chunk-JEDL4IKF.js → chunk-LYFRGP42.js} +1 -1
- package/chunks/{chunk-G6DALGGS.js → chunk-MDCA4I63.js} +1 -1
- package/chunks/{chunk-W5Z4BWWA.js → chunk-MS2XCBPP.js} +1 -1
- package/chunks/{chunk-GBSRWT7J.js → chunk-MXZXQUVP.js} +1 -1
- package/chunks/{chunk-VD2GSW64.js → chunk-N4ZQC5HB.js} +1 -1
- package/chunks/{chunk-2LWJGXTW.js → chunk-N6EFYQ7M.js} +1 -1
- package/chunks/{chunk-P62S5JGM.js → chunk-NHPKD7LY.js} +1 -1
- package/chunks/{chunk-W66WWTOP.js → chunk-NPAENNRO.js} +1 -1
- package/chunks/{chunk-EYPLBTMI.js → chunk-NYBYDW6R.js} +1 -1
- package/chunks/{chunk-7RNOS7R4.js → chunk-O3TUZQP4.js} +1 -1
- package/chunks/{chunk-JH3V5SPA.js → chunk-OZFZBGZG.js} +1 -1
- package/chunks/{chunk-QDCUR3JB.js → chunk-P2MZZMCS.js} +1 -1
- package/chunks/{chunk-KZNYALFU.js → chunk-PMBI46K4.js} +1 -1
- package/chunks/{chunk-2TAJ5STJ.js → chunk-Q5RRVBTY.js} +1 -1
- package/chunks/{chunk-H3IR3GIE.js → chunk-QHYSRPQR.js} +1 -1
- package/chunks/{chunk-NA4ZF2FE.js → chunk-QONPET6Y.js} +2 -2
- package/chunks/{chunk-W2RQIZ6B.js → chunk-QSPXKBUX.js} +1 -1
- package/chunks/{chunk-WGFX3EL3.js → chunk-QTKPC24L.js} +1 -1
- package/chunks/{chunk-BHIDG6VZ.js → chunk-QTVSPQZQ.js} +1 -1
- package/chunks/{chunk-HOG66S6K.js → chunk-QVHDM6N7.js} +1 -1
- package/chunks/{chunk-4NDJKNN6.js → chunk-RT6J7PV4.js} +1 -1
- package/chunks/{chunk-NEKPQLFY.js → chunk-RULGA7WE.js} +2 -2
- package/chunks/{chunk-LTE4N6L3.js → chunk-SAVYMUU3.js} +1 -1
- package/chunks/{chunk-2JGTWRZJ.js → chunk-T3CQ72HC.js} +6 -6
- package/chunks/{chunk-FYBJGRX7.js → chunk-U5YOAOU3.js} +1 -1
- package/chunks/{chunk-EFIRES46.js → chunk-ULLW2AYD.js} +1 -1
- package/chunks/{chunk-MPVQDYPH.js → chunk-UM5KBBYP.js} +1 -1
- package/chunks/{chunk-M6KB5RVD.js → chunk-UVMLWDRU.js} +1 -1
- package/chunks/{chunk-5EXL4TKQ.js → chunk-VK7LOUOJ.js} +1 -1
- package/chunks/{chunk-T2YTHAJW.js → chunk-VUNHJ74J.js} +1 -1
- package/chunks/{chunk-HTAUIJB4.js → chunk-W2CV36HT.js} +1 -1
- package/chunks/{chunk-ET5M5WFN.js → chunk-WCI33URB.js} +1 -1
- package/chunks/{chunk-P3JEEDQZ.js → chunk-WEPC42YR.js} +1 -1
- package/chunks/{chunk-BQZF3UKI.js → chunk-WF7Q3ZSQ.js} +1 -1
- package/chunks/{chunk-GSPGIGO5.js → chunk-WK666FGZ.js} +3 -3
- package/chunks/{chunk-CUP2TNJK.js → chunk-WMLYHZZX.js} +1 -1
- package/chunks/{chunk-2N3NBTYJ.js → chunk-WSI4G7XC.js} +1 -1
- package/chunks/{chunk-U3Q72OGV.js → chunk-WXK7Z45R.js} +1 -1
- package/chunks/{chunk-MTDBCIDA.js → chunk-YWK3E4WJ.js} +1 -1
- package/chunks/{chunk-34HC2AXI.js → chunk-YY4GWNTU.js} +2 -2
- package/chunks/{chunk-UKLXKJKL.js → chunk-ZFOEVHWG.js} +1 -1
- package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-GPTKVP7H.js} +1 -1
- package/chunks/{config-utils-OWY5G5Y2.js → config-utils-6B5FHBSF.js} +1 -1
- package/chunks/{contextCommand-IXFUZH65.js → contextCommand-FGRDE3GA.js} +1 -1
- package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-OFEHSKDB.js} +1 -1
- package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-D2KEWVHQ.js} +1 -1
- package/chunks/{cron-create-2422NBSJ.js → cron-create-RFGGKTL7.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-AV752IOZ.js} +1 -1
- package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-GHQBRDMC.js} +1 -1
- package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-24ENJNTQ.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-NMSQAGWV.js} +1 -1
- package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-5BAMFFOI.js} +1 -1
- package/chunks/{edit-E5LEI2LL.js → edit-XCECLEH3.js} +1 -1
- package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-SEN2PMRM.js} +1 -1
- package/chunks/{environment-XBBIB3VA.js → environment-CCPQJYKS.js} +1 -1
- package/chunks/{errors-LNMQ7TUK.js → errors-Y6HHUTGK.js} +1 -1
- package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-HADWGMIG.js} +1 -1
- package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-GZS7WOQL.js} +1 -1
- package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-76B5HDLT.js} +1 -1
- package/chunks/{fast-path-M6K2RACY.js → fast-path-OEV7LQYV.js} +1 -1
- package/chunks/{glob-N2QT4U7U.js → glob-NLWCQRMS.js} +1 -1
- package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-43XV33BT.js} +1 -1
- package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-JDQWGSSP.js} +1 -1
- package/chunks/{i18n-AGOA6MUI.js → i18n-JW6BVEGF.js} +1 -1
- package/chunks/{initializer-FRKYDUSX.js → initializer-UT6JLZ3O.js} +1 -1
- package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-LKWDV3S2.js} +1 -1
- package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-2KWKYVPC.js} +1 -1
- package/chunks/{list-DE7VUIR2.js → list-BKINK3S2.js} +1 -1
- package/chunks/{llm-N3JGJHYC.js → llm-3RWXAVM2.js} +4 -4
- package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-MDRBSH73.js} +1 -1
- package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-WWJUKWUN.js} +1 -1
- package/chunks/{local-BE624O3A.js → local-TT4FLCTR.js} +1 -1
- package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-OBA6VWYL.js} +1 -1
- package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-CK7IKYQH.js} +1 -1
- package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-4MSRX3DY.js} +1 -1
- package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-PX5PZJKZ.js} +1 -1
- package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-WMAUR3ZK.js} +1 -1
- package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-X7REHGB4.js} +1 -1
- package/chunks/{managed-npm-update-CTL6LH5Z.js → managed-npm-update-6HUVAJH7.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-F4AT53M5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-3BP5JRJX.js} +1 -1
- package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-2PO7J5UK.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-4N7EMRSV.js} +1 -1
- package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-MYOYTUM2.js} +1 -1
- package/chunks/{mcp-VC4CJPE5.js → mcp-5OTEMZ7P.js} +1 -1
- package/chunks/{memory-S6OJA3ZD.js → memory-TNW7RSAV.js} +1 -1
- package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-KNTWFZQS.js} +1 -1
- package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-U5C5P5UQ.js} +1 -1
- package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-R4KFI2WK.js} +1 -1
- package/chunks/{monitor-M3PNLCYP.js → monitor-RD2PFK42.js} +1 -1
- package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-QQ72HZSH.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-QPQYR6IS.js} +1 -1
- package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-YLRN3UZT.js} +1 -1
- package/chunks/{omni-6YBX4R6K.js → omni-CUJ52EW5.js} +1 -1
- package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-6B5MAU54.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-I245I3R7.js} +1 -1
- package/chunks/{pidfile-XR4JF2Z6.js → pidfile-P2HIGAUA.js} +1 -1
- package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JSKN5UGS.js} +1 -1
- package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-F5TSXVGU.js} +1 -1
- package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-IEDZONWG.js} +1 -1
- package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-FYZBJCF6.js} +1 -1
- package/chunks/{read-file-VD7OFO2E.js → read-file-VNZNSD6X.js} +1 -1
- package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-IDPE6N2N.js} +1 -1
- package/chunks/{review-C365WGCW.js → review-TBJRZWTD.js} +1 -1
- package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-4W5B5FOE.js} +1 -1
- package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-44X262G5.js} +1 -1
- package/chunks/{runtime-J6SPBSCS.js → runtime-6H6LKD73.js} +1 -1
- package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-SQXDRGVN.js} +1 -1
- package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-62IZKHJG.js} +1 -1
- package/chunks/{scheduler-KCMSPHON.js → scheduler-QUCXJYRL.js} +1 -1
- package/chunks/{search-memory-EUBJ7IAV.js → search-memory-TC2Z34QN.js} +1 -1
- package/chunks/{send-message-CWWZUPSK.js → send-message-TFZX7KI7.js} +1 -1
- package/chunks/{serve-4CB4BWJ5.js → serve-WSICDFGG.js} +1 -1
- package/chunks/{server-JNANUIGC.js → server-GYYVTNGY.js} +3 -3
- package/chunks/{session-3LQLXPUA.js → session-KF3O23ZJ.js} +1 -1
- package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-7HFUSONH.js} +1 -1
- package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-NVILT6BR.js} +1 -1
- package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-3KDFTDEV.js} +1 -1
- package/chunks/{sessionService-U7ACD2HP.js → sessionService-XRTFLPDW.js} +1 -1
- package/chunks/{settings-FTGWYTUH.js → settings-QPPK6WXE.js} +1 -1
- package/chunks/{shell-E4RENYQC.js → shell-WYQDZWL7.js} +1 -1
- package/chunks/{skill-OLNPHRWB.js → skill-FYPT6AU7.js} +1 -1
- package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-OGFI5KZF.js} +1 -1
- package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-ANOOVPG7.js} +1 -1
- package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-45WTDY4E.js} +1 -1
- package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-TL5WK33V.js} +1 -1
- package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-N2IREVBM.js} +1 -1
- package/chunks/{team-create-HAVKHNU5.js → team-create-R77PRZ5U.js} +1 -1
- package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-6DCRKB5I.js} +1 -1
- package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-TB7EX2WW.js} +1 -1
- package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-RQDXJGVR.js} +1 -1
- package/chunks/{tool-call-LZHZ5RVH.js → tool-call-LVB4NCDT.js} +1 -1
- package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-LRBB2KS6.js} +1 -1
- package/chunks/{tool-search-K6S3ON7M.js → tool-search-OG73QAQZ.js} +1 -1
- package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-A4CUF6AD.js} +1 -1
- package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-LSGOYTU2.js} +1 -1
- package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-OGC6BZO7.js} +1 -1
- package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-7J3GXTER.js} +1 -1
- package/chunks/{upload-config-TCCFCNCD.js → upload-config-ML5XEJIF.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-6DH6GQ2X.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-KJDAGZCM.js} +1 -1
- package/chunks/{version-JYWKKMNP.js → version-7JN2YXL2.js} +1 -1
- package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-42ZR4FEZ.js} +1 -1
- package/chunks/{web-search-HAI5LW3G.js → web-search-74NLPMZJ.js} +1 -1
- package/chunks/{workflow-BZ2YFGF6.js → workflow-WNPHX42I.js} +1 -1
- package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-HGF6G7LQ.js} +1 -1
- package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-3YFBFAK3.js} +1 -1
- package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-EPJI6KRV.js} +1 -1
- package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-T3FK5YOD.js} +1 -1
- package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-VEXYBDMA.js} +1 -1
- package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-NRZYTP2X.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-USNSTP2V.js} +1 -1
- package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-USATWO56.js} +1 -1
- package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-M5JTSFDL.js} +1 -1
- package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-ZUZ2O5WC.js} +1 -1
- package/chunks/{write-file-HD5LHXGL.js → write-file-UMJVKE4S.js} +1 -1
- package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-76XYHQ3Z.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/gerege.mjs +11 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{buildTrustPrecedenceRules,resolveTrustDecision,resolveTrustRule}from"./chunk-EIPLDYEY.js";import{arePathsEquivalent,getPathComparisonVariants}from"./chunk-IDXJIDME.js";import{ideContextStore}from"./chunk-2JGTWRZJ.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{atomicWriteFileSync}from"./chunk-BMHYEQTI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{FatalConfigError,getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs4 from"node:fs";import*as path3 from"node:path";init_esbuild_shims();import*as fs2 from"node:fs";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();function createScanner(text,ignoreTrivia=false){const len=text.length;let pos=0,value="",tokenOffset=0,token=16,lineNumber=0,lineStartOffset=0,tokenLineStartOffset=0,prevTokenLineStartOffset=0,scanError=0;function scanHexDigits(count,exact){let digits=0;let value2=0;while(digits<count||!exact){let ch=text.charCodeAt(pos);if(ch>=48&&ch<=57){value2=value2*16+ch-48}else if(ch>=65&&ch<=70){value2=value2*16+ch-65+10}else if(ch>=97&&ch<=102){value2=value2*16+ch-97+10}else{break}pos++;digits++}if(digits<count){value2=-1}return value2}__name(scanHexDigits,"scanHexDigits");function setPosition(newPosition){pos=newPosition;value="";tokenOffset=0;token=16;scanError=0}__name(setPosition,"setPosition");function scanNumber(){let start=pos;if(text.charCodeAt(pos)===48){pos++}else{pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}if(pos<text.length&&text.charCodeAt(pos)===46){pos++;if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}else{scanError=3;return text.substring(start,pos)}}let end=pos;if(pos<text.length&&(text.charCodeAt(pos)===69||text.charCodeAt(pos)===101)){pos++;if(pos<text.length&&text.charCodeAt(pos)===43||text.charCodeAt(pos)===45){pos++}if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}end=pos}else{scanError=3}}return text.substring(start,end)}__name(scanNumber,"scanNumber");function scanString(){let result="",start=pos;while(true){if(pos>=len){result+=text.substring(start,pos);scanError=2;break}const ch=text.charCodeAt(pos);if(ch===34){result+=text.substring(start,pos);pos++;break}if(ch===92){result+=text.substring(start,pos);pos++;if(pos>=len){scanError=2;break}const ch2=text.charCodeAt(pos++);switch(ch2){case 34:result+='"';break;case 92:result+="\\";break;case 47:result+="/";break;case 98:result+="\b";break;case 102:result+="\f";break;case 110:result+="\n";break;case 114:result+="\r";break;case 116:result+=" ";break;case 117:const ch3=scanHexDigits(4,true);if(ch3>=0){result+=String.fromCharCode(ch3)}else{scanError=4}break;default:scanError=5}start=pos;continue}if(ch>=0&&ch<=31){if(isLineBreak(ch)){result+=text.substring(start,pos);scanError=2;break}else{scanError=6}}pos++}return result}__name(scanString,"scanString");function scanNext(){value="";scanError=0;tokenOffset=pos;lineStartOffset=lineNumber;prevTokenLineStartOffset=tokenLineStartOffset;if(pos>=len){tokenOffset=len;return token=17}let code=text.charCodeAt(pos);if(isWhiteSpace(code)){do{pos++;value+=String.fromCharCode(code);code=text.charCodeAt(pos)}while(isWhiteSpace(code));return token=15}if(isLineBreak(code)){pos++;value+=String.fromCharCode(code);if(code===13&&text.charCodeAt(pos)===10){pos++;value+="\n"}lineNumber++;tokenLineStartOffset=pos;return token=14}switch(code){case 123:pos++;return token=1;case 125:pos++;return token=2;case 91:pos++;return token=3;case 93:pos++;return token=4;case 58:pos++;return token=6;case 44:pos++;return token=5;case 34:pos++;value=scanString();return token=10;case 47:const start=pos-1;if(text.charCodeAt(pos+1)===47){pos+=2;while(pos<len){if(isLineBreak(text.charCodeAt(pos))){break}pos++}value=text.substring(start,pos);return token=12}if(text.charCodeAt(pos+1)===42){pos+=2;const safeLength=len-1;let commentClosed=false;while(pos<safeLength){const ch=text.charCodeAt(pos);if(ch===42&&text.charCodeAt(pos+1)===47){pos+=2;commentClosed=true;break}pos++;if(isLineBreak(ch)){if(ch===13&&text.charCodeAt(pos)===10){pos++}lineNumber++;tokenLineStartOffset=pos}}if(!commentClosed){pos++;scanError=1}value=text.substring(start,pos);return token=13}value+=String.fromCharCode(code);pos++;return token=16;case 45:value+=String.fromCharCode(code);pos++;if(pos===len||!isDigit(text.charCodeAt(pos))){return token=16}case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:value+=scanNumber();return token=11;default:while(pos<len&&isUnknownContentCharacter(code)){pos++;code=text.charCodeAt(pos)}if(tokenOffset!==pos){value=text.substring(tokenOffset,pos);switch(value){case"true":return token=8;case"false":return token=9;case"null":return token=7}return token=16}value+=String.fromCharCode(code);pos++;return token=16}}__name(scanNext,"scanNext");function isUnknownContentCharacter(code){if(isWhiteSpace(code)||isLineBreak(code)){return false}switch(code){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}__name(isUnknownContentCharacter,"isUnknownContentCharacter");function scanNextNonTrivia(){let result;do{result=scanNext()}while(result>=12&&result<=15);return result}__name(scanNextNonTrivia,"scanNextNonTrivia");return{setPosition,getPosition:__name(()=>pos,"getPosition"),scan:ignoreTrivia?scanNextNonTrivia:scanNext,getToken:__name(()=>token,"getToken"),getTokenValue:__name(()=>value,"getTokenValue"),getTokenOffset:__name(()=>tokenOffset,"getTokenOffset"),getTokenLength:__name(()=>pos-tokenOffset,"getTokenLength"),getTokenStartLine:__name(()=>lineStartOffset,"getTokenStartLine"),getTokenStartCharacter:__name(()=>tokenOffset-prevTokenLineStartOffset,"getTokenStartCharacter"),getTokenError:__name(()=>scanError,"getTokenError")}}__name(createScanner,"createScanner");function isWhiteSpace(ch){return ch===32||ch===9}__name(isWhiteSpace,"isWhiteSpace");function isLineBreak(ch){return ch===10||ch===13}__name(isLineBreak,"isLineBreak");function isDigit(ch){return ch>=48&&ch<=57}__name(isDigit,"isDigit");var CharacterCodes;(function(CharacterCodes2){CharacterCodes2[CharacterCodes2["lineFeed"]=10]="lineFeed";CharacterCodes2[CharacterCodes2["carriageReturn"]=13]="carriageReturn";CharacterCodes2[CharacterCodes2["space"]=32]="space";CharacterCodes2[CharacterCodes2["_0"]=48]="_0";CharacterCodes2[CharacterCodes2["_1"]=49]="_1";CharacterCodes2[CharacterCodes2["_2"]=50]="_2";CharacterCodes2[CharacterCodes2["_3"]=51]="_3";CharacterCodes2[CharacterCodes2["_4"]=52]="_4";CharacterCodes2[CharacterCodes2["_5"]=53]="_5";CharacterCodes2[CharacterCodes2["_6"]=54]="_6";CharacterCodes2[CharacterCodes2["_7"]=55]="_7";CharacterCodes2[CharacterCodes2["_8"]=56]="_8";CharacterCodes2[CharacterCodes2["_9"]=57]="_9";CharacterCodes2[CharacterCodes2["a"]=97]="a";CharacterCodes2[CharacterCodes2["b"]=98]="b";CharacterCodes2[CharacterCodes2["c"]=99]="c";CharacterCodes2[CharacterCodes2["d"]=100]="d";CharacterCodes2[CharacterCodes2["e"]=101]="e";CharacterCodes2[CharacterCodes2["f"]=102]="f";CharacterCodes2[CharacterCodes2["g"]=103]="g";CharacterCodes2[CharacterCodes2["h"]=104]="h";CharacterCodes2[CharacterCodes2["i"]=105]="i";CharacterCodes2[CharacterCodes2["j"]=106]="j";CharacterCodes2[CharacterCodes2["k"]=107]="k";CharacterCodes2[CharacterCodes2["l"]=108]="l";CharacterCodes2[CharacterCodes2["m"]=109]="m";CharacterCodes2[CharacterCodes2["n"]=110]="n";CharacterCodes2[CharacterCodes2["o"]=111]="o";CharacterCodes2[CharacterCodes2["p"]=112]="p";CharacterCodes2[CharacterCodes2["q"]=113]="q";CharacterCodes2[CharacterCodes2["r"]=114]="r";CharacterCodes2[CharacterCodes2["s"]=115]="s";CharacterCodes2[CharacterCodes2["t"]=116]="t";CharacterCodes2[CharacterCodes2["u"]=117]="u";CharacterCodes2[CharacterCodes2["v"]=118]="v";CharacterCodes2[CharacterCodes2["w"]=119]="w";CharacterCodes2[CharacterCodes2["x"]=120]="x";CharacterCodes2[CharacterCodes2["y"]=121]="y";CharacterCodes2[CharacterCodes2["z"]=122]="z";CharacterCodes2[CharacterCodes2["A"]=65]="A";CharacterCodes2[CharacterCodes2["B"]=66]="B";CharacterCodes2[CharacterCodes2["C"]=67]="C";CharacterCodes2[CharacterCodes2["D"]=68]="D";CharacterCodes2[CharacterCodes2["E"]=69]="E";CharacterCodes2[CharacterCodes2["F"]=70]="F";CharacterCodes2[CharacterCodes2["G"]=71]="G";CharacterCodes2[CharacterCodes2["H"]=72]="H";CharacterCodes2[CharacterCodes2["I"]=73]="I";CharacterCodes2[CharacterCodes2["J"]=74]="J";CharacterCodes2[CharacterCodes2["K"]=75]="K";CharacterCodes2[CharacterCodes2["L"]=76]="L";CharacterCodes2[CharacterCodes2["M"]=77]="M";CharacterCodes2[CharacterCodes2["N"]=78]="N";CharacterCodes2[CharacterCodes2["O"]=79]="O";CharacterCodes2[CharacterCodes2["P"]=80]="P";CharacterCodes2[CharacterCodes2["Q"]=81]="Q";CharacterCodes2[CharacterCodes2["R"]=82]="R";CharacterCodes2[CharacterCodes2["S"]=83]="S";CharacterCodes2[CharacterCodes2["T"]=84]="T";CharacterCodes2[CharacterCodes2["U"]=85]="U";CharacterCodes2[CharacterCodes2["V"]=86]="V";CharacterCodes2[CharacterCodes2["W"]=87]="W";CharacterCodes2[CharacterCodes2["X"]=88]="X";CharacterCodes2[CharacterCodes2["Y"]=89]="Y";CharacterCodes2[CharacterCodes2["Z"]=90]="Z";CharacterCodes2[CharacterCodes2["asterisk"]=42]="asterisk";CharacterCodes2[CharacterCodes2["backslash"]=92]="backslash";CharacterCodes2[CharacterCodes2["closeBrace"]=125]="closeBrace";CharacterCodes2[CharacterCodes2["closeBracket"]=93]="closeBracket";CharacterCodes2[CharacterCodes2["colon"]=58]="colon";CharacterCodes2[CharacterCodes2["comma"]=44]="comma";CharacterCodes2[CharacterCodes2["dot"]=46]="dot";CharacterCodes2[CharacterCodes2["doubleQuote"]=34]="doubleQuote";CharacterCodes2[CharacterCodes2["minus"]=45]="minus";CharacterCodes2[CharacterCodes2["openBrace"]=123]="openBrace";CharacterCodes2[CharacterCodes2["openBracket"]=91]="openBracket";CharacterCodes2[CharacterCodes2["plus"]=43]="plus";CharacterCodes2[CharacterCodes2["slash"]=47]="slash";CharacterCodes2[CharacterCodes2["formFeed"]=12]="formFeed";CharacterCodes2[CharacterCodes2["tab"]=9]="tab"})(CharacterCodes||(CharacterCodes={}));init_esbuild_shims();var cachedSpaces=new Array(20).fill(0).map((_,index)=>{return" ".repeat(index)});var maxCachedValues=200;var cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r\n"+" ".repeat(index)})}," ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r\n"+" ".repeat(index)})}};var supportedEols=["\n","\r","\r\n"];function format(documentText,range,options){let initialIndentLevel;let formatText;let formatTextStart;let rangeStart;let rangeEnd;if(range){rangeStart=range.offset;rangeEnd=rangeStart+range.length;formatTextStart=rangeStart;while(formatTextStart>0&&!isEOL(documentText,formatTextStart-1)){formatTextStart--}let endOffset=rangeEnd;while(endOffset<documentText.length&&!isEOL(documentText,endOffset)){endOffset++}formatText=documentText.substring(formatTextStart,endOffset);initialIndentLevel=computeIndentLevel(formatText,options)}else{formatText=documentText;initialIndentLevel=0;formatTextStart=0;rangeStart=0;rangeEnd=documentText.length}const eol=getEOL(options,documentText);const eolFastPathSupported=supportedEols.includes(eol);let numberLineBreaks=0;let indentLevel=0;let indentValue;if(options.insertSpaces){indentValue=cachedSpaces[options.tabSize||4]??repeat(cachedSpaces[1],options.tabSize||4)}else{indentValue=" "}const indentType=indentValue===" "?" ":" ";let scanner=createScanner(formatText,false);let hasError=false;function newLinesAndIndent(){if(numberLineBreaks>1){return repeat(eol,numberLineBreaks)+repeat(indentValue,initialIndentLevel+indentLevel)}const amountOfSpaces=indentValue.length*(initialIndentLevel+indentLevel);if(!eolFastPathSupported||amountOfSpaces>cachedBreakLinesWithSpaces[indentType][eol].length){return eol+repeat(indentValue,initialIndentLevel+indentLevel)}if(amountOfSpaces<=0){return eol}return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]}__name(newLinesAndIndent,"newLinesAndIndent");function scanNext(){let token=scanner.scan();numberLineBreaks=0;while(token===15||token===14){if(token===14&&options.keepLines){numberLineBreaks+=1}else if(token===14){numberLineBreaks=1}token=scanner.scan()}hasError=token===16||scanner.getTokenError()!==0;return token}__name(scanNext,"scanNext");const editOperations=[];function addEdit(text,startOffset,endOffset){if(!hasError&&(!range||startOffset<rangeEnd&&endOffset>rangeStart)&&documentText.substring(startOffset,endOffset)!==text){editOperations.push({offset:startOffset,length:endOffset-startOffset,content:text})}}__name(addEdit,"addEdit");let firstToken=scanNext();if(options.keepLines&&numberLineBreaks>0){addEdit(repeat(eol,numberLineBreaks),0,0)}if(firstToken!==17){let firstTokenStart=scanner.getTokenOffset()+formatTextStart;let initialIndent=indentValue.length*initialIndentLevel<20&&options.insertSpaces?cachedSpaces[indentValue.length*initialIndentLevel]:repeat(indentValue,initialIndentLevel);addEdit(initialIndent,formatTextStart,firstTokenStart)}while(firstToken!==17){let firstTokenEnd=scanner.getTokenOffset()+scanner.getTokenLength()+formatTextStart;let secondToken=scanNext();let replaceContent="";let needsLineBreak=false;while(numberLineBreaks===0&&(secondToken===12||secondToken===13)){let commentTokenStart=scanner.getTokenOffset()+formatTextStart;addEdit(cachedSpaces[1],firstTokenEnd,commentTokenStart);firstTokenEnd=scanner.getTokenOffset()+scanner.getTokenLength()+formatTextStart;needsLineBreak=secondToken===12;replaceContent=needsLineBreak?newLinesAndIndent():"";secondToken=scanNext()}if(secondToken===2){if(firstToken!==1){indentLevel--};if(options.keepLines&&numberLineBreaks>0||!options.keepLines&&firstToken!==1){replaceContent=newLinesAndIndent()}else if(options.keepLines){replaceContent=cachedSpaces[1]}}else if(secondToken===4){if(firstToken!==3){indentLevel--};if(options.keepLines&&numberLineBreaks>0||!options.keepLines&&firstToken!==3){replaceContent=newLinesAndIndent()}else if(options.keepLines){replaceContent=cachedSpaces[1]}}else{switch(firstToken){case 3:case 1:indentLevel++;if(options.keepLines&&numberLineBreaks>0||!options.keepLines){replaceContent=newLinesAndIndent()}else{replaceContent=cachedSpaces[1]}break;case 5:if(options.keepLines&&numberLineBreaks>0||!options.keepLines){replaceContent=newLinesAndIndent()}else{replaceContent=cachedSpaces[1]}break;case 12:replaceContent=newLinesAndIndent();break;case 13:if(numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(!needsLineBreak){replaceContent=cachedSpaces[1]}break;case 6:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(!needsLineBreak){replaceContent=cachedSpaces[1]}break;case 10:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(secondToken===6&&!needsLineBreak){replaceContent=""}break;case 7:case 8:case 9:case 11:case 2:case 4:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else{if((secondToken===12||secondToken===13)&&!needsLineBreak){replaceContent=cachedSpaces[1]}else if(secondToken!==5&&secondToken!==17){hasError=true}}break;case 16:hasError=true;break}if(numberLineBreaks>0&&(secondToken===12||secondToken===13)){replaceContent=newLinesAndIndent()}}if(secondToken===17){if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else{replaceContent=options.insertFinalNewline?eol:""}}const secondTokenStart=scanner.getTokenOffset()+formatTextStart;addEdit(replaceContent,firstTokenEnd,secondTokenStart);firstToken=secondToken}return editOperations}__name(format,"format");function repeat(s,count){let result="";for(let i=0;i<count;i++){result+=s}return result}__name(repeat,"repeat");function computeIndentLevel(content,options){let i=0;let nChars=0;const tabSize=options.tabSize||4;while(i<content.length){let ch=content.charAt(i);if(ch===cachedSpaces[1]){nChars++}else if(ch===" "){nChars+=tabSize}else{break}i++}return Math.floor(nChars/tabSize)}__name(computeIndentLevel,"computeIndentLevel");function getEOL(options,text){for(let i=0;i<text.length;i++){const ch=text.charAt(i);if(ch==="\r"){if(i+1<text.length&&text.charAt(i+1)==="\n"){return"\r\n"}return"\r"}else if(ch==="\n"){return"\n"}}return options&&options.eol||"\n"}__name(getEOL,"getEOL");function isEOL(text,offset){return"\r\n".indexOf(text.charAt(offset))!==-1}__name(isEOL,"isEOL");init_esbuild_shims();init_esbuild_shims();var ParseOptions;(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}));function parseTree(text,errors=[],options=ParseOptions.DEFAULT){let currentParent={type:"array",offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(endOffset){if(currentParent.type==="property"){currentParent.length=endOffset-currentParent.offset;currentParent=currentParent.parent}}__name(ensurePropertyComplete,"ensurePropertyComplete");function onValue(valueNode){currentParent.children.push(valueNode);return valueNode}__name(onValue,"onValue");const visitor={onObjectBegin:__name(offset=>{currentParent=onValue({type:"object",offset,length:-1,parent:currentParent,children:[]})},"onObjectBegin"),onObjectProperty:__name((name,offset,length)=>{currentParent=onValue({type:"property",offset,length:-1,parent:currentParent,children:[]});currentParent.children.push({type:"string",value:name,offset,length,parent:currentParent})},"onObjectProperty"),onObjectEnd:__name((offset,length)=>{ensurePropertyComplete(offset+length);currentParent.length=offset+length-currentParent.offset;currentParent=currentParent.parent;ensurePropertyComplete(offset+length)},"onObjectEnd"),onArrayBegin:__name((offset,length)=>{currentParent=onValue({type:"array",offset,length:-1,parent:currentParent,children:[]})},"onArrayBegin"),onArrayEnd:__name((offset,length)=>{currentParent.length=offset+length-currentParent.offset;currentParent=currentParent.parent;ensurePropertyComplete(offset+length)},"onArrayEnd"),onLiteralValue:__name((value,offset,length)=>{onValue({type:getNodeType(value),offset,length,parent:currentParent,value});ensurePropertyComplete(offset+length)},"onLiteralValue"),onSeparator:__name((sep,offset,length)=>{if(currentParent.type==="property"){if(sep===":"){currentParent.colonOffset=offset}else if(sep===","){ensurePropertyComplete(offset)}}},"onSeparator"),onError:__name((error,offset,length)=>{errors.push({error,offset,length})},"onError")};visit(text,visitor,options);const result=currentParent.children[0];if(result){delete result.parent}return result}__name(parseTree,"parseTree");function findNodeAtLocation(root,path4){if(!root){return void 0}let node=root;for(let segment of path4){if(typeof segment==="string"){if(node.type!=="object"||!Array.isArray(node.children)){return void 0}let found=false;for(const propertyNode of node.children){if(Array.isArray(propertyNode.children)&&propertyNode.children[0].value===segment&&propertyNode.children.length===2){node=propertyNode.children[1];found=true;break}}if(!found){return void 0}}else{const index=segment;if(node.type!=="array"||index<0||!Array.isArray(node.children)||index>=node.children.length){return void 0}node=node.children[index]}}return node}__name(findNodeAtLocation,"findNodeAtLocation");function getNodeValue(node){switch(node.type){case"array":return node.children.map(getNodeValue);case"object":const obj=Object.create(null);for(let prop of node.children){const valueNode=prop.children[1];if(valueNode){obj[prop.children[0].value]=getNodeValue(valueNode)}}return obj;case"null":case"string":case"number":case"boolean":return node.value;default:return void 0}}__name(getNodeValue,"getNodeValue");function visit(text,visitor,options=ParseOptions.DEFAULT){const _scanner=createScanner(text,false);const _jsonPath=[];let suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}__name(toNoArgVisit,"toNoArgVisit");function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}__name(toOneArgVisit,"toOneArgVisit");function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>true}__name(toOneArgVisitWithPath,"toOneArgVisitWithPath");function toBeginVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks++}else{let cbReturn=visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice());if(cbReturn===false){suppressedCallbacks=1}}}:()=>true}__name(toBeginVisit,"toBeginVisit");function toEndVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks--}if(suppressedCallbacks===0){visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}}:()=>true}__name(toEndVisit,"toEndVisit");const onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError);const disallowComments=options&&options.disallowComments;const allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){while(true){const token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!disallowComments){handleError(11)}break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:if(disallowComments){handleError(10)}else{onComment()}break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}__name(scanNext,"scanNext");function handleError(error,skipUntilAfter=[],skipUntil=[]){onError(error);if(skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();while(token!==17){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1){break}token=scanNext()}}}__name(handleError,"handleError");function parseString(isValue){const value=_scanner.getTokenValue();if(isValue){onLiteralValue(value)}else{onObjectProperty(value);_jsonPath.push(value)}scanNext();return true}__name(parseString,"parseString");function parseLiteral(){switch(_scanner.getToken()){case 11:const tokenValue=_scanner.getTokenValue();let value=Number(tokenValue);if(isNaN(value)){handleError(2);value=0}onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(true);break;case 9:onLiteralValue(false);break;default:return false}scanNext();return true}__name(parseLiteral,"parseLiteral");function parseProperty(){if(_scanner.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(_scanner.getToken()===6){onSeparator(":");scanNext();if(!parseValue()){handleError(4,[],[2,5])}}else{handleError(5,[],[2,5])}_jsonPath.pop();return true}__name(parseProperty,"parseProperty");function parseObject(){onObjectBegin();scanNext();let needsComma=false;while(_scanner.getToken()!==2&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===2&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(!parseProperty()){handleError(4,[],[2,5])}needsComma=true}onObjectEnd();if(_scanner.getToken()!==2){handleError(7,[2],[])}else{scanNext()}return true}__name(parseObject,"parseObject");function parseArray(){onArrayBegin();scanNext();let isFirstElement=true;let needsComma=false;while(_scanner.getToken()!==4&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===4&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(isFirstElement){_jsonPath.push(0);isFirstElement=false}else{_jsonPath[_jsonPath.length-1]++}if(!parseValue()){handleError(4,[],[4,5])}needsComma=true}onArrayEnd();if(!isFirstElement){_jsonPath.pop()}if(_scanner.getToken()!==4){handleError(8,[4],[])}else{scanNext()}return true}__name(parseArray,"parseArray");function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}__name(parseValue,"parseValue");scanNext();if(_scanner.getToken()===17){if(options.allowEmptyContent){return true}handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(_scanner.getToken()!==17){handleError(9,[],[])}return true}__name(visit,"visit");function getNodeType(value){switch(typeof value){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(!value){return"null"}else if(Array.isArray(value)){return"array"}return"object"}default:return"null"}}__name(getNodeType,"getNodeType");function setProperty(text,originalPath,value,options){const path4=originalPath.slice();const errors=[];const root=parseTree(text,errors);let parent=void 0;let lastSegment=void 0;while(path4.length>0){lastSegment=path4.pop();parent=findNodeAtLocation(root,path4);if(parent===void 0&&value!==void 0){if(typeof lastSegment==="string"){value={[lastSegment]:value}}else{value=[value]}}else{break}}if(!parent){if(value===void 0){throw new Error("Can not delete in empty document")}return withFormatting(text,{offset:root?root.offset:0,length:root?root.length:0,content:JSON.stringify(value)},options)}else if(parent.type==="object"&&typeof lastSegment==="string"&&Array.isArray(parent.children)){const existing=findNodeAtLocation(parent,[lastSegment]);if(existing!==void 0){if(value===void 0){if(!existing.parent){throw new Error("Malformed AST")}const propertyIndex=parent.children.indexOf(existing.parent);let removeBegin;let removeEnd=existing.parent.offset+existing.parent.length;if(propertyIndex>0){let previous=parent.children[propertyIndex-1];removeBegin=previous.offset+previous.length}else{removeBegin=parent.offset+1;if(parent.children.length>1){let next=parent.children[1];removeEnd=next.offset}}return withFormatting(text,{offset:removeBegin,length:removeEnd-removeBegin,content:""},options)}else{return withFormatting(text,{offset:existing.offset,length:existing.length,content:JSON.stringify(value)},options)}}else{if(value===void 0){return[]}const newProperty=`${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;const index=options.getInsertionIndex?options.getInsertionIndex(parent.children.map(p=>p.children[0].value)):parent.children.length;let edit;if(index>0){let previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}else if(parent.children.length===0){edit={offset:parent.offset+1,length:0,content:newProperty}}else{edit={offset:parent.offset+1,length:0,content:newProperty+","}}return withFormatting(text,edit,options)}}else if(parent.type==="array"&&typeof lastSegment==="number"&&Array.isArray(parent.children)){const insertIndex=lastSegment;if(insertIndex===-1){const newProperty=`${JSON.stringify(value)}`;let edit;if(parent.children.length===0){edit={offset:parent.offset+1,length:0,content:newProperty}}else{const previous=parent.children[parent.children.length-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else if(value===void 0&&parent.children.length>=0){const removalIndex=lastSegment;const toRemove=parent.children[removalIndex];let edit;if(parent.children.length===1){edit={offset:parent.offset+1,length:parent.length-2,content:""}}else if(parent.children.length-1===removalIndex){let previous=parent.children[removalIndex-1];let offset=previous.offset+previous.length;let parentEndOffset=parent.offset+parent.length;edit={offset,length:parentEndOffset-2-offset,content:""}}else{edit={offset:toRemove.offset,length:parent.children[removalIndex+1].offset-toRemove.offset,content:""}}return withFormatting(text,edit,options)}else if(value!==void 0){let edit;const newProperty=`${JSON.stringify(value)}`;if(!options.isArrayInsertion&&parent.children.length>lastSegment){const toModify=parent.children[lastSegment];edit={offset:toModify.offset,length:toModify.length,content:newProperty}}else if(parent.children.length===0||lastSegment===0){edit={offset:parent.offset+1,length:0,content:parent.children.length===0?newProperty:newProperty+","}}else{const index=lastSegment>parent.children.length?parent.children.length:lastSegment;const previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else{throw new Error(`Can not ${value===void 0?"remove":options.isArrayInsertion?"insert":"modify"} Array index ${insertIndex} as length is not sufficient`)}}else{throw new Error(`Can not add ${typeof lastSegment!=="number"?"index":"property"} to parent of type ${parent.type}`)}}__name(setProperty,"setProperty");function withFormatting(text,edit,options){if(!options.formattingOptions){return[edit]}let newText=applyEdit(text,edit);let begin=edit.offset;let end=edit.offset+edit.content.length;if(edit.length===0||edit.content.length===0){while(begin>0&&!isEOL(newText,begin-1)){begin--}while(end<newText.length&&!isEOL(newText,end)){end++}}const edits=format(newText,{offset:begin,length:end-begin},{...options.formattingOptions,keepLines:false});for(let i=edits.length-1;i>=0;i--){const edit2=edits[i];newText=applyEdit(newText,edit2);begin=Math.min(begin,edit2.offset);end=Math.max(end,edit2.offset+edit2.length);end+=edit2.content.length-edit2.length}const editLength=text.length-(newText.length-end)-begin;return[{offset:begin,length:editLength,content:newText.substring(begin,end)}]}__name(withFormatting,"withFormatting");function applyEdit(text,edit){return text.substring(0,edit.offset)+edit.content+text.substring(edit.offset+edit.length)}__name(applyEdit,"applyEdit");var ScanError;(function(ScanError2){ScanError2[ScanError2["None"]=0]="None";ScanError2[ScanError2["UnexpectedEndOfComment"]=1]="UnexpectedEndOfComment";ScanError2[ScanError2["UnexpectedEndOfString"]=2]="UnexpectedEndOfString";ScanError2[ScanError2["UnexpectedEndOfNumber"]=3]="UnexpectedEndOfNumber";ScanError2[ScanError2["InvalidUnicode"]=4]="InvalidUnicode";ScanError2[ScanError2["InvalidEscapeCharacter"]=5]="InvalidEscapeCharacter";ScanError2[ScanError2["InvalidCharacter"]=6]="InvalidCharacter"})(ScanError||(ScanError={}));var SyntaxKind;(function(SyntaxKind2){SyntaxKind2[SyntaxKind2["OpenBraceToken"]=1]="OpenBraceToken";SyntaxKind2[SyntaxKind2["CloseBraceToken"]=2]="CloseBraceToken";SyntaxKind2[SyntaxKind2["OpenBracketToken"]=3]="OpenBracketToken";SyntaxKind2[SyntaxKind2["CloseBracketToken"]=4]="CloseBracketToken";SyntaxKind2[SyntaxKind2["CommaToken"]=5]="CommaToken";SyntaxKind2[SyntaxKind2["ColonToken"]=6]="ColonToken";SyntaxKind2[SyntaxKind2["NullKeyword"]=7]="NullKeyword";SyntaxKind2[SyntaxKind2["TrueKeyword"]=8]="TrueKeyword";SyntaxKind2[SyntaxKind2["FalseKeyword"]=9]="FalseKeyword";SyntaxKind2[SyntaxKind2["StringLiteral"]=10]="StringLiteral";SyntaxKind2[SyntaxKind2["NumericLiteral"]=11]="NumericLiteral";SyntaxKind2[SyntaxKind2["LineCommentTrivia"]=12]="LineCommentTrivia";SyntaxKind2[SyntaxKind2["BlockCommentTrivia"]=13]="BlockCommentTrivia";SyntaxKind2[SyntaxKind2["LineBreakTrivia"]=14]="LineBreakTrivia";SyntaxKind2[SyntaxKind2["Trivia"]=15]="Trivia";SyntaxKind2[SyntaxKind2["Unknown"]=16]="Unknown";SyntaxKind2[SyntaxKind2["EOF"]=17]="EOF"})(SyntaxKind||(SyntaxKind={}));var parseTree2=parseTree;var findNodeAtLocation2=findNodeAtLocation;var getNodeValue2=getNodeValue;var ParseErrorCode;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2["InvalidSymbol"]=1]="InvalidSymbol";ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"]=2]="InvalidNumberFormat";ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"]=3]="PropertyNameExpected";ParseErrorCode2[ParseErrorCode2["ValueExpected"]=4]="ValueExpected";ParseErrorCode2[ParseErrorCode2["ColonExpected"]=5]="ColonExpected";ParseErrorCode2[ParseErrorCode2["CommaExpected"]=6]="CommaExpected";ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"]=7]="CloseBraceExpected";ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"]=8]="CloseBracketExpected";ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"]=9]="EndOfFileExpected";ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"]=10]="InvalidCommentToken";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"]=11]="UnexpectedEndOfComment";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"]=12]="UnexpectedEndOfString";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"]=13]="UnexpectedEndOfNumber";ParseErrorCode2[ParseErrorCode2["InvalidUnicode"]=14]="InvalidUnicode";ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"]=15]="InvalidEscapeCharacter";ParseErrorCode2[ParseErrorCode2["InvalidCharacter"]=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}));function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}__name(printParseErrorCode,"printParseErrorCode");function modify(text,path4,value,options){return setProperty(text,path4,value,options)}__name(modify,"modify");function applyEdits(text,edits){let sortedEdits=edits.slice(0).sort((a,b)=>{const diff=a.offset-b.offset;if(diff===0){return a.length-b.length}return diff});let lastModifiedOffset=text.length;for(let i=sortedEdits.length-1;i>=0;i--){let e=sortedEdits[i];if(e.offset+e.length<=lastModifiedOffset){text=applyEdit(text,e)}else{throw new Error("Overlapping edit")}lastModifiedOffset=e.offset}return text}__name(applyEdits,"applyEdits");init_esbuild_shims();import*as fs from"node:fs";import path from"node:path";function writeWithBackupSync(targetPath,content,options={}){const{backupSuffix=".orig",encoding="utf-8"}=options;const existing=fs.existsSync(targetPath)?fs.statSync(targetPath):void 0;if(existing?.isDirectory()){throw new Error(`Cannot write to '${targetPath}' because it is a directory`)}const workingDirectory=fs.mkdtempSync(`${targetPath}.write-`);const basename=path.basename(targetPath);const tempPath=path.join(workingDirectory,`${basename}.tmp`);const backupPath=path.join(workingDirectory,`${basename}${backupSuffix}`);let backupCreated=false;try{const mode=existing&&fs.lstatSync(targetPath,{throwIfNoEntry:false})?.isFile()?existing.mode&511:void 0;fs.writeFileSync(tempPath,content,{encoding,flag:"wx",flush:true,mode});if(mode!==void 0){try{fs.chmodSync(tempPath,mode)}catch(error){const code=error instanceof Error&&"code"in error?error.code:void 0;if(code!=="ENOSYS"&&code!=="ENOTSUP"&&code!=="EPERM"||(fs.statSync(tempPath).mode&511&~mode)!==0){throw error}}}if(fs.existsSync(targetPath)){try{fs.copyFileSync(targetPath,backupPath,fs.constants.COPYFILE_EXCL);backupCreated=true}catch(backupError){throw new Error(`Failed to backup existing file: ${backupError instanceof Error?backupError.message:String(backupError)}`)}}fs.renameSync(tempPath,targetPath)}catch(error){const recoveryRetained=backupCreated&&!sameContents(backupPath,targetPath);try{if(recoveryRetained){fs.unlinkSync(tempPath)}else{fs.rmSync(workingDirectory,{recursive:true,force:true})}}catch{}if(recoveryRetained){throw new Error(`Failed to write file: ${error instanceof Error?error.message:String(error)}. Recovery copy retained at '${backupPath}'; inspect the current target before restoring it.`)}throw error}try{fs.rmSync(workingDirectory,{recursive:true,force:true})}catch{}}__name(writeWithBackupSync,"writeWithBackupSync");function sameContents(first,second){try{return fs.readFileSync(first).equals(fs.readFileSync(second))}catch{return false}}__name(sameContents,"sameContents");var PARSE_OPTIONS={allowTrailingComma:true};function updateSettingsFilePreservingFormat(filePath,updates,sync=false,replacePath=[]){if(!fs2.existsSync(filePath)){const content=JSON.stringify(updates,null,2);writeWithBackupSync(filePath,content);return true}const originalContent=fs2.readFileSync(filePath,"utf-8");try{parseJsoncObject(originalContent)}catch(_error){writeStderrLine("Error parsing settings file.");writeStderrLine(`Settings file may be corrupted: ${_error instanceof Error?_error.message:String(_error)}`);return false}let updatedContent;try{updatedContent=updateJsoncContent(originalContent,updates,sync,replacePath)}catch(validationError){writeStderrLine("Error: Refusing to write settings file \u2014 the result would not be valid JSON.");writeStderrLine(validationError instanceof Error?validationError.message:String(validationError));return false}writeWithBackupSync(filePath,updatedContent);return true}__name(updateSettingsFilePreservingFormat,"updateSettingsFilePreservingFormat");function parseJsoncObject(content){const errors=[];const root=parseTree2(stripBom(content),errors,PARSE_OPTIONS);if(errors.length>0){const error=errors[0];throw new Error(`${printParseErrorCode(error.error)} at offset ${error.offset}`)}if(root?.type!=="object"){throw new Error("JSONC document root is not a JSON object.")}return JSON.parse(JSON.stringify(getNodeValue2(root)))}__name(parseJsoncObject,"parseJsoncObject");function updateJsoncContent(content,updates,sync=false,replacePath=[]){const bom=content.startsWith("\uFEFF")?"\uFEFF":"";const editableContent=stripBom(content);const parsed=parseJsoncObject(editableContent);const targetWithUndefined=applyUpdates(structuredClone(parsed),updates,sync,replacePath);const target=JSON.parse(JSON.stringify(targetWithUndefined));const options={formattingOptions:detectFormattingOptions(editableContent)};let updated=normalizeDuplicateProperties(editableContent,options);const current=parseJsoncObject(updated);for(const operation of collectOperations(current,target)){if(operation.value===void 0){updated=removeTrailingInlineComment(updated,operation.path)}updated=applyEdits(updated,modify(updated,operation.path,operation.value,options))}const reparsed=parseJsoncObject(updated);if(!isDeepStrictEqual(reparsed,target)){throw new Error("Edited JSONC does not match the intended settings.")}return bom+updated}__name(updateJsoncContent,"updateJsoncContent");function applyUpdates(current,updates,sync=false,replacePath=[],currentPath=[]){const result=current;if(sync){const keysToRemove=Object.keys(result).filter(key=>!Object.hasOwn(updates,key));for(const key of keysToRemove){delete result[key]}}for(const key of Object.getOwnPropertyNames(updates)){if(key==="__proto__"||key==="constructor"||key==="prototype"){continue}const value=updates[key];const nextPath=[...currentPath,key];const valueIsObject=typeof value==="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length>0;if(pathsEqual(nextPath,replacePath)){result[key]=valueIsObject?applyUpdates({},value):value;continue}if(valueIsObject&&(typeof result[key]!=="object"||result[key]===null||Array.isArray(result[key]))){result[key]=applyUpdates({},value,sync,replacePath,nextPath)}else if(valueIsObject&&typeof result[key]==="object"&&result[key]!==null&&!Array.isArray(result[key])){result[key]=applyUpdates(result[key],value,sync,replacePath,nextPath)}else{result[key]=value}}return result}__name(applyUpdates,"applyUpdates");function stripBom(content){return content.startsWith("\uFEFF")?content.slice(1):content}__name(stripBom,"stripBom");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function detectFormattingOptions(content){const root=parseTree2(content,[],PARSE_OPTIONS);const firstKey=root?.children?.[0]?.children?.[0];const lineStart=firstKey===void 0?-1:content.lastIndexOf("\n",firstKey.offset-1);const candidate=firstKey===void 0?void 0:content.slice(lineStart+1,firstKey.offset);const indentation=candidate!==void 0&&/^[ \t]*$/.test(candidate)?candidate:" ";return{eol:content.includes("\r\n")?"\r\n":"\n",insertSpaces:!indentation.startsWith(" "),tabSize:indentation.startsWith(" ")?1:indentation.length,insertFinalNewline:content.endsWith("\n")}}__name(detectFormattingOptions,"detectFormattingOptions");function collectOperations(current,target,path4=[],operations=[]){for(const key of Object.keys(current)){if(!Object.hasOwn(target,key)){operations.push({path:[...path4,key],value:void 0})}}for(const key of Object.keys(target)){const nextPath=[...path4,key];if(!Object.hasOwn(current,key)){operations.push({path:nextPath,value:target[key]})}else if(isRecord(current[key])&&isRecord(target[key])){collectOperations(current[key],target[key],nextPath,operations)}else if(!isDeepStrictEqual(current[key],target[key])){operations.push({path:nextPath,value:target[key]})}}return operations}__name(collectOperations,"collectOperations");function findDuplicateProperty(node,path4=[]){if(node.type!=="object"||node.children===void 0){return void 0}const properties=new Map;for(const property of node.children){const keyNode=property.children?.[0];const key=keyNode?.value;if(typeof key!=="string"||keyNode===void 0){continue}const previous=properties.get(key);if(previous!==void 0){return{objectPath:[...path4],keyNode:previous,propertyNames:new Set(properties.keys())}}properties.set(key,keyNode)}for(const property of node.children){const key=property.children?.[0]?.value;const valueNode=property.children?.[1];if(typeof key!=="string"||valueNode===void 0){continue}const duplicate=findDuplicateProperty(valueNode,[...path4,key]);if(duplicate!==void 0){return duplicate}}return void 0}__name(findDuplicateProperty,"findDuplicateProperty");function normalizeDuplicateProperties(content,options){let normalized=content;let duplicateIndex=0;while(true){const root=parseTree2(normalized,[],PARSE_OPTIONS);if(root===void 0){return normalized}const duplicate=findDuplicateProperty(root);if(duplicate===void 0){return normalized}let temporaryKey;do{temporaryKey=`__qwen_duplicate_${duplicateIndex}`;duplicateIndex+=1}while(duplicate.propertyNames.has(temporaryKey));let renamed=normalized.slice(0,duplicate.keyNode.offset)+JSON.stringify(temporaryKey)+normalized.slice(duplicate.keyNode.offset+duplicate.keyNode.length);renamed=removeTrailingInlineComment(renamed,[...duplicate.objectPath,temporaryKey]);normalized=applyEdits(renamed,modify(renamed,[...duplicate.objectPath,temporaryKey],void 0,options))}}__name(normalizeDuplicateProperties,"normalizeDuplicateProperties");function removeTrailingInlineComment(content,path4){const root=parseTree2(content,[],PARSE_OPTIONS);if(root===void 0){return content}const node=findNodeAtLocation2(root,[...path4]);if(node===void 0){return content}const tail=content.slice(node.offset+node.length);const match=tail.match(/^[ \t]*(?:,[ \t]*)?(\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)/);const comment=match?.[1];if(comment===void 0||match===null){return content}const commentOffset=node.offset+node.length+match[0].indexOf(comment);return content.slice(0,commentOffset)+content.slice(commentOffset+comment.length)}__name(removeTrailingInlineComment,"removeTrailingInlineComment");function pathsEqual(left,right){return left.length===right.length&&left.every((segment,index)=>segment===right[index])}__name(pathsEqual,"pathsEqual");init_esbuild_shims();import*as fs3 from"node:fs";import*as path2 from"node:path";function isWorkflowAncestorDirectorySafe(directory){if(process.platform==="win32")return true;for(const location of[directory,path2.join(directory,".qwen"),path2.join(directory,".qwen","workflows")]){try{if((fs3.statSync(location).mode&2)!==0)return false}catch(error){const code=error.code;if(location===directory)return false;if(code==="ENOENT"||code==="ENOTDIR")break;return false}}return true}__name(isWorkflowAncestorDirectorySafe,"isWorkflowAncestorDirectorySafe");var debugLogger=createDebugLogger("TRUSTED_FOLDERS");var TRUSTED_FOLDERS_FILENAME="trustedFolders.json";function getTrustedFoldersPath(){if(process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]){return process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]}return path3.join(Storage.getGlobalQwenDir(),TRUSTED_FOLDERS_FILENAME)}__name(getTrustedFoldersPath,"getTrustedFoldersPath");var TrustLevel=(TrustLevel2=>{TrustLevel2["TRUST_FOLDER"]="TRUST_FOLDER";TrustLevel2["TRUST_PARENT"]="TRUST_PARENT";TrustLevel2["DO_NOT_TRUST"]="DO_NOT_TRUST";return TrustLevel2})(TrustLevel||{});var trustedFoldersChangeListeners=new Set;function onTrustedFoldersChanged(listener){trustedFoldersChangeListeners.add(listener);return()=>trustedFoldersChangeListeners.delete(listener)}__name(onTrustedFoldersChanged,"onTrustedFoldersChanged");function notifyTrustedFoldersChanged(){for(const listener of trustedFoldersChangeListeners)listener()}__name(notifyTrustedFoldersChanged,"notifyTrustedFoldersChanged");var LoadedTrustedFolders=class{constructor(user,errors){this.user=user;this.errors=errors}static{__name(this,"LoadedTrustedFolders")}get rules(){return Object.entries(this.user.config).map(([path4,trustLevel])=>({path:path4,trustLevel}))}isPathTrusted(location){return resolveTrustDecision(buildTrustPrecedenceRules(this.rules),getPathComparisonVariants(location))}setValue(path4,trustLevel,preserveExistingTrust=false){const committedConfig=writeTrustedFolders(this.user.path,diskConfig=>{const existing=diskConfig[path4];if(preserveExistingTrust&&(existing==="TRUST_FOLDER"||existing==="TRUST_PARENT")){return diskConfig}return{...diskConfig,[path4]:trustLevel}});this.user.config=committedConfig;notifyTrustedFoldersChanged()}};var loadedTrustedFolders;function resetTrustedFoldersForTesting(){loadedTrustedFolders=void 0}__name(resetTrustedFoldersForTesting,"resetTrustedFoldersForTesting");function loadTrustedFolders(){loadedTrustedFolders??=readTrustedFoldersFile(false);return loadedTrustedFolders}__name(loadTrustedFolders,"loadTrustedFolders");function loadTrustedFoldersFresh(){return readTrustedFoldersFile(true)}__name(loadTrustedFoldersFresh,"loadTrustedFoldersFresh");function readTrustedFoldersFile(validateRules){const errors=[];let userConfig={};const userPath=getTrustedFoldersPath();try{if(fs4.existsSync(userPath)){const content=fs4.readFileSync(userPath,"utf-8");const parsed=parseJsoncObject(content);if(validateRules)assertTrustedFoldersConfig(parsed);userConfig=parsed}}catch(error){errors.push({message:error instanceof Error&&error.message==="JSONC document root is not a JSON object."?"Trusted folders file is not a valid JSON object.":getErrorMessage(error),path:userPath})}return new LoadedTrustedFolders({path:userPath,config:userConfig},errors)}__name(readTrustedFoldersFile,"readTrustedFoldersFile");function createLocalWorkflowAncestorTrustProvider(settings){return async(ancestorDirs,canonicalTargetDir)=>{if(!isFolderTrustEnabled(settings)){return ancestorDirs.map(isWorkflowAncestorDirectorySafe)}if(ideContextStore.get()?.workspaceState?.isTrusted===false){return ancestorDirs.map(()=>false)}const folders=loadTrustedFoldersFresh();if(folders.errors.length>0){debugLogger.warn("Workflow ancestor trust denied: invalid trusted folders snapshot:",folders.errors.map(error=>`${error.path}: ${error.message}`).join("; "));return ancestorDirs.map(()=>false)}if(folders.isPathTrusted(canonicalTargetDir)!==true){return ancestorDirs.map(()=>false)}return ancestorDirs.map(directory=>folders.isPathTrusted(directory)===true)}}__name(createLocalWorkflowAncestorTrustProvider,"createLocalWorkflowAncestorTrustProvider");function saveTrustedFolders(trustedFoldersFile){writeTrustedFolders(trustedFoldersFile.path,()=>({...trustedFoldersFile.config}))}__name(saveTrustedFolders,"saveTrustedFolders");function assertTrustedFoldersConfig(config){for(const[rulePath,trustLevel]of Object.entries(config)){if(!Object.values(TrustLevel).includes(trustLevel)){throw new FatalConfigError(`Invalid trusted folder rule for ${JSON.stringify(rulePath)}.`)}}}__name(assertTrustedFoldersConfig,"assertTrustedFoldersConfig");function writeTrustedFolders(filePath,update){const dirPath=path3.dirname(filePath);if(!fs4.existsSync(dirPath)){fs4.mkdirSync(dirPath,{recursive:true})}const release=import_proper_lockfile.default.lockSync(filePath,{realpath:false,stale:1e4,onCompromised:__name(err=>{debugLogger.warn("trusted folders lock compromised:",err)},"onCompromised")});try{let originalContent="{}";if(fs4.existsSync(filePath)){const stat=fs4.lstatSync(filePath);if(stat.isSymbolicLink()||!stat.isFile()){throw new FatalConfigError("Trusted folders path must be a regular file.")}originalContent=fs4.readFileSync(filePath,"utf-8")}let parsed;try{parsed=parseJsoncObject(originalContent)}catch(error){if(error instanceof Error&&error.message==="JSONC document root is not a JSON object."){throw new FatalConfigError("Trusted folders file is not a valid JSON object.")}throw error}const diskConfig=Object.fromEntries(Object.entries(parsed));assertTrustedFoldersConfig(diskConfig);const nextConfig=update({...diskConfig});assertTrustedFoldersConfig(nextConfig);const content=updateJsoncContent(originalContent,nextConfig,true);atomicWriteFileSync(filePath,content,{encoding:"utf-8",mode:384,forceMode:true,noFollow:true});return nextConfig}finally{try{release()}catch{}}}__name(writeTrustedFolders,"writeTrustedFolders");function isFolderTrustEnabled(settings){const folderTrustSetting=settings.security?.folderTrust?.enabled??false;return folderTrustSetting}__name(isFolderTrustEnabled,"isFolderTrustEnabled");function getExplicitTrustLevel(trustConfig,workspaceCwd){const winner=resolveTrustRule(buildTrustPrecedenceRules(Object.entries(trustConfig).map(([rulePath,trustLevel])=>({path:rulePath,trustLevel}))),getPathComparisonVariants(workspaceCwd));return winner?.payload??null}__name(getExplicitTrustLevel,"getExplicitTrustLevel");function loadTrustedFoldersWithOverrides(trustConfig){const folders=loadTrustedFolders();if(folders.errors.length>0){const errorMessages=folders.errors.map(error=>`Error in ${error.path}: ${error.message}`);throw new FatalConfigError(`${errorMessages.join("\n")}
|
|
3
|
+
import{buildTrustPrecedenceRules,resolveTrustDecision,resolveTrustRule}from"./chunk-EIPLDYEY.js";import{arePathsEquivalent,getPathComparisonVariants}from"./chunk-IDXJIDME.js";import{ideContextStore}from"./chunk-T3CQ72HC.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{atomicWriteFileSync}from"./chunk-BMHYEQTI.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{Storage}from"./chunk-EPODBRBP.js";import{FatalConfigError,getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs4 from"node:fs";import*as path3 from"node:path";init_esbuild_shims();import*as fs2 from"node:fs";import{isDeepStrictEqual}from"node:util";init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();function createScanner(text,ignoreTrivia=false){const len=text.length;let pos=0,value="",tokenOffset=0,token=16,lineNumber=0,lineStartOffset=0,tokenLineStartOffset=0,prevTokenLineStartOffset=0,scanError=0;function scanHexDigits(count,exact){let digits=0;let value2=0;while(digits<count||!exact){let ch=text.charCodeAt(pos);if(ch>=48&&ch<=57){value2=value2*16+ch-48}else if(ch>=65&&ch<=70){value2=value2*16+ch-65+10}else if(ch>=97&&ch<=102){value2=value2*16+ch-97+10}else{break}pos++;digits++}if(digits<count){value2=-1}return value2}__name(scanHexDigits,"scanHexDigits");function setPosition(newPosition){pos=newPosition;value="";tokenOffset=0;token=16;scanError=0}__name(setPosition,"setPosition");function scanNumber(){let start=pos;if(text.charCodeAt(pos)===48){pos++}else{pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}if(pos<text.length&&text.charCodeAt(pos)===46){pos++;if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}}else{scanError=3;return text.substring(start,pos)}}let end=pos;if(pos<text.length&&(text.charCodeAt(pos)===69||text.charCodeAt(pos)===101)){pos++;if(pos<text.length&&text.charCodeAt(pos)===43||text.charCodeAt(pos)===45){pos++}if(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++;while(pos<text.length&&isDigit(text.charCodeAt(pos))){pos++}end=pos}else{scanError=3}}return text.substring(start,end)}__name(scanNumber,"scanNumber");function scanString(){let result="",start=pos;while(true){if(pos>=len){result+=text.substring(start,pos);scanError=2;break}const ch=text.charCodeAt(pos);if(ch===34){result+=text.substring(start,pos);pos++;break}if(ch===92){result+=text.substring(start,pos);pos++;if(pos>=len){scanError=2;break}const ch2=text.charCodeAt(pos++);switch(ch2){case 34:result+='"';break;case 92:result+="\\";break;case 47:result+="/";break;case 98:result+="\b";break;case 102:result+="\f";break;case 110:result+="\n";break;case 114:result+="\r";break;case 116:result+=" ";break;case 117:const ch3=scanHexDigits(4,true);if(ch3>=0){result+=String.fromCharCode(ch3)}else{scanError=4}break;default:scanError=5}start=pos;continue}if(ch>=0&&ch<=31){if(isLineBreak(ch)){result+=text.substring(start,pos);scanError=2;break}else{scanError=6}}pos++}return result}__name(scanString,"scanString");function scanNext(){value="";scanError=0;tokenOffset=pos;lineStartOffset=lineNumber;prevTokenLineStartOffset=tokenLineStartOffset;if(pos>=len){tokenOffset=len;return token=17}let code=text.charCodeAt(pos);if(isWhiteSpace(code)){do{pos++;value+=String.fromCharCode(code);code=text.charCodeAt(pos)}while(isWhiteSpace(code));return token=15}if(isLineBreak(code)){pos++;value+=String.fromCharCode(code);if(code===13&&text.charCodeAt(pos)===10){pos++;value+="\n"}lineNumber++;tokenLineStartOffset=pos;return token=14}switch(code){case 123:pos++;return token=1;case 125:pos++;return token=2;case 91:pos++;return token=3;case 93:pos++;return token=4;case 58:pos++;return token=6;case 44:pos++;return token=5;case 34:pos++;value=scanString();return token=10;case 47:const start=pos-1;if(text.charCodeAt(pos+1)===47){pos+=2;while(pos<len){if(isLineBreak(text.charCodeAt(pos))){break}pos++}value=text.substring(start,pos);return token=12}if(text.charCodeAt(pos+1)===42){pos+=2;const safeLength=len-1;let commentClosed=false;while(pos<safeLength){const ch=text.charCodeAt(pos);if(ch===42&&text.charCodeAt(pos+1)===47){pos+=2;commentClosed=true;break}pos++;if(isLineBreak(ch)){if(ch===13&&text.charCodeAt(pos)===10){pos++}lineNumber++;tokenLineStartOffset=pos}}if(!commentClosed){pos++;scanError=1}value=text.substring(start,pos);return token=13}value+=String.fromCharCode(code);pos++;return token=16;case 45:value+=String.fromCharCode(code);pos++;if(pos===len||!isDigit(text.charCodeAt(pos))){return token=16}case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:value+=scanNumber();return token=11;default:while(pos<len&&isUnknownContentCharacter(code)){pos++;code=text.charCodeAt(pos)}if(tokenOffset!==pos){value=text.substring(tokenOffset,pos);switch(value){case"true":return token=8;case"false":return token=9;case"null":return token=7}return token=16}value+=String.fromCharCode(code);pos++;return token=16}}__name(scanNext,"scanNext");function isUnknownContentCharacter(code){if(isWhiteSpace(code)||isLineBreak(code)){return false}switch(code){case 125:case 93:case 123:case 91:case 34:case 58:case 44:case 47:return false}return true}__name(isUnknownContentCharacter,"isUnknownContentCharacter");function scanNextNonTrivia(){let result;do{result=scanNext()}while(result>=12&&result<=15);return result}__name(scanNextNonTrivia,"scanNextNonTrivia");return{setPosition,getPosition:__name(()=>pos,"getPosition"),scan:ignoreTrivia?scanNextNonTrivia:scanNext,getToken:__name(()=>token,"getToken"),getTokenValue:__name(()=>value,"getTokenValue"),getTokenOffset:__name(()=>tokenOffset,"getTokenOffset"),getTokenLength:__name(()=>pos-tokenOffset,"getTokenLength"),getTokenStartLine:__name(()=>lineStartOffset,"getTokenStartLine"),getTokenStartCharacter:__name(()=>tokenOffset-prevTokenLineStartOffset,"getTokenStartCharacter"),getTokenError:__name(()=>scanError,"getTokenError")}}__name(createScanner,"createScanner");function isWhiteSpace(ch){return ch===32||ch===9}__name(isWhiteSpace,"isWhiteSpace");function isLineBreak(ch){return ch===10||ch===13}__name(isLineBreak,"isLineBreak");function isDigit(ch){return ch>=48&&ch<=57}__name(isDigit,"isDigit");var CharacterCodes;(function(CharacterCodes2){CharacterCodes2[CharacterCodes2["lineFeed"]=10]="lineFeed";CharacterCodes2[CharacterCodes2["carriageReturn"]=13]="carriageReturn";CharacterCodes2[CharacterCodes2["space"]=32]="space";CharacterCodes2[CharacterCodes2["_0"]=48]="_0";CharacterCodes2[CharacterCodes2["_1"]=49]="_1";CharacterCodes2[CharacterCodes2["_2"]=50]="_2";CharacterCodes2[CharacterCodes2["_3"]=51]="_3";CharacterCodes2[CharacterCodes2["_4"]=52]="_4";CharacterCodes2[CharacterCodes2["_5"]=53]="_5";CharacterCodes2[CharacterCodes2["_6"]=54]="_6";CharacterCodes2[CharacterCodes2["_7"]=55]="_7";CharacterCodes2[CharacterCodes2["_8"]=56]="_8";CharacterCodes2[CharacterCodes2["_9"]=57]="_9";CharacterCodes2[CharacterCodes2["a"]=97]="a";CharacterCodes2[CharacterCodes2["b"]=98]="b";CharacterCodes2[CharacterCodes2["c"]=99]="c";CharacterCodes2[CharacterCodes2["d"]=100]="d";CharacterCodes2[CharacterCodes2["e"]=101]="e";CharacterCodes2[CharacterCodes2["f"]=102]="f";CharacterCodes2[CharacterCodes2["g"]=103]="g";CharacterCodes2[CharacterCodes2["h"]=104]="h";CharacterCodes2[CharacterCodes2["i"]=105]="i";CharacterCodes2[CharacterCodes2["j"]=106]="j";CharacterCodes2[CharacterCodes2["k"]=107]="k";CharacterCodes2[CharacterCodes2["l"]=108]="l";CharacterCodes2[CharacterCodes2["m"]=109]="m";CharacterCodes2[CharacterCodes2["n"]=110]="n";CharacterCodes2[CharacterCodes2["o"]=111]="o";CharacterCodes2[CharacterCodes2["p"]=112]="p";CharacterCodes2[CharacterCodes2["q"]=113]="q";CharacterCodes2[CharacterCodes2["r"]=114]="r";CharacterCodes2[CharacterCodes2["s"]=115]="s";CharacterCodes2[CharacterCodes2["t"]=116]="t";CharacterCodes2[CharacterCodes2["u"]=117]="u";CharacterCodes2[CharacterCodes2["v"]=118]="v";CharacterCodes2[CharacterCodes2["w"]=119]="w";CharacterCodes2[CharacterCodes2["x"]=120]="x";CharacterCodes2[CharacterCodes2["y"]=121]="y";CharacterCodes2[CharacterCodes2["z"]=122]="z";CharacterCodes2[CharacterCodes2["A"]=65]="A";CharacterCodes2[CharacterCodes2["B"]=66]="B";CharacterCodes2[CharacterCodes2["C"]=67]="C";CharacterCodes2[CharacterCodes2["D"]=68]="D";CharacterCodes2[CharacterCodes2["E"]=69]="E";CharacterCodes2[CharacterCodes2["F"]=70]="F";CharacterCodes2[CharacterCodes2["G"]=71]="G";CharacterCodes2[CharacterCodes2["H"]=72]="H";CharacterCodes2[CharacterCodes2["I"]=73]="I";CharacterCodes2[CharacterCodes2["J"]=74]="J";CharacterCodes2[CharacterCodes2["K"]=75]="K";CharacterCodes2[CharacterCodes2["L"]=76]="L";CharacterCodes2[CharacterCodes2["M"]=77]="M";CharacterCodes2[CharacterCodes2["N"]=78]="N";CharacterCodes2[CharacterCodes2["O"]=79]="O";CharacterCodes2[CharacterCodes2["P"]=80]="P";CharacterCodes2[CharacterCodes2["Q"]=81]="Q";CharacterCodes2[CharacterCodes2["R"]=82]="R";CharacterCodes2[CharacterCodes2["S"]=83]="S";CharacterCodes2[CharacterCodes2["T"]=84]="T";CharacterCodes2[CharacterCodes2["U"]=85]="U";CharacterCodes2[CharacterCodes2["V"]=86]="V";CharacterCodes2[CharacterCodes2["W"]=87]="W";CharacterCodes2[CharacterCodes2["X"]=88]="X";CharacterCodes2[CharacterCodes2["Y"]=89]="Y";CharacterCodes2[CharacterCodes2["Z"]=90]="Z";CharacterCodes2[CharacterCodes2["asterisk"]=42]="asterisk";CharacterCodes2[CharacterCodes2["backslash"]=92]="backslash";CharacterCodes2[CharacterCodes2["closeBrace"]=125]="closeBrace";CharacterCodes2[CharacterCodes2["closeBracket"]=93]="closeBracket";CharacterCodes2[CharacterCodes2["colon"]=58]="colon";CharacterCodes2[CharacterCodes2["comma"]=44]="comma";CharacterCodes2[CharacterCodes2["dot"]=46]="dot";CharacterCodes2[CharacterCodes2["doubleQuote"]=34]="doubleQuote";CharacterCodes2[CharacterCodes2["minus"]=45]="minus";CharacterCodes2[CharacterCodes2["openBrace"]=123]="openBrace";CharacterCodes2[CharacterCodes2["openBracket"]=91]="openBracket";CharacterCodes2[CharacterCodes2["plus"]=43]="plus";CharacterCodes2[CharacterCodes2["slash"]=47]="slash";CharacterCodes2[CharacterCodes2["formFeed"]=12]="formFeed";CharacterCodes2[CharacterCodes2["tab"]=9]="tab"})(CharacterCodes||(CharacterCodes={}));init_esbuild_shims();var cachedSpaces=new Array(20).fill(0).map((_,index)=>{return" ".repeat(index)});var maxCachedValues=200;var cachedBreakLinesWithSpaces={" ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r\n"+" ".repeat(index)})}," ":{"\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\n"+" ".repeat(index)}),"\r":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r"+" ".repeat(index)}),"\r\n":new Array(maxCachedValues).fill(0).map((_,index)=>{return"\r\n"+" ".repeat(index)})}};var supportedEols=["\n","\r","\r\n"];function format(documentText,range,options){let initialIndentLevel;let formatText;let formatTextStart;let rangeStart;let rangeEnd;if(range){rangeStart=range.offset;rangeEnd=rangeStart+range.length;formatTextStart=rangeStart;while(formatTextStart>0&&!isEOL(documentText,formatTextStart-1)){formatTextStart--}let endOffset=rangeEnd;while(endOffset<documentText.length&&!isEOL(documentText,endOffset)){endOffset++}formatText=documentText.substring(formatTextStart,endOffset);initialIndentLevel=computeIndentLevel(formatText,options)}else{formatText=documentText;initialIndentLevel=0;formatTextStart=0;rangeStart=0;rangeEnd=documentText.length}const eol=getEOL(options,documentText);const eolFastPathSupported=supportedEols.includes(eol);let numberLineBreaks=0;let indentLevel=0;let indentValue;if(options.insertSpaces){indentValue=cachedSpaces[options.tabSize||4]??repeat(cachedSpaces[1],options.tabSize||4)}else{indentValue=" "}const indentType=indentValue===" "?" ":" ";let scanner=createScanner(formatText,false);let hasError=false;function newLinesAndIndent(){if(numberLineBreaks>1){return repeat(eol,numberLineBreaks)+repeat(indentValue,initialIndentLevel+indentLevel)}const amountOfSpaces=indentValue.length*(initialIndentLevel+indentLevel);if(!eolFastPathSupported||amountOfSpaces>cachedBreakLinesWithSpaces[indentType][eol].length){return eol+repeat(indentValue,initialIndentLevel+indentLevel)}if(amountOfSpaces<=0){return eol}return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]}__name(newLinesAndIndent,"newLinesAndIndent");function scanNext(){let token=scanner.scan();numberLineBreaks=0;while(token===15||token===14){if(token===14&&options.keepLines){numberLineBreaks+=1}else if(token===14){numberLineBreaks=1}token=scanner.scan()}hasError=token===16||scanner.getTokenError()!==0;return token}__name(scanNext,"scanNext");const editOperations=[];function addEdit(text,startOffset,endOffset){if(!hasError&&(!range||startOffset<rangeEnd&&endOffset>rangeStart)&&documentText.substring(startOffset,endOffset)!==text){editOperations.push({offset:startOffset,length:endOffset-startOffset,content:text})}}__name(addEdit,"addEdit");let firstToken=scanNext();if(options.keepLines&&numberLineBreaks>0){addEdit(repeat(eol,numberLineBreaks),0,0)}if(firstToken!==17){let firstTokenStart=scanner.getTokenOffset()+formatTextStart;let initialIndent=indentValue.length*initialIndentLevel<20&&options.insertSpaces?cachedSpaces[indentValue.length*initialIndentLevel]:repeat(indentValue,initialIndentLevel);addEdit(initialIndent,formatTextStart,firstTokenStart)}while(firstToken!==17){let firstTokenEnd=scanner.getTokenOffset()+scanner.getTokenLength()+formatTextStart;let secondToken=scanNext();let replaceContent="";let needsLineBreak=false;while(numberLineBreaks===0&&(secondToken===12||secondToken===13)){let commentTokenStart=scanner.getTokenOffset()+formatTextStart;addEdit(cachedSpaces[1],firstTokenEnd,commentTokenStart);firstTokenEnd=scanner.getTokenOffset()+scanner.getTokenLength()+formatTextStart;needsLineBreak=secondToken===12;replaceContent=needsLineBreak?newLinesAndIndent():"";secondToken=scanNext()}if(secondToken===2){if(firstToken!==1){indentLevel--};if(options.keepLines&&numberLineBreaks>0||!options.keepLines&&firstToken!==1){replaceContent=newLinesAndIndent()}else if(options.keepLines){replaceContent=cachedSpaces[1]}}else if(secondToken===4){if(firstToken!==3){indentLevel--};if(options.keepLines&&numberLineBreaks>0||!options.keepLines&&firstToken!==3){replaceContent=newLinesAndIndent()}else if(options.keepLines){replaceContent=cachedSpaces[1]}}else{switch(firstToken){case 3:case 1:indentLevel++;if(options.keepLines&&numberLineBreaks>0||!options.keepLines){replaceContent=newLinesAndIndent()}else{replaceContent=cachedSpaces[1]}break;case 5:if(options.keepLines&&numberLineBreaks>0||!options.keepLines){replaceContent=newLinesAndIndent()}else{replaceContent=cachedSpaces[1]}break;case 12:replaceContent=newLinesAndIndent();break;case 13:if(numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(!needsLineBreak){replaceContent=cachedSpaces[1]}break;case 6:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(!needsLineBreak){replaceContent=cachedSpaces[1]}break;case 10:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else if(secondToken===6&&!needsLineBreak){replaceContent=""}break;case 7:case 8:case 9:case 11:case 2:case 4:if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else{if((secondToken===12||secondToken===13)&&!needsLineBreak){replaceContent=cachedSpaces[1]}else if(secondToken!==5&&secondToken!==17){hasError=true}}break;case 16:hasError=true;break}if(numberLineBreaks>0&&(secondToken===12||secondToken===13)){replaceContent=newLinesAndIndent()}}if(secondToken===17){if(options.keepLines&&numberLineBreaks>0){replaceContent=newLinesAndIndent()}else{replaceContent=options.insertFinalNewline?eol:""}}const secondTokenStart=scanner.getTokenOffset()+formatTextStart;addEdit(replaceContent,firstTokenEnd,secondTokenStart);firstToken=secondToken}return editOperations}__name(format,"format");function repeat(s,count){let result="";for(let i=0;i<count;i++){result+=s}return result}__name(repeat,"repeat");function computeIndentLevel(content,options){let i=0;let nChars=0;const tabSize=options.tabSize||4;while(i<content.length){let ch=content.charAt(i);if(ch===cachedSpaces[1]){nChars++}else if(ch===" "){nChars+=tabSize}else{break}i++}return Math.floor(nChars/tabSize)}__name(computeIndentLevel,"computeIndentLevel");function getEOL(options,text){for(let i=0;i<text.length;i++){const ch=text.charAt(i);if(ch==="\r"){if(i+1<text.length&&text.charAt(i+1)==="\n"){return"\r\n"}return"\r"}else if(ch==="\n"){return"\n"}}return options&&options.eol||"\n"}__name(getEOL,"getEOL");function isEOL(text,offset){return"\r\n".indexOf(text.charAt(offset))!==-1}__name(isEOL,"isEOL");init_esbuild_shims();init_esbuild_shims();var ParseOptions;(function(ParseOptions2){ParseOptions2.DEFAULT={allowTrailingComma:false}})(ParseOptions||(ParseOptions={}));function parseTree(text,errors=[],options=ParseOptions.DEFAULT){let currentParent={type:"array",offset:-1,length:-1,children:[],parent:void 0};function ensurePropertyComplete(endOffset){if(currentParent.type==="property"){currentParent.length=endOffset-currentParent.offset;currentParent=currentParent.parent}}__name(ensurePropertyComplete,"ensurePropertyComplete");function onValue(valueNode){currentParent.children.push(valueNode);return valueNode}__name(onValue,"onValue");const visitor={onObjectBegin:__name(offset=>{currentParent=onValue({type:"object",offset,length:-1,parent:currentParent,children:[]})},"onObjectBegin"),onObjectProperty:__name((name,offset,length)=>{currentParent=onValue({type:"property",offset,length:-1,parent:currentParent,children:[]});currentParent.children.push({type:"string",value:name,offset,length,parent:currentParent})},"onObjectProperty"),onObjectEnd:__name((offset,length)=>{ensurePropertyComplete(offset+length);currentParent.length=offset+length-currentParent.offset;currentParent=currentParent.parent;ensurePropertyComplete(offset+length)},"onObjectEnd"),onArrayBegin:__name((offset,length)=>{currentParent=onValue({type:"array",offset,length:-1,parent:currentParent,children:[]})},"onArrayBegin"),onArrayEnd:__name((offset,length)=>{currentParent.length=offset+length-currentParent.offset;currentParent=currentParent.parent;ensurePropertyComplete(offset+length)},"onArrayEnd"),onLiteralValue:__name((value,offset,length)=>{onValue({type:getNodeType(value),offset,length,parent:currentParent,value});ensurePropertyComplete(offset+length)},"onLiteralValue"),onSeparator:__name((sep,offset,length)=>{if(currentParent.type==="property"){if(sep===":"){currentParent.colonOffset=offset}else if(sep===","){ensurePropertyComplete(offset)}}},"onSeparator"),onError:__name((error,offset,length)=>{errors.push({error,offset,length})},"onError")};visit(text,visitor,options);const result=currentParent.children[0];if(result){delete result.parent}return result}__name(parseTree,"parseTree");function findNodeAtLocation(root,path4){if(!root){return void 0}let node=root;for(let segment of path4){if(typeof segment==="string"){if(node.type!=="object"||!Array.isArray(node.children)){return void 0}let found=false;for(const propertyNode of node.children){if(Array.isArray(propertyNode.children)&&propertyNode.children[0].value===segment&&propertyNode.children.length===2){node=propertyNode.children[1];found=true;break}}if(!found){return void 0}}else{const index=segment;if(node.type!=="array"||index<0||!Array.isArray(node.children)||index>=node.children.length){return void 0}node=node.children[index]}}return node}__name(findNodeAtLocation,"findNodeAtLocation");function getNodeValue(node){switch(node.type){case"array":return node.children.map(getNodeValue);case"object":const obj=Object.create(null);for(let prop of node.children){const valueNode=prop.children[1];if(valueNode){obj[prop.children[0].value]=getNodeValue(valueNode)}}return obj;case"null":case"string":case"number":case"boolean":return node.value;default:return void 0}}__name(getNodeValue,"getNodeValue");function visit(text,visitor,options=ParseOptions.DEFAULT){const _scanner=createScanner(text,false);const _jsonPath=[];let suppressedCallbacks=0;function toNoArgVisit(visitFunction){return visitFunction?()=>suppressedCallbacks===0&&visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}__name(toNoArgVisit,"toNoArgVisit");function toOneArgVisit(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter()):()=>true}__name(toOneArgVisit,"toOneArgVisit");function toOneArgVisitWithPath(visitFunction){return visitFunction?arg=>suppressedCallbacks===0&&visitFunction(arg,_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice()):()=>true}__name(toOneArgVisitWithPath,"toOneArgVisitWithPath");function toBeginVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks++}else{let cbReturn=visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter(),()=>_jsonPath.slice());if(cbReturn===false){suppressedCallbacks=1}}}:()=>true}__name(toBeginVisit,"toBeginVisit");function toEndVisit(visitFunction){return visitFunction?()=>{if(suppressedCallbacks>0){suppressedCallbacks--}if(suppressedCallbacks===0){visitFunction(_scanner.getTokenOffset(),_scanner.getTokenLength(),_scanner.getTokenStartLine(),_scanner.getTokenStartCharacter())}}:()=>true}__name(toEndVisit,"toEndVisit");const onObjectBegin=toBeginVisit(visitor.onObjectBegin),onObjectProperty=toOneArgVisitWithPath(visitor.onObjectProperty),onObjectEnd=toEndVisit(visitor.onObjectEnd),onArrayBegin=toBeginVisit(visitor.onArrayBegin),onArrayEnd=toEndVisit(visitor.onArrayEnd),onLiteralValue=toOneArgVisitWithPath(visitor.onLiteralValue),onSeparator=toOneArgVisit(visitor.onSeparator),onComment=toNoArgVisit(visitor.onComment),onError=toOneArgVisit(visitor.onError);const disallowComments=options&&options.disallowComments;const allowTrailingComma=options&&options.allowTrailingComma;function scanNext(){while(true){const token=_scanner.scan();switch(_scanner.getTokenError()){case 4:handleError(14);break;case 5:handleError(15);break;case 3:handleError(13);break;case 1:if(!disallowComments){handleError(11)}break;case 2:handleError(12);break;case 6:handleError(16);break}switch(token){case 12:case 13:if(disallowComments){handleError(10)}else{onComment()}break;case 16:handleError(1);break;case 15:case 14:break;default:return token}}}__name(scanNext,"scanNext");function handleError(error,skipUntilAfter=[],skipUntil=[]){onError(error);if(skipUntilAfter.length+skipUntil.length>0){let token=_scanner.getToken();while(token!==17){if(skipUntilAfter.indexOf(token)!==-1){scanNext();break}else if(skipUntil.indexOf(token)!==-1){break}token=scanNext()}}}__name(handleError,"handleError");function parseString(isValue){const value=_scanner.getTokenValue();if(isValue){onLiteralValue(value)}else{onObjectProperty(value);_jsonPath.push(value)}scanNext();return true}__name(parseString,"parseString");function parseLiteral(){switch(_scanner.getToken()){case 11:const tokenValue=_scanner.getTokenValue();let value=Number(tokenValue);if(isNaN(value)){handleError(2);value=0}onLiteralValue(value);break;case 7:onLiteralValue(null);break;case 8:onLiteralValue(true);break;case 9:onLiteralValue(false);break;default:return false}scanNext();return true}__name(parseLiteral,"parseLiteral");function parseProperty(){if(_scanner.getToken()!==10){handleError(3,[],[2,5]);return false}parseString(false);if(_scanner.getToken()===6){onSeparator(":");scanNext();if(!parseValue()){handleError(4,[],[2,5])}}else{handleError(5,[],[2,5])}_jsonPath.pop();return true}__name(parseProperty,"parseProperty");function parseObject(){onObjectBegin();scanNext();let needsComma=false;while(_scanner.getToken()!==2&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===2&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(!parseProperty()){handleError(4,[],[2,5])}needsComma=true}onObjectEnd();if(_scanner.getToken()!==2){handleError(7,[2],[])}else{scanNext()}return true}__name(parseObject,"parseObject");function parseArray(){onArrayBegin();scanNext();let isFirstElement=true;let needsComma=false;while(_scanner.getToken()!==4&&_scanner.getToken()!==17){if(_scanner.getToken()===5){if(!needsComma){handleError(4,[],[])}onSeparator(",");scanNext();if(_scanner.getToken()===4&&allowTrailingComma){break}}else if(needsComma){handleError(6,[],[])}if(isFirstElement){_jsonPath.push(0);isFirstElement=false}else{_jsonPath[_jsonPath.length-1]++}if(!parseValue()){handleError(4,[],[4,5])}needsComma=true}onArrayEnd();if(!isFirstElement){_jsonPath.pop()}if(_scanner.getToken()!==4){handleError(8,[4],[])}else{scanNext()}return true}__name(parseArray,"parseArray");function parseValue(){switch(_scanner.getToken()){case 3:return parseArray();case 1:return parseObject();case 10:return parseString(true);default:return parseLiteral()}}__name(parseValue,"parseValue");scanNext();if(_scanner.getToken()===17){if(options.allowEmptyContent){return true}handleError(4,[],[]);return false}if(!parseValue()){handleError(4,[],[]);return false}if(_scanner.getToken()!==17){handleError(9,[],[])}return true}__name(visit,"visit");function getNodeType(value){switch(typeof value){case"boolean":return"boolean";case"number":return"number";case"string":return"string";case"object":{if(!value){return"null"}else if(Array.isArray(value)){return"array"}return"object"}default:return"null"}}__name(getNodeType,"getNodeType");function setProperty(text,originalPath,value,options){const path4=originalPath.slice();const errors=[];const root=parseTree(text,errors);let parent=void 0;let lastSegment=void 0;while(path4.length>0){lastSegment=path4.pop();parent=findNodeAtLocation(root,path4);if(parent===void 0&&value!==void 0){if(typeof lastSegment==="string"){value={[lastSegment]:value}}else{value=[value]}}else{break}}if(!parent){if(value===void 0){throw new Error("Can not delete in empty document")}return withFormatting(text,{offset:root?root.offset:0,length:root?root.length:0,content:JSON.stringify(value)},options)}else if(parent.type==="object"&&typeof lastSegment==="string"&&Array.isArray(parent.children)){const existing=findNodeAtLocation(parent,[lastSegment]);if(existing!==void 0){if(value===void 0){if(!existing.parent){throw new Error("Malformed AST")}const propertyIndex=parent.children.indexOf(existing.parent);let removeBegin;let removeEnd=existing.parent.offset+existing.parent.length;if(propertyIndex>0){let previous=parent.children[propertyIndex-1];removeBegin=previous.offset+previous.length}else{removeBegin=parent.offset+1;if(parent.children.length>1){let next=parent.children[1];removeEnd=next.offset}}return withFormatting(text,{offset:removeBegin,length:removeEnd-removeBegin,content:""},options)}else{return withFormatting(text,{offset:existing.offset,length:existing.length,content:JSON.stringify(value)},options)}}else{if(value===void 0){return[]}const newProperty=`${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;const index=options.getInsertionIndex?options.getInsertionIndex(parent.children.map(p=>p.children[0].value)):parent.children.length;let edit;if(index>0){let previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}else if(parent.children.length===0){edit={offset:parent.offset+1,length:0,content:newProperty}}else{edit={offset:parent.offset+1,length:0,content:newProperty+","}}return withFormatting(text,edit,options)}}else if(parent.type==="array"&&typeof lastSegment==="number"&&Array.isArray(parent.children)){const insertIndex=lastSegment;if(insertIndex===-1){const newProperty=`${JSON.stringify(value)}`;let edit;if(parent.children.length===0){edit={offset:parent.offset+1,length:0,content:newProperty}}else{const previous=parent.children[parent.children.length-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else if(value===void 0&&parent.children.length>=0){const removalIndex=lastSegment;const toRemove=parent.children[removalIndex];let edit;if(parent.children.length===1){edit={offset:parent.offset+1,length:parent.length-2,content:""}}else if(parent.children.length-1===removalIndex){let previous=parent.children[removalIndex-1];let offset=previous.offset+previous.length;let parentEndOffset=parent.offset+parent.length;edit={offset,length:parentEndOffset-2-offset,content:""}}else{edit={offset:toRemove.offset,length:parent.children[removalIndex+1].offset-toRemove.offset,content:""}}return withFormatting(text,edit,options)}else if(value!==void 0){let edit;const newProperty=`${JSON.stringify(value)}`;if(!options.isArrayInsertion&&parent.children.length>lastSegment){const toModify=parent.children[lastSegment];edit={offset:toModify.offset,length:toModify.length,content:newProperty}}else if(parent.children.length===0||lastSegment===0){edit={offset:parent.offset+1,length:0,content:parent.children.length===0?newProperty:newProperty+","}}else{const index=lastSegment>parent.children.length?parent.children.length:lastSegment;const previous=parent.children[index-1];edit={offset:previous.offset+previous.length,length:0,content:","+newProperty}}return withFormatting(text,edit,options)}else{throw new Error(`Can not ${value===void 0?"remove":options.isArrayInsertion?"insert":"modify"} Array index ${insertIndex} as length is not sufficient`)}}else{throw new Error(`Can not add ${typeof lastSegment!=="number"?"index":"property"} to parent of type ${parent.type}`)}}__name(setProperty,"setProperty");function withFormatting(text,edit,options){if(!options.formattingOptions){return[edit]}let newText=applyEdit(text,edit);let begin=edit.offset;let end=edit.offset+edit.content.length;if(edit.length===0||edit.content.length===0){while(begin>0&&!isEOL(newText,begin-1)){begin--}while(end<newText.length&&!isEOL(newText,end)){end++}}const edits=format(newText,{offset:begin,length:end-begin},{...options.formattingOptions,keepLines:false});for(let i=edits.length-1;i>=0;i--){const edit2=edits[i];newText=applyEdit(newText,edit2);begin=Math.min(begin,edit2.offset);end=Math.max(end,edit2.offset+edit2.length);end+=edit2.content.length-edit2.length}const editLength=text.length-(newText.length-end)-begin;return[{offset:begin,length:editLength,content:newText.substring(begin,end)}]}__name(withFormatting,"withFormatting");function applyEdit(text,edit){return text.substring(0,edit.offset)+edit.content+text.substring(edit.offset+edit.length)}__name(applyEdit,"applyEdit");var ScanError;(function(ScanError2){ScanError2[ScanError2["None"]=0]="None";ScanError2[ScanError2["UnexpectedEndOfComment"]=1]="UnexpectedEndOfComment";ScanError2[ScanError2["UnexpectedEndOfString"]=2]="UnexpectedEndOfString";ScanError2[ScanError2["UnexpectedEndOfNumber"]=3]="UnexpectedEndOfNumber";ScanError2[ScanError2["InvalidUnicode"]=4]="InvalidUnicode";ScanError2[ScanError2["InvalidEscapeCharacter"]=5]="InvalidEscapeCharacter";ScanError2[ScanError2["InvalidCharacter"]=6]="InvalidCharacter"})(ScanError||(ScanError={}));var SyntaxKind;(function(SyntaxKind2){SyntaxKind2[SyntaxKind2["OpenBraceToken"]=1]="OpenBraceToken";SyntaxKind2[SyntaxKind2["CloseBraceToken"]=2]="CloseBraceToken";SyntaxKind2[SyntaxKind2["OpenBracketToken"]=3]="OpenBracketToken";SyntaxKind2[SyntaxKind2["CloseBracketToken"]=4]="CloseBracketToken";SyntaxKind2[SyntaxKind2["CommaToken"]=5]="CommaToken";SyntaxKind2[SyntaxKind2["ColonToken"]=6]="ColonToken";SyntaxKind2[SyntaxKind2["NullKeyword"]=7]="NullKeyword";SyntaxKind2[SyntaxKind2["TrueKeyword"]=8]="TrueKeyword";SyntaxKind2[SyntaxKind2["FalseKeyword"]=9]="FalseKeyword";SyntaxKind2[SyntaxKind2["StringLiteral"]=10]="StringLiteral";SyntaxKind2[SyntaxKind2["NumericLiteral"]=11]="NumericLiteral";SyntaxKind2[SyntaxKind2["LineCommentTrivia"]=12]="LineCommentTrivia";SyntaxKind2[SyntaxKind2["BlockCommentTrivia"]=13]="BlockCommentTrivia";SyntaxKind2[SyntaxKind2["LineBreakTrivia"]=14]="LineBreakTrivia";SyntaxKind2[SyntaxKind2["Trivia"]=15]="Trivia";SyntaxKind2[SyntaxKind2["Unknown"]=16]="Unknown";SyntaxKind2[SyntaxKind2["EOF"]=17]="EOF"})(SyntaxKind||(SyntaxKind={}));var parseTree2=parseTree;var findNodeAtLocation2=findNodeAtLocation;var getNodeValue2=getNodeValue;var ParseErrorCode;(function(ParseErrorCode2){ParseErrorCode2[ParseErrorCode2["InvalidSymbol"]=1]="InvalidSymbol";ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"]=2]="InvalidNumberFormat";ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"]=3]="PropertyNameExpected";ParseErrorCode2[ParseErrorCode2["ValueExpected"]=4]="ValueExpected";ParseErrorCode2[ParseErrorCode2["ColonExpected"]=5]="ColonExpected";ParseErrorCode2[ParseErrorCode2["CommaExpected"]=6]="CommaExpected";ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"]=7]="CloseBraceExpected";ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"]=8]="CloseBracketExpected";ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"]=9]="EndOfFileExpected";ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"]=10]="InvalidCommentToken";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"]=11]="UnexpectedEndOfComment";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"]=12]="UnexpectedEndOfString";ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"]=13]="UnexpectedEndOfNumber";ParseErrorCode2[ParseErrorCode2["InvalidUnicode"]=14]="InvalidUnicode";ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"]=15]="InvalidEscapeCharacter";ParseErrorCode2[ParseErrorCode2["InvalidCharacter"]=16]="InvalidCharacter"})(ParseErrorCode||(ParseErrorCode={}));function printParseErrorCode(code){switch(code){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}__name(printParseErrorCode,"printParseErrorCode");function modify(text,path4,value,options){return setProperty(text,path4,value,options)}__name(modify,"modify");function applyEdits(text,edits){let sortedEdits=edits.slice(0).sort((a,b)=>{const diff=a.offset-b.offset;if(diff===0){return a.length-b.length}return diff});let lastModifiedOffset=text.length;for(let i=sortedEdits.length-1;i>=0;i--){let e=sortedEdits[i];if(e.offset+e.length<=lastModifiedOffset){text=applyEdit(text,e)}else{throw new Error("Overlapping edit")}lastModifiedOffset=e.offset}return text}__name(applyEdits,"applyEdits");init_esbuild_shims();import*as fs from"node:fs";import path from"node:path";function writeWithBackupSync(targetPath,content,options={}){const{backupSuffix=".orig",encoding="utf-8"}=options;const existing=fs.existsSync(targetPath)?fs.statSync(targetPath):void 0;if(existing?.isDirectory()){throw new Error(`Cannot write to '${targetPath}' because it is a directory`)}const workingDirectory=fs.mkdtempSync(`${targetPath}.write-`);const basename=path.basename(targetPath);const tempPath=path.join(workingDirectory,`${basename}.tmp`);const backupPath=path.join(workingDirectory,`${basename}${backupSuffix}`);let backupCreated=false;try{const mode=existing&&fs.lstatSync(targetPath,{throwIfNoEntry:false})?.isFile()?existing.mode&511:void 0;fs.writeFileSync(tempPath,content,{encoding,flag:"wx",flush:true,mode});if(mode!==void 0){try{fs.chmodSync(tempPath,mode)}catch(error){const code=error instanceof Error&&"code"in error?error.code:void 0;if(code!=="ENOSYS"&&code!=="ENOTSUP"&&code!=="EPERM"||(fs.statSync(tempPath).mode&511&~mode)!==0){throw error}}}if(fs.existsSync(targetPath)){try{fs.copyFileSync(targetPath,backupPath,fs.constants.COPYFILE_EXCL);backupCreated=true}catch(backupError){throw new Error(`Failed to backup existing file: ${backupError instanceof Error?backupError.message:String(backupError)}`)}}fs.renameSync(tempPath,targetPath)}catch(error){const recoveryRetained=backupCreated&&!sameContents(backupPath,targetPath);try{if(recoveryRetained){fs.unlinkSync(tempPath)}else{fs.rmSync(workingDirectory,{recursive:true,force:true})}}catch{}if(recoveryRetained){throw new Error(`Failed to write file: ${error instanceof Error?error.message:String(error)}. Recovery copy retained at '${backupPath}'; inspect the current target before restoring it.`)}throw error}try{fs.rmSync(workingDirectory,{recursive:true,force:true})}catch{}}__name(writeWithBackupSync,"writeWithBackupSync");function sameContents(first,second){try{return fs.readFileSync(first).equals(fs.readFileSync(second))}catch{return false}}__name(sameContents,"sameContents");var PARSE_OPTIONS={allowTrailingComma:true};function updateSettingsFilePreservingFormat(filePath,updates,sync=false,replacePath=[]){if(!fs2.existsSync(filePath)){const content=JSON.stringify(updates,null,2);writeWithBackupSync(filePath,content);return true}const originalContent=fs2.readFileSync(filePath,"utf-8");try{parseJsoncObject(originalContent)}catch(_error){writeStderrLine("Error parsing settings file.");writeStderrLine(`Settings file may be corrupted: ${_error instanceof Error?_error.message:String(_error)}`);return false}let updatedContent;try{updatedContent=updateJsoncContent(originalContent,updates,sync,replacePath)}catch(validationError){writeStderrLine("Error: Refusing to write settings file \u2014 the result would not be valid JSON.");writeStderrLine(validationError instanceof Error?validationError.message:String(validationError));return false}writeWithBackupSync(filePath,updatedContent);return true}__name(updateSettingsFilePreservingFormat,"updateSettingsFilePreservingFormat");function parseJsoncObject(content){const errors=[];const root=parseTree2(stripBom(content),errors,PARSE_OPTIONS);if(errors.length>0){const error=errors[0];throw new Error(`${printParseErrorCode(error.error)} at offset ${error.offset}`)}if(root?.type!=="object"){throw new Error("JSONC document root is not a JSON object.")}return JSON.parse(JSON.stringify(getNodeValue2(root)))}__name(parseJsoncObject,"parseJsoncObject");function updateJsoncContent(content,updates,sync=false,replacePath=[]){const bom=content.startsWith("\uFEFF")?"\uFEFF":"";const editableContent=stripBom(content);const parsed=parseJsoncObject(editableContent);const targetWithUndefined=applyUpdates(structuredClone(parsed),updates,sync,replacePath);const target=JSON.parse(JSON.stringify(targetWithUndefined));const options={formattingOptions:detectFormattingOptions(editableContent)};let updated=normalizeDuplicateProperties(editableContent,options);const current=parseJsoncObject(updated);for(const operation of collectOperations(current,target)){if(operation.value===void 0){updated=removeTrailingInlineComment(updated,operation.path)}updated=applyEdits(updated,modify(updated,operation.path,operation.value,options))}const reparsed=parseJsoncObject(updated);if(!isDeepStrictEqual(reparsed,target)){throw new Error("Edited JSONC does not match the intended settings.")}return bom+updated}__name(updateJsoncContent,"updateJsoncContent");function applyUpdates(current,updates,sync=false,replacePath=[],currentPath=[]){const result=current;if(sync){const keysToRemove=Object.keys(result).filter(key=>!Object.hasOwn(updates,key));for(const key of keysToRemove){delete result[key]}}for(const key of Object.getOwnPropertyNames(updates)){if(key==="__proto__"||key==="constructor"||key==="prototype"){continue}const value=updates[key];const nextPath=[...currentPath,key];const valueIsObject=typeof value==="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length>0;if(pathsEqual(nextPath,replacePath)){result[key]=valueIsObject?applyUpdates({},value):value;continue}if(valueIsObject&&(typeof result[key]!=="object"||result[key]===null||Array.isArray(result[key]))){result[key]=applyUpdates({},value,sync,replacePath,nextPath)}else if(valueIsObject&&typeof result[key]==="object"&&result[key]!==null&&!Array.isArray(result[key])){result[key]=applyUpdates(result[key],value,sync,replacePath,nextPath)}else{result[key]=value}}return result}__name(applyUpdates,"applyUpdates");function stripBom(content){return content.startsWith("\uFEFF")?content.slice(1):content}__name(stripBom,"stripBom");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function detectFormattingOptions(content){const root=parseTree2(content,[],PARSE_OPTIONS);const firstKey=root?.children?.[0]?.children?.[0];const lineStart=firstKey===void 0?-1:content.lastIndexOf("\n",firstKey.offset-1);const candidate=firstKey===void 0?void 0:content.slice(lineStart+1,firstKey.offset);const indentation=candidate!==void 0&&/^[ \t]*$/.test(candidate)?candidate:" ";return{eol:content.includes("\r\n")?"\r\n":"\n",insertSpaces:!indentation.startsWith(" "),tabSize:indentation.startsWith(" ")?1:indentation.length,insertFinalNewline:content.endsWith("\n")}}__name(detectFormattingOptions,"detectFormattingOptions");function collectOperations(current,target,path4=[],operations=[]){for(const key of Object.keys(current)){if(!Object.hasOwn(target,key)){operations.push({path:[...path4,key],value:void 0})}}for(const key of Object.keys(target)){const nextPath=[...path4,key];if(!Object.hasOwn(current,key)){operations.push({path:nextPath,value:target[key]})}else if(isRecord(current[key])&&isRecord(target[key])){collectOperations(current[key],target[key],nextPath,operations)}else if(!isDeepStrictEqual(current[key],target[key])){operations.push({path:nextPath,value:target[key]})}}return operations}__name(collectOperations,"collectOperations");function findDuplicateProperty(node,path4=[]){if(node.type!=="object"||node.children===void 0){return void 0}const properties=new Map;for(const property of node.children){const keyNode=property.children?.[0];const key=keyNode?.value;if(typeof key!=="string"||keyNode===void 0){continue}const previous=properties.get(key);if(previous!==void 0){return{objectPath:[...path4],keyNode:previous,propertyNames:new Set(properties.keys())}}properties.set(key,keyNode)}for(const property of node.children){const key=property.children?.[0]?.value;const valueNode=property.children?.[1];if(typeof key!=="string"||valueNode===void 0){continue}const duplicate=findDuplicateProperty(valueNode,[...path4,key]);if(duplicate!==void 0){return duplicate}}return void 0}__name(findDuplicateProperty,"findDuplicateProperty");function normalizeDuplicateProperties(content,options){let normalized=content;let duplicateIndex=0;while(true){const root=parseTree2(normalized,[],PARSE_OPTIONS);if(root===void 0){return normalized}const duplicate=findDuplicateProperty(root);if(duplicate===void 0){return normalized}let temporaryKey;do{temporaryKey=`__qwen_duplicate_${duplicateIndex}`;duplicateIndex+=1}while(duplicate.propertyNames.has(temporaryKey));let renamed=normalized.slice(0,duplicate.keyNode.offset)+JSON.stringify(temporaryKey)+normalized.slice(duplicate.keyNode.offset+duplicate.keyNode.length);renamed=removeTrailingInlineComment(renamed,[...duplicate.objectPath,temporaryKey]);normalized=applyEdits(renamed,modify(renamed,[...duplicate.objectPath,temporaryKey],void 0,options))}}__name(normalizeDuplicateProperties,"normalizeDuplicateProperties");function removeTrailingInlineComment(content,path4){const root=parseTree2(content,[],PARSE_OPTIONS);if(root===void 0){return content}const node=findNodeAtLocation2(root,[...path4]);if(node===void 0){return content}const tail=content.slice(node.offset+node.length);const match=tail.match(/^[ \t]*(?:,[ \t]*)?(\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)/);const comment=match?.[1];if(comment===void 0||match===null){return content}const commentOffset=node.offset+node.length+match[0].indexOf(comment);return content.slice(0,commentOffset)+content.slice(commentOffset+comment.length)}__name(removeTrailingInlineComment,"removeTrailingInlineComment");function pathsEqual(left,right){return left.length===right.length&&left.every((segment,index)=>segment===right[index])}__name(pathsEqual,"pathsEqual");init_esbuild_shims();import*as fs3 from"node:fs";import*as path2 from"node:path";function isWorkflowAncestorDirectorySafe(directory){if(process.platform==="win32")return true;for(const location of[directory,path2.join(directory,".qwen"),path2.join(directory,".qwen","workflows")]){try{if((fs3.statSync(location).mode&2)!==0)return false}catch(error){const code=error.code;if(location===directory)return false;if(code==="ENOENT"||code==="ENOTDIR")break;return false}}return true}__name(isWorkflowAncestorDirectorySafe,"isWorkflowAncestorDirectorySafe");var debugLogger=createDebugLogger("TRUSTED_FOLDERS");var TRUSTED_FOLDERS_FILENAME="trustedFolders.json";function getTrustedFoldersPath(){if(process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]){return process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]}return path3.join(Storage.getGlobalQwenDir(),TRUSTED_FOLDERS_FILENAME)}__name(getTrustedFoldersPath,"getTrustedFoldersPath");var TrustLevel=(TrustLevel2=>{TrustLevel2["TRUST_FOLDER"]="TRUST_FOLDER";TrustLevel2["TRUST_PARENT"]="TRUST_PARENT";TrustLevel2["DO_NOT_TRUST"]="DO_NOT_TRUST";return TrustLevel2})(TrustLevel||{});var trustedFoldersChangeListeners=new Set;function onTrustedFoldersChanged(listener){trustedFoldersChangeListeners.add(listener);return()=>trustedFoldersChangeListeners.delete(listener)}__name(onTrustedFoldersChanged,"onTrustedFoldersChanged");function notifyTrustedFoldersChanged(){for(const listener of trustedFoldersChangeListeners)listener()}__name(notifyTrustedFoldersChanged,"notifyTrustedFoldersChanged");var LoadedTrustedFolders=class{constructor(user,errors){this.user=user;this.errors=errors}static{__name(this,"LoadedTrustedFolders")}get rules(){return Object.entries(this.user.config).map(([path4,trustLevel])=>({path:path4,trustLevel}))}isPathTrusted(location){return resolveTrustDecision(buildTrustPrecedenceRules(this.rules),getPathComparisonVariants(location))}setValue(path4,trustLevel,preserveExistingTrust=false){const committedConfig=writeTrustedFolders(this.user.path,diskConfig=>{const existing=diskConfig[path4];if(preserveExistingTrust&&(existing==="TRUST_FOLDER"||existing==="TRUST_PARENT")){return diskConfig}return{...diskConfig,[path4]:trustLevel}});this.user.config=committedConfig;notifyTrustedFoldersChanged()}};var loadedTrustedFolders;function resetTrustedFoldersForTesting(){loadedTrustedFolders=void 0}__name(resetTrustedFoldersForTesting,"resetTrustedFoldersForTesting");function loadTrustedFolders(){loadedTrustedFolders??=readTrustedFoldersFile(false);return loadedTrustedFolders}__name(loadTrustedFolders,"loadTrustedFolders");function loadTrustedFoldersFresh(){return readTrustedFoldersFile(true)}__name(loadTrustedFoldersFresh,"loadTrustedFoldersFresh");function readTrustedFoldersFile(validateRules){const errors=[];let userConfig={};const userPath=getTrustedFoldersPath();try{if(fs4.existsSync(userPath)){const content=fs4.readFileSync(userPath,"utf-8");const parsed=parseJsoncObject(content);if(validateRules)assertTrustedFoldersConfig(parsed);userConfig=parsed}}catch(error){errors.push({message:error instanceof Error&&error.message==="JSONC document root is not a JSON object."?"Trusted folders file is not a valid JSON object.":getErrorMessage(error),path:userPath})}return new LoadedTrustedFolders({path:userPath,config:userConfig},errors)}__name(readTrustedFoldersFile,"readTrustedFoldersFile");function createLocalWorkflowAncestorTrustProvider(settings){return async(ancestorDirs,canonicalTargetDir)=>{if(!isFolderTrustEnabled(settings)){return ancestorDirs.map(isWorkflowAncestorDirectorySafe)}if(ideContextStore.get()?.workspaceState?.isTrusted===false){return ancestorDirs.map(()=>false)}const folders=loadTrustedFoldersFresh();if(folders.errors.length>0){debugLogger.warn("Workflow ancestor trust denied: invalid trusted folders snapshot:",folders.errors.map(error=>`${error.path}: ${error.message}`).join("; "));return ancestorDirs.map(()=>false)}if(folders.isPathTrusted(canonicalTargetDir)!==true){return ancestorDirs.map(()=>false)}return ancestorDirs.map(directory=>folders.isPathTrusted(directory)===true)}}__name(createLocalWorkflowAncestorTrustProvider,"createLocalWorkflowAncestorTrustProvider");function saveTrustedFolders(trustedFoldersFile){writeTrustedFolders(trustedFoldersFile.path,()=>({...trustedFoldersFile.config}))}__name(saveTrustedFolders,"saveTrustedFolders");function assertTrustedFoldersConfig(config){for(const[rulePath,trustLevel]of Object.entries(config)){if(!Object.values(TrustLevel).includes(trustLevel)){throw new FatalConfigError(`Invalid trusted folder rule for ${JSON.stringify(rulePath)}.`)}}}__name(assertTrustedFoldersConfig,"assertTrustedFoldersConfig");function writeTrustedFolders(filePath,update){const dirPath=path3.dirname(filePath);if(!fs4.existsSync(dirPath)){fs4.mkdirSync(dirPath,{recursive:true})}const release=import_proper_lockfile.default.lockSync(filePath,{realpath:false,stale:1e4,onCompromised:__name(err=>{debugLogger.warn("trusted folders lock compromised:",err)},"onCompromised")});try{let originalContent="{}";if(fs4.existsSync(filePath)){const stat=fs4.lstatSync(filePath);if(stat.isSymbolicLink()||!stat.isFile()){throw new FatalConfigError("Trusted folders path must be a regular file.")}originalContent=fs4.readFileSync(filePath,"utf-8")}let parsed;try{parsed=parseJsoncObject(originalContent)}catch(error){if(error instanceof Error&&error.message==="JSONC document root is not a JSON object."){throw new FatalConfigError("Trusted folders file is not a valid JSON object.")}throw error}const diskConfig=Object.fromEntries(Object.entries(parsed));assertTrustedFoldersConfig(diskConfig);const nextConfig=update({...diskConfig});assertTrustedFoldersConfig(nextConfig);const content=updateJsoncContent(originalContent,nextConfig,true);atomicWriteFileSync(filePath,content,{encoding:"utf-8",mode:384,forceMode:true,noFollow:true});return nextConfig}finally{try{release()}catch{}}}__name(writeTrustedFolders,"writeTrustedFolders");function isFolderTrustEnabled(settings){const folderTrustSetting=settings.security?.folderTrust?.enabled??false;return folderTrustSetting}__name(isFolderTrustEnabled,"isFolderTrustEnabled");function getExplicitTrustLevel(trustConfig,workspaceCwd){const winner=resolveTrustRule(buildTrustPrecedenceRules(Object.entries(trustConfig).map(([rulePath,trustLevel])=>({path:rulePath,trustLevel}))),getPathComparisonVariants(workspaceCwd));return winner?.payload??null}__name(getExplicitTrustLevel,"getExplicitTrustLevel");function loadTrustedFoldersWithOverrides(trustConfig){const folders=loadTrustedFolders();if(folders.errors.length>0){const errorMessages=folders.errors.map(error=>`Error in ${error.path}: ${error.message}`);throw new FatalConfigError(`${errorMessages.join("\n")}
|
|
4
4
|
Please fix the configuration file and try again.`)}if(trustConfig){return new LoadedTrustedFolders({...folders.user,config:trustConfig},folders.errors)}return folders}__name(loadTrustedFoldersWithOverrides,"loadTrustedFoldersWithOverrides");function trustStatusToResult(status){if(status.effective.source==="disabled"){return{isTrusted:true,source:void 0}}return{isTrusted:status.effective.state==="trusted"?true:status.effective.state==="untrusted"?false:void 0,source:status.effective.source==="file"||status.effective.source==="ide"?status.effective.source:void 0}}__name(trustStatusToResult,"trustStatusToResult");function getWorkspaceTrustStatus(settings,workspaceCwd,trustConfig){if(!isFolderTrustEnabled(settings)){return{v:1,workspaceCwd,folderTrustEnabled:false,effective:{state:"trusted",source:"disabled"},explicitTrustLevel:null,requiresDaemonRestartForChanges:true}}const ideTrust=ideContextStore.get()?.workspaceState?.isTrusted;if(ideTrust!==void 0&&arePathsEquivalent(workspaceCwd,process.cwd())){return{v:1,workspaceCwd,folderTrustEnabled:true,effective:{state:ideTrust?"trusted":"untrusted",source:"ide"},explicitTrustLevel:null,requiresDaemonRestartForChanges:true}}const folders=loadTrustedFoldersWithOverrides(trustConfig);const isTrusted=folders.isPathTrusted(workspaceCwd);const state=isTrusted===true?"trusted":isTrusted===false?"untrusted":"unknown";return{v:1,workspaceCwd,folderTrustEnabled:true,effective:{state,source:isTrusted===void 0?"none":"file"},explicitTrustLevel:getExplicitTrustLevel(folders.user.config,workspaceCwd),requiresDaemonRestartForChanges:true}}__name(getWorkspaceTrustStatus,"getWorkspaceTrustStatus");function isWorkspaceTrusted(settings,trustConfig,workspacePath){if(!isFolderTrustEnabled(settings)){return{isTrusted:true,source:void 0}}const ideTrust=ideContextStore.get()?.workspaceState?.isTrusted;if(ideTrust!==void 0&&(workspacePath===void 0||arePathsEquivalent(workspacePath,process.cwd()))){return{isTrusted:ideTrust,source:"ide"}}return trustStatusToResult(getWorkspaceTrustStatus(settings,workspacePath??process.cwd(),trustConfig))}__name(isWorkspaceTrusted,"isWorkspaceTrusted");export{writeWithBackupSync,updateSettingsFilePreservingFormat,parseJsoncObject,isWorkflowAncestorDirectorySafe,TRUSTED_FOLDERS_FILENAME,getTrustedFoldersPath,TrustLevel,onTrustedFoldersChanged,LoadedTrustedFolders,resetTrustedFoldersForTesting,loadTrustedFolders,loadTrustedFoldersFresh,createLocalWorkflowAncestorTrustProvider,saveTrustedFolders,isFolderTrustEnabled,getExplicitTrustLevel,getWorkspaceTrustStatus,isWorkspaceTrusted};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{HEADLESS_YOLO_NO_SANDBOX_WARNING}from"./chunk-Z57KDB5F.js";import{DEFAULT_RING_SIZE}from"./chunk-BWQ5AIEA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,JOURNAL_GROWTH_HARD_CAP_BYTES}from"./chunk-WDR5XP3Y.js";import{JOURNAL_GROWTH_POOL_FRACTION,MAX_JOURNAL_GROWTH_POOL_MB,MIN_MEMORY_BUDGET_MB,isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{EXTERNAL_TOOL_GUARD_TOKEN_ENV}from"./chunk-NIEO2TBE.js";import{loadSettings}from"./chunk-
|
|
4
|
-
${status.interfaceName}: ${status.url}`);qrcode.generate(status.url,{small:true},code=>{writeStdoutLine(code.trimEnd())});writeStdoutLine("\nKeep this terminal open. "+(status.sleepInhibited?"Sleep is inhibited while this session is active. ":"Sleep inhibition is unavailable here, so the host may sleep. ")+(status.encrypted?"Traffic is encrypted.":"Traffic is unencrypted \u2014 use it only on a network you trust.")+" Turn Local Control off from the Web Shell Settings card, or press Ctrl+C to exit the daemon.")}__name(startLocalControl,"startLocalControl");async function maybeOpenWebShellBrowser(handle,open,manualFallbackWhenIneligible=false){if(!open||!handle.webShellMounted)return;const shouldLaunch=shouldLaunchBrowser();if(!shouldLaunch&&!manualFallbackWhenIneligible)return;try{await handle.runtimeReady}catch(runtimeErr){writeStderrLine(`qwen serve: Web Shell runtime not ready; skipping --open: ${runtimeErr instanceof Error?runtimeErr.message:String(runtimeErr)}`);return}let target;try{target=new URL(handle.url);if(target.hostname==="0.0.0.0"||target.hostname==="[::]"){target.hostname="127.0.0.1"}if(handle.resolvedToken){target.hash=`token=${encodeURIComponent(handle.resolvedToken)}`}if(!shouldLaunch){writeStderrLine(`Browser launch is not available in this environment. Please open this URL manually: ${target.toString()}`);return}if(handle.resolvedToken){writeStderrLine("qwen serve: --open passes the token in the browser launch command (visible via `ps` / /proc); on a multi-user host open the URL manually instead.")}await openBrowserSecurely(target.toString())}catch(browserErr){const manualUrl=manualFallbackWhenIneligible&&target?`. Please open this URL manually: ${target.toString()}`:"";writeStderrLine(`qwen serve: failed to open browser: ${browserErr instanceof Error?browserErr.message:String(browserErr)}${manualUrl}`)}}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function primaryWorkspaceArg(workspace){return Array.isArray(workspace)?workspace[0]:workspace}__name(primaryWorkspaceArg,"primaryWorkspaceArg");var serveCommand={command:"serve",describe:"Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:__name(yargs=>yargs.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:DEFAULT_SERVE_HOSTNAME,description:"Interface to bind. Loopback (127.0.0.0/8, localhost, ::1, [::1]) is auth-free; anything else requires a token (one is generated and printed when neither --token nor QWEN_SERVER_TOKEN supplies one). A localhost bind that resolves off-loopback never generates, and still refuses when no token source resolved; an empty value is rejected as operator error."}).option("profile",{choices:["default","hosted-harness"],default:"default",description:"Deployment profile. hosted-harness enables the private no-tool Managed Session API on loopback."}).option("hosted-harness-capability-digest",{type:"string",description:"SHA-256 capability digest for the private Hosted Harness profile. Falls back to QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST."}).option("managed",{type:"boolean",default:false,description:"Start the daemon and Managed Agent with shared WebShell and embedded storage; downloads the server on first use and requires Java 21."}).option("managed-data-dir",{type:"string",requiresArg:true,description:"Private persistent data directory for --managed; defaults to <Qwen home>/managed-local."}).option("managed-web-config",{type:"string",requiresArg:true,description:"Run only the authenticated Managed Web gateway using a JSON file with apiUrl, tenantId, actorId and signingKeyFile. Requires an independent browser token of at least 32 bytes via QWEN_SERVER_TOKEN or --token."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the QWEN_SERVER_TOKEN env var; a non-loopback bind with neither generates an ephemeral token at startup, while loopback keeps the trusted tokenless mode unless --require-auth is set."}).option("max-sessions",{type:"number",description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable. Defaults to 32, or to the serve.maxSessions setting (user, system, and system-defaults scopes only); the flag wins when passed."}).option("max-total-sessions",{type:"number",description:"Non-negative integer cap on concurrent live sessions across all workspace runtimes. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",array:true,requiresArg:true,description:"Absolute workspace path to register with this daemon. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. Repeat to register isolated workspace runtimes; the first is primary."}).option("memory-project-scope",{type:"string",choices:MEMORY_PROJECT_SCOPES,description:'Choose how project memory is partitioned. Defaults to "workspace" so each daemon workspace stays isolated; "git-root" preserves the legacy shared scope. Overrides QWEN_CODE_MEMORY_PROJECT_SCOPE when provided.'}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:false,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token, QWEN_SERVER_TOKEN, or --open-with-auth (which installs its own generated loopback token); on non-loopback binds the generated ephemeral token also satisfies it, so the no-configured-secret fail-fast is loopback-only. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:false,description:"Enable direct POST /session/:id/shell execution. Available with bearer auth or trusted loopback; each call still requires a session-bound client id."}).option("tls-cert",{type:"string",description:"Path to a PEM certificate file. Serve over HTTPS instead of HTTP. Required for secure-context browser APIs (voice input/getUserMedia, WebRTC) when accessed over a LAN IP. Must be used together with --tls-key. Generate a local cert with mkcert."}).option("tls-key",{type:"string",description:"Path to a PEM private key file. Must be used together with --tls-cert."}).option("experimental-lsp",{type:"boolean",default:false,description:"Forward the experimental LSP opt-in to spawned agent sessions."}).option("restore-ask-user-question",{type:"boolean",default:false,description:"On session load/resume, re-hang a trailing unanswered ask_user_question instead of synthesizing a failed tool result."}).option("channel",{type:"string",array:true,description:"Experimental: start a daemon-managed channel worker for the named channel. Repeat to select multiple channels, or use --channel all."}).option("web",{type:"boolean",default:true,description:"Serve the Web Shell UI at the daemon root path. Use --no-web for an API-only daemon."}).option("open",{type:"boolean",default:false,description:"Open the Web Shell in a browser once the daemon is listening. With a token configured, the launch URL (token included) is handed to the browser launcher and is visible in the process list, so prefer opening the URL manually on multi-user hosts. No-op with --no-web, when the UI assets are absent, or in headless/CI/SSH environments."}).option("open-with-auth",{type:"boolean",default:false,description:"Open the Web Shell with bearer authentication on loopback. Reuse --token or QWEN_SERVER_TOKEN, or generate a temporary 256-bit token and deliver it in the URL fragment. In headless environments, print the fragment URL for manual opening."}).option("token-qr",{type:"boolean",description:"Print the token-bearing QR even when stdout is captured (not an interactive terminal) and the bearer is an operator-supplied (stable) token, which is withheld by default to keep stable credentials out of collected logs. Enable only when the log pipeline is as trusted as the daemon host. Can also be set via the serve.tokenQr setting (user, system, and system-defaults scopes only); the flag wins when passed. --no-token-qr suppresses the startup quickstart token QR for that run on every quickstart path \u2014 interactive terminal and generated token included. It does not govern the Local Control pairing QR, which --local-control prints by design."}).option("local-control",{type:"boolean",default:false,description:"Share the Web Shell on the local IPv4 network with its own revocable pairing token, terminal QR code, and best-effort sleep inhibition. Ctrl+C turns it off by ending the whole daemon; the Web Shell Settings card turns it off while the daemon keeps running."}).option("local-control-address",{type:"string",description:"Which local IPv4 address to share when the host is on more than one network. Only needed if --local-control reports an ambiguous choice."}).option("join",{type:"string",description:"Join another Qwen Code as a runtime, with the one-line link it shows under Agent \u2192 Runtime \u2192 Add runtime."}).option("agent-host-server",{type:"string",description:"Register this daemon as an Agent Host with a primary Qwen daemon."}).option("agent-host-workspace-id",{type:"string",description:"Control-plane workspace id printed by the primary daemon."}).option("agent-host-name",{type:"string",description:"Display name advertised for this Agent Host."}).option("agent-host-allow-http",{type:"boolean",default:false,description:"Allow unencrypted Agent Host HTTP connections outside loopback (trusted demo networks only)."}).check(argv=>{if(argv["local-control"]===true&&argv["web"]===false){throw new Error("Local Control requires the Web Shell.")}if(argv["local-control"]===true&&argv.hostname!==DEFAULT_SERVE_HOSTNAME){throw new Error(`Local Control requires --hostname ${DEFAULT_SERVE_HOSTNAME}.`)}if(argv["local-control"]!==true&&argv["local-control-address"]!==void 0){throw new Error("--local-control-address requires --local-control.")}if(argv["local-control-address"]===""){throw new Error("--local-control-address must not be empty.")}if(Boolean(argv["agent-host-server"])!==Boolean(argv["agent-host-workspace-id"])){throw new Error("--agent-host-server and --agent-host-workspace-id must be used together.")}if(argv["agent-host-name"]===""){throw new Error("--agent-host-name must not be empty.")}if(argv["join"]!==void 0){if(argv["agent-host-server"]||argv["agent-host-workspace-id"]){throw new Error("--join already names the coordinator and workspace; drop --agent-host-server and --agent-host-workspace-id.")}parseJoinLink(argv["join"])}return true}).option("event-ring-size",{type:"number",default:DEFAULT_RING_SIZE,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("compacted-replay-max-bytes",{type:"number",default:DEFAULT_COMPACTED_REPLAY_MAX_BYTES,description:"Per-session in-memory compacted replay snapshot byte cap for `POST /session/:id/load` late attaches. Larger = more recent history in load snapshots at higher heap cost. Must be a positive safe integer no larger than 256 MiB."}).option("max-journal-events",{type:"number",nargs:1,description:"Per-session baseline cap on replay entries retained in the in-flight live journal (current unfinished turn). Compatible text/thought chunks share bounded entries. When exceeded, the daemon first tries adaptive growth (see --max-journal-bytes); without granted headroom the oldest entries are dropped. Pinning this flag (or --max-journal-bytes) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_EVENTS+" when unset. Must be a positive safe integer."}).option("max-journal-bytes",{type:"number",nargs:1,description:"Per-session baseline source-event byte cap on the in-flight live journal. When a turn outgrows it, adaptive growth raises the session's caps (per-session hard cap "+JOURNAL_GROWTH_HARD_CAP_BYTES/(1024*1024)+" MiB) within a growth pool derived from the daemon memory budget (see --memory-budget-mb); without granted headroom the oldest entries are dropped whole (at least one is always kept), so the retained tail can be much smaller than the cap. Pinning this flag (or --max-journal-events) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_BYTES+" bytes when unset. Must be a positive safe integer."}).option("http-bridge",{type:"boolean",default:true,description:"HTTP bridge mode: attempt to preheat the primary `qwen --acp` child; trusted secondaries start one on demand. Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("memory-budget-mb",{type:"number",description:"Total memory budget in MB for the daemon process tree. When unset, derived as 50% of cgroup-constrained or host memory, and capped at the resolved available memory either way. In `admit` and `enforce` modes it determines managed ACP child capacity; `enforce` also applies the modeled per-child old-space ceiling. It also sizes one daemon-wide pool of "+JOURNAL_GROWTH_POOL_FRACTION*100+"% of the effective budget (capped at "+MAX_JOURNAL_GROWTH_POOL_MB+" MB; 0, growth disabled, when the effective budget falls below the "+MIN_MEMORY_BUDGET_MB+" MB minimum; see --max-journal-bytes). Reported under `limits.memory` in daemon status, alongside a modeled per-child partition under `limits.memory.childHeap`. Must be an integer in [1024, 1048576]."}).option("memory-pressure-mode",{choices:["off","observe"],default:"observe",description:"Whether the daemon derives a memory-pressure level from its own RSS and V8 heap. `observe` (default) reports the level in daemon status and raises a status issue when it leaves normal. `off` still reports the underlying figures but raises no issue, so the overall status rollup is unchanged \u2014 use it while calibrating, or if you alert on the top-level status. Nothing remediates in either mode."}).option("child-heap-mode",{choices:["off","observe","admit","enforce"],default:"observe",description:"Whether the daemon models a per-child heap partition of the memory budget. `observe` (default) reports the partition it would apply \u2014 `limits.memory.childHeap.perChildCeilingMb` and `maxConcurrentChildren` \u2014 and counts spawns that would have exceeded it. Nothing is applied: no child is sized from the budget and no spawn is refused. `off` models nothing. Note a refusal count of 0 does NOT mean the partition would be safe to apply; children still run on the much larger host-derived ceiling, so a workload needing more old space than the modeled ceiling looks healthy here. `admit` rejects starts past the modeled process limit but keeps the existing child heap arguments. Experimental `enforce` also applies the fixed modeled old-space ceiling to each managed child; it does not cap total process RSS."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:true,description:"Cross-origin allowlist for browser clients. Accepts `*`, a canonical origin, or a loopback port wildcard like `http://127.0.0.1:*` (requires a bearer token)."}).option("allow-private-auth-base-url",{type:"boolean",default:false,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to QWEN_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("experimental-paired-engines",{type:"boolean",default:false,description:"Experimental: build workspace runtimes, other than the private Conversations one, with paired Legacy and Managed engines. No Managed engine is available yet, so sessions run on Legacy with a durable owner."}).option("experimental-managed-agents",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-worker",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-auto-local",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-url",{type:"string",requiresArg:true,description:"Reserved experimental Runtime URL; not implemented and rejects startup."}).option("experimental-managed-runtime-token",{type:"string",requiresArg:true,description:"Reserved experimental Runtime credential; not implemented and rejects startup."}).option("managed-runtime-broker-url",{type:"string",requiresArg:true,description:"Private Broker URL for --profile hosted-harness; required together with token for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_URL."}).option("managed-runtime-broker-token",{type:"string",requiresArg:true,description:"Private Broker credential for --profile hosted-harness; required together with URL for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_TOKEN; prefer the variable, since this option puts the credential in the process list."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Compatibility auto-reap delay for an idle workspace ACP child. 0 or unset = reap after work drains; keepalive windows may extend it (default)."}).option("initialize-timeout-ms",{type:"number",description:"ACP child request timeout, including the initialize handshake (ms). Default: 10000 (10 s)."}).option("session-restore-timeout-ms",{type:"number",description:"ACP session load/resume timeout (ms). Default: 60000. An explicit --initialize-timeout-ms can raise (but never lower) this default."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("session-prompt-settled-close-grace-ms",{type:"number",description:"Grace period after a prompt settles before an otherwise-idle session may be auto-closed (ms). Poll-based SSE clients use this window to reconnect without triggering a session rebuild. 0 = disabled (immediate close). Default: 0."}).option("permission-response-timeout-ms",{type:"number",description:"Wall-clock timeout for a human permission / ask_user_question response in daemon (ACP) mode (ms). 0 or unset = disabled (wait indefinitely). Default: 0."}).option("external-tool-guard-mode",{choices:["off","required"],default:"off",description:"Managed ACP pre-execution policy mode. Default off preserves current CLI and daemon behavior. Required fails startup unless a compatible loopback provider is available."}).option("external-tool-guard-endpoint",{type:"string",description:"Origin-only loopback HTTP(S) endpoint for required external tool guarding, for example http://127.0.0.1:8787."}).option("external-tool-guard-timeout-ms",{type:"number",description:"Per-handshake/prepare external tool guard timeout in milliseconds. Default: 3000."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),"builder"),handler:__name(async argv=>{if(argv["managed-web-config"]!==void 0){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedWebFlags(process.argv.slice(serveIndex+1));if(argv.managed||argv.profile!=="default"||!argv.web||argv.workspace!==void 0){throw new Error("--managed-web-config cannot be combined with daemon execution or Managed local mode.")}const{runManagedWebServe}=await import("./managed-web-serve-JPJBFJMR.js");const handle=await runManagedWebServe({configFile:argv["managed-web-config"],hostname:argv.hostname,port:argv.port,token:argv.token,allowOrigins:argv["allow-origin"]});writeStdoutLine(`Managed WebShell: ${handle.url}`);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv.managed){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedLocalFlags(process.argv.slice(serveIndex+1));if(argv.hostname!==DEFAULT_SERVE_HOSTNAME||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv.token!==void 0||argv["tls-cert"]||argv["tls-key"]||argv["local-control"]||argv.join||argv["agent-host-server"]||argv.channel!==void 0||argv["experimental-paired-engines"]||argv["experimental-managed-agents"]||argv["experimental-managed-runtime-worker"]||argv["experimental-managed-runtime-auto-local"]||argv["experimental-managed-runtime-url"]!==void 0||argv["managed-runtime-broker-url"]!==void 0||argv["managed-runtime-broker-token"]!==void 0||argv["allow-origin"]?.length||argv["enable-session-shell"]||!argv["http-bridge"]){throw new Error("--managed uses its own loopback services, persistent credentials, and application-owned Workspaces. Use --port, --managed-data-dir, and --open; other deployment, workspace-import, or execution modes cannot be combined.")}const{runManagedLocalServe}=await import("./managed-local-serve-ICNAS3E6.js");const handle=await runManagedLocalServe({port:argv.port,dataDirectory:argv["managed-data-dir"]});await maybeOpenWebShellBrowser(handle,argv.open||argv["open-with-auth"],argv["open-with-auth"]);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv["managed-data-dir"]!==void 0){writeStderrLine("qwen serve: --managed-data-dir requires --managed.");process.exit(1)}const managedRuntimeBrokerUrl=argv["managed-runtime-broker-url"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];const managedRuntimeBrokerToken=argv["managed-runtime-broker-token"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];const agentHostEnrollmentToken=process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"]?.trim();delete process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"];if(!argv["http-bridge"]){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(argv.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}if(argv["managed-runtime-broker-token"]!==void 0){writeStderrLine("qwen serve: --managed-runtime-broker-token is visible in the process command line; prefer the QWEN_MANAGED_RUNTIME_BROKER_TOKEN env var.")}let channelSelection;try{channelSelection=normalizeServeChannelSelection(argv.channel)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}const mcpClientBudget=argv["mcp-client-budget"];const mcpBudgetMode=argv["mcp-budget-mode"];if(mcpClientBudget!==void 0){if(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0){writeStderrLine("qwen serve: --mcp-client-budget must be a positive integer.");process.exit(1)}}if(mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){writeStderrLine("qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N.");process.exit(1)}const resolvedMcpMode=mcpBudgetMode??(mcpClientBudget!==void 0?"warn":"off");const memoryBudgetMb=argv["memory-budget-mb"];if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){writeStderrLine(memoryBudgetRangeError());process.exit(1)}const maxPendingPromptsPerSession=argv["max-pending-prompts-per-session"];if(maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){writeStderrLine("qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited).");process.exit(1)}if(mcpClientBudget!==void 0){writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}try{const loaded=loadSettings(primaryWorkspaceArg(argv.workspace)??process.cwd());const merged=loaded.merged;const approvalMode=merged.tools?.approvalMode;const sandbox=merged.tools?.sandbox;const sandboxEnv=process.env["SANDBOX"];const suppress=process.env["QWEN_CODE_SUPPRESS_YOLO_WARNING"];const suppressed=suppress==="1"||suppress==="true";if(approvalMode==="yolo"&&!sandbox&&!sandboxEnv&&!suppressed){writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING)}}catch{}const rateLimit=argv["rate-limit"]??(process.env["QWEN_SERVE_RATE_LIMIT"]==="1"||process.env["QWEN_SERVE_RATE_LIMIT"]==="true");let rateLimitPrompt;let rateLimitMutation;let rateLimitRead;let rateLimitWindowMs;if(rateLimit){const envInt=__name(key=>{const raw=process.env[key];if(raw===void 0||raw==="")return void 0;return parsePositiveIntegerEnv(raw,Number.NaN)},"envInt");rateLimitPrompt=argv["rate-limit-prompt"]??envInt("QWEN_SERVE_RATE_LIMIT_PROMPT");rateLimitMutation=argv["rate-limit-mutation"]??envInt("QWEN_SERVE_RATE_LIMIT_MUTATION");rateLimitRead=argv["rate-limit-read"]??envInt("QWEN_SERVE_RATE_LIMIT_READ");rateLimitWindowMs=argv["rate-limit-window-ms"]??envInt("QWEN_SERVE_RATE_LIMIT_WINDOW_MS");for(const[name,value]of[["--rate-limit-prompt",rateLimitPrompt],["--rate-limit-mutation",rateLimitMutation],["--rate-limit-read",rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){writeStderrLine(`qwen serve: ${name} must be a positive integer.`);process.exit(1)}}if(rateLimitWindowMs!==void 0&&(!Number.isFinite(rateLimitWindowMs)||!Number.isInteger(rateLimitWindowMs)||rateLimitWindowMs<1e3)){writeStderrLine("qwen serve: --rate-limit-window-ms must be an integer >= 1000.");process.exit(1)}}const externalToolGuardToken=process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]??"";delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const openWithAuth=argv["open-with-auth"];const open=argv.open||openWithAuth;const{runQwenServe}=await import("./run-qwen-serve-NZWQHWQA.js");try{const serveOptions={port:argv.port,hostname:argv.hostname,profile:argv.profile,token:argv.token,mode:"http-bridge",maxSessions:argv["max-sessions"],...argv["max-total-sessions"]!==void 0?{maxTotalSessions:argv["max-total-sessions"]}:{},maxPendingPromptsPerSession,maxConnections:argv["max-connections"],eventRingSize:argv["event-ring-size"],compactedReplayMaxBytes:argv["compacted-replay-max-bytes"],...argv["max-journal-events"]!==void 0?{maxJournalEvents:argv["max-journal-events"]}:{},...argv["max-journal-bytes"]!==void 0?{maxJournalBytes:argv["max-journal-bytes"]}:{},workspace:argv.workspace,...argv["memory-project-scope"]!==void 0?{memoryProjectScope:argv["memory-project-scope"]}:{},requireAuth:argv["require-auth"],enableSessionShell:argv["enable-session-shell"],serveWebShell:argv.web,...argv["token-qr"]!==void 0?{tokenQr:argv["token-qr"]}:{},...argv["tls-cert"]!==void 0?{tlsCert:argv["tls-cert"]}:{},...argv["tls-key"]!==void 0?{tlsKey:argv["tls-key"]}:{},allowPrivateAuthBaseUrl:argv["allow-private-auth-base-url"],mcpClientBudget,mcpBudgetMode:resolvedMcpMode,...memoryBudgetMb!==void 0?{memoryBudgetMb}:{},memoryPressureMode:argv["memory-pressure-mode"],childHeapMode:argv["child-heap-mode"],...argv["allow-origin"]&&argv["allow-origin"].length>0?{allowOrigins:argv["allow-origin"]}:{},...argv["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:argv["prompt-deadline-ms"]}:{},...argv["experimental-paired-engines"]?{experimentalPairedEngines:true}:{},...argv["experimental-managed-agents"]?{experimentalManagedAgents:true}:{},...argv["experimental-managed-runtime-auto-local"]?{experimentalManagedRuntimeAutoLocal:true}:{},...argv["experimental-managed-runtime-worker"]?{experimentalManagedRuntimeWorker:true}:{},...argv["experimental-managed-runtime-url"]!==void 0?{experimentalManagedRuntimeUrl:argv["experimental-managed-runtime-url"]}:{},...argv["experimental-managed-runtime-token"]!==void 0?{experimentalManagedRuntimeToken:argv["experimental-managed-runtime-token"]}:{},...managedRuntimeBrokerUrl!==void 0?{managedRuntimeBrokerUrl}:{},...managedRuntimeBrokerToken!==void 0?{managedRuntimeBrokerToken}:{},...argv["hosted-harness-capability-digest"]!==void 0?{hostedHarnessCapabilityDigest:argv["hosted-harness-capability-digest"]}:{},...argv["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:argv["writer-idle-timeout-ms"]}:{},...argv["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:argv["channel-idle-timeout-ms"]}:{},...argv["initialize-timeout-ms"]!==void 0?{initializeTimeoutMs:argv["initialize-timeout-ms"]}:{},...argv["session-restore-timeout-ms"]!==void 0?{sessionRestoreTimeoutMs:argv["session-restore-timeout-ms"]}:{},...argv["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:argv["session-reap-interval-ms"]}:{},...argv["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:argv["session-idle-timeout-ms"]}:{},...argv["session-prompt-settled-close-grace-ms"]!==void 0?{sessionPromptSettledCloseGraceMs:argv["session-prompt-settled-close-grace-ms"]}:{},...argv["permission-response-timeout-ms"]!==void 0?{permissionResponseTimeoutMs:argv["permission-response-timeout-ms"]}:{},...argv["external-tool-guard-mode"]==="required"?{externalToolGuard:{mode:"required",endpoint:argv["external-tool-guard-endpoint"]??"",token:externalToolGuardToken,...argv["external-tool-guard-timeout-ms"]!==void 0?{timeoutMs:argv["external-tool-guard-timeout-ms"]}:{}}}:{},...rateLimit?{rateLimit:true}:{},...rateLimitPrompt!==void 0?{rateLimitPrompt}:{},...rateLimitMutation!==void 0?{rateLimitMutation}:{},...rateLimitRead!==void 0?{rateLimitRead}:{},...rateLimitWindowMs!==void 0?{rateLimitWindowMs}:{},...argv.experimentalLsp===true?{experimentalLsp:true}:{},...argv.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},...channelSelection!==void 0?{channelSelection}:{}};if(openWithAuth){const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(serveOptions)}const handle=await runQwenServe(serveOptions,{updateRestartArgv:process.argv.slice(2)});const joined=argv["join"]?parseJoinLink(argv["join"]):void 0;const hostTarget=joined?{...joined,token:agentHostEnrollmentToken}:argv["agent-host-server"]&&argv["agent-host-workspace-id"]?{serverUrl:argv["agent-host-server"],workspaceId:argv["agent-host-workspace-id"],token:agentHostEnrollmentToken}:void 0;if(hostTarget){try{await handle.runtimeReady;const runtime=handle.getPrimaryWorkspaceRuntime();if(!runtime?.trusted||!runtime.generationGuard||runtime.generationGuard.closed){throw new Error("Agent Host join requires a trusted active workspace.")}const{startAgentHostConnection}=await import("./agent-host-client-L5EHC4AC.js");await startAgentHostConnection({bridge:runtime.bridge,serverUrl:hostTarget.serverUrl,workspaceId:hostTarget.workspaceId,workspaceCwd:runtime.workspaceCwd,allowHttp:argv["agent-host-allow-http"]===true,generationGuard:runtime.generationGuard,...hostTarget.token?{enrollmentToken:hostTarget.token}:{},...argv["agent-host-name"]?{name:argv["agent-host-name"]}:{}})}catch(error){await handle.close().catch(()=>void 0);throw error}}if(argv["local-control"]){try{await startLocalControl(handle,argv["local-control-address"])}catch(err){await handle.close().catch(()=>void 0);throw err}}await maybeOpenWebShellBrowser(handle,open,openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await blockForever()},"handler")};export{parseJoinLink,validateManagedLocalFlags,validateManagedWebFlags,maybeOpenWebShellBrowser,serveCommand};
|
|
3
|
+
import{HEADLESS_YOLO_NO_SANDBOX_WARNING}from"./chunk-Z57KDB5F.js";import{DEFAULT_RING_SIZE}from"./chunk-BWQ5AIEA.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,JOURNAL_GROWTH_HARD_CAP_BYTES}from"./chunk-WDR5XP3Y.js";import{JOURNAL_GROWTH_POOL_FRACTION,MAX_JOURNAL_GROWTH_POOL_MB,MIN_MEMORY_BUDGET_MB,isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{EXTERNAL_TOOL_GUARD_TOKEN_ENV}from"./chunk-NIEO2TBE.js";import{loadSettings}from"./chunk-Q5RRVBTY.js";import{MCP_BUDGET_WARN_FRACTION}from"./chunk-T3CQ72HC.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{openBrowserSecurely,shouldLaunchBrowser}from"./chunk-3YWXKSOI.js";import{MEMORY_PROJECT_SCOPES}from"./chunk-PWOQASXT.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var SEGMENT=/^[A-Za-z0-9_-]{1,256}$/;function parseJoinLink(link){let url;try{url=new URL(link.trim())}catch{throw new Error("--join expects the link shown by the coordinator.")}const marker=url.pathname.lastIndexOf("/join/");const[workspaceId,...rest]=marker>=0?url.pathname.slice(marker+"/join/".length).split("/"):[];if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.search||url.hash||!workspaceId||rest.some(Boolean)||!SEGMENT.test(workspaceId)){throw new Error("--join expects a link like https://host:4170/join/<workspace>.")}const base=url.pathname.slice(0,marker).replace(/\/+$/,"");return{serverUrl:`${url.origin}${base}`,workspaceId}}__name(parseJoinLink,"parseJoinLink");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");var DEFAULT_SERVE_HOSTNAME="127.0.0.1";function validateManagedLocalFlags(args){const supported=new Set(["--managed","--managed-data-dir","--port","--hostname","--open","--no-open","--open-with-auth","--no-open-with-auth","--web","--require-auth","--http-bridge"]);const unsupported=args.find(arg=>arg.startsWith("--")&&!supported.has(arg.split("=")[0]));if(unsupported){throw new Error(`${unsupported.split("=")[0]} is not supported with --managed. Use --port, --managed-data-dir, and --open.`)}}__name(validateManagedLocalFlags,"validateManagedLocalFlags");function validateManagedWebFlags(args){const supported=new Set(["--managed-web-config","--hostname","--port","--allow-origin","--token","--require-auth"]);const unsupported=args.find(arg=>arg.startsWith("--")&&!supported.has(arg.split("=")[0]));if(unsupported){throw new Error(`${unsupported.split("=")[0]} is not supported with --managed-web-config. Only hostname, port, allow-origin and browser authentication options are supported.`)}}__name(validateManagedWebFlags,"validateManagedWebFlags");async function startLocalControl(handle,address){await handle.runtimeReady;if(!handle.webShellMounted){throw new Error("Local Control requires the Web Shell.")}const service=handle.getLocalControl();if(!service){throw new Error("Local Control is unavailable on this daemon.")}let status;try{status=await service.enable(address?{address}:{})}catch(err){if(err instanceof Error&&err.code==="ambiguous_lan_interface"){throw new Error(`${err.message}. Pass --local-control-address <ip>.`)}throw err}if(!status.url){throw new Error("Local Control did not return a pairing URL.")}const{default:qrcode}=await import("./main-5IVKRF6Q.js");qrcode.setErrorLevel("Q");writeStdoutLine("\nLocal Control is on. Scan this QR code from the same network:");writeStdoutLine(`
|
|
4
|
+
${status.interfaceName}: ${status.url}`);qrcode.generate(status.url,{small:true},code=>{writeStdoutLine(code.trimEnd())});writeStdoutLine("\nKeep this terminal open. "+(status.sleepInhibited?"Sleep is inhibited while this session is active. ":"Sleep inhibition is unavailable here, so the host may sleep. ")+(status.encrypted?"Traffic is encrypted.":"Traffic is unencrypted \u2014 use it only on a network you trust.")+" Turn Local Control off from the Web Shell Settings card, or press Ctrl+C to exit the daemon.")}__name(startLocalControl,"startLocalControl");async function maybeOpenWebShellBrowser(handle,open,manualFallbackWhenIneligible=false){if(!open||!handle.webShellMounted)return;const shouldLaunch=shouldLaunchBrowser();if(!shouldLaunch&&!manualFallbackWhenIneligible)return;try{await handle.runtimeReady}catch(runtimeErr){writeStderrLine(`qwen serve: Web Shell runtime not ready; skipping --open: ${runtimeErr instanceof Error?runtimeErr.message:String(runtimeErr)}`);return}let target;try{target=new URL(handle.url);if(target.hostname==="0.0.0.0"||target.hostname==="[::]"){target.hostname="127.0.0.1"}if(handle.resolvedToken){target.hash=`token=${encodeURIComponent(handle.resolvedToken)}`}if(!shouldLaunch){writeStderrLine(`Browser launch is not available in this environment. Please open this URL manually: ${target.toString()}`);return}if(handle.resolvedToken){writeStderrLine("qwen serve: --open passes the token in the browser launch command (visible via `ps` / /proc); on a multi-user host open the URL manually instead.")}await openBrowserSecurely(target.toString())}catch(browserErr){const manualUrl=manualFallbackWhenIneligible&&target?`. Please open this URL manually: ${target.toString()}`:"";writeStderrLine(`qwen serve: failed to open browser: ${browserErr instanceof Error?browserErr.message:String(browserErr)}${manualUrl}`)}}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function primaryWorkspaceArg(workspace){return Array.isArray(workspace)?workspace[0]:workspace}__name(primaryWorkspaceArg,"primaryWorkspaceArg");var serveCommand={command:"serve",describe:"Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:__name(yargs=>yargs.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:DEFAULT_SERVE_HOSTNAME,description:"Interface to bind. Loopback (127.0.0.0/8, localhost, ::1, [::1]) is auth-free; anything else requires a token (one is generated and printed when neither --token nor QWEN_SERVER_TOKEN supplies one). A localhost bind that resolves off-loopback never generates, and still refuses when no token source resolved; an empty value is rejected as operator error."}).option("profile",{choices:["default","hosted-harness"],default:"default",description:"Deployment profile. hosted-harness enables the private no-tool Managed Session API on loopback."}).option("hosted-harness-capability-digest",{type:"string",description:"SHA-256 capability digest for the private Hosted Harness profile. Falls back to QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST."}).option("managed",{type:"boolean",default:false,description:"Start the daemon and Managed Agent with shared WebShell and embedded storage; downloads the server on first use and requires Java 21."}).option("managed-data-dir",{type:"string",requiresArg:true,description:"Private persistent data directory for --managed; defaults to <Qwen home>/managed-local."}).option("managed-web-config",{type:"string",requiresArg:true,description:"Run only the authenticated Managed Web gateway using a JSON file with apiUrl, tenantId, actorId and signingKeyFile. Requires an independent browser token of at least 32 bytes via QWEN_SERVER_TOKEN or --token."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the QWEN_SERVER_TOKEN env var; a non-loopback bind with neither generates an ephemeral token at startup, while loopback keeps the trusted tokenless mode unless --require-auth is set."}).option("max-sessions",{type:"number",description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable. Defaults to 32, or to the serve.maxSessions setting (user, system, and system-defaults scopes only); the flag wins when passed."}).option("max-total-sessions",{type:"number",description:"Non-negative integer cap on concurrent live sessions across all workspace runtimes. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",array:true,requiresArg:true,description:"Absolute workspace path to register with this daemon. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. Repeat to register isolated workspace runtimes; the first is primary."}).option("memory-project-scope",{type:"string",choices:MEMORY_PROJECT_SCOPES,description:'Choose how project memory is partitioned. Defaults to "workspace" so each daemon workspace stays isolated; "git-root" preserves the legacy shared scope. Overrides QWEN_CODE_MEMORY_PROJECT_SCOPE when provided.'}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:false,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token, QWEN_SERVER_TOKEN, or --open-with-auth (which installs its own generated loopback token); on non-loopback binds the generated ephemeral token also satisfies it, so the no-configured-secret fail-fast is loopback-only. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:false,description:"Enable direct POST /session/:id/shell execution. Available with bearer auth or trusted loopback; each call still requires a session-bound client id."}).option("tls-cert",{type:"string",description:"Path to a PEM certificate file. Serve over HTTPS instead of HTTP. Required for secure-context browser APIs (voice input/getUserMedia, WebRTC) when accessed over a LAN IP. Must be used together with --tls-key. Generate a local cert with mkcert."}).option("tls-key",{type:"string",description:"Path to a PEM private key file. Must be used together with --tls-cert."}).option("experimental-lsp",{type:"boolean",default:false,description:"Forward the experimental LSP opt-in to spawned agent sessions."}).option("restore-ask-user-question",{type:"boolean",default:false,description:"On session load/resume, re-hang a trailing unanswered ask_user_question instead of synthesizing a failed tool result."}).option("channel",{type:"string",array:true,description:"Experimental: start a daemon-managed channel worker for the named channel. Repeat to select multiple channels, or use --channel all."}).option("web",{type:"boolean",default:true,description:"Serve the Web Shell UI at the daemon root path. Use --no-web for an API-only daemon."}).option("open",{type:"boolean",default:false,description:"Open the Web Shell in a browser once the daemon is listening. With a token configured, the launch URL (token included) is handed to the browser launcher and is visible in the process list, so prefer opening the URL manually on multi-user hosts. No-op with --no-web, when the UI assets are absent, or in headless/CI/SSH environments."}).option("open-with-auth",{type:"boolean",default:false,description:"Open the Web Shell with bearer authentication on loopback. Reuse --token or QWEN_SERVER_TOKEN, or generate a temporary 256-bit token and deliver it in the URL fragment. In headless environments, print the fragment URL for manual opening."}).option("token-qr",{type:"boolean",description:"Print the token-bearing QR even when stdout is captured (not an interactive terminal) and the bearer is an operator-supplied (stable) token, which is withheld by default to keep stable credentials out of collected logs. Enable only when the log pipeline is as trusted as the daemon host. Can also be set via the serve.tokenQr setting (user, system, and system-defaults scopes only); the flag wins when passed. --no-token-qr suppresses the startup quickstart token QR for that run on every quickstart path \u2014 interactive terminal and generated token included. It does not govern the Local Control pairing QR, which --local-control prints by design."}).option("local-control",{type:"boolean",default:false,description:"Share the Web Shell on the local IPv4 network with its own revocable pairing token, terminal QR code, and best-effort sleep inhibition. Ctrl+C turns it off by ending the whole daemon; the Web Shell Settings card turns it off while the daemon keeps running."}).option("local-control-address",{type:"string",description:"Which local IPv4 address to share when the host is on more than one network. Only needed if --local-control reports an ambiguous choice."}).option("join",{type:"string",description:"Join another Qwen Code as a runtime, with the one-line link it shows under Agent \u2192 Runtime \u2192 Add runtime."}).option("agent-host-server",{type:"string",description:"Register this daemon as an Agent Host with a primary Qwen daemon."}).option("agent-host-workspace-id",{type:"string",description:"Control-plane workspace id printed by the primary daemon."}).option("agent-host-name",{type:"string",description:"Display name advertised for this Agent Host."}).option("agent-host-allow-http",{type:"boolean",default:false,description:"Allow unencrypted Agent Host HTTP connections outside loopback (trusted demo networks only)."}).check(argv=>{if(argv["local-control"]===true&&argv["web"]===false){throw new Error("Local Control requires the Web Shell.")}if(argv["local-control"]===true&&argv.hostname!==DEFAULT_SERVE_HOSTNAME){throw new Error(`Local Control requires --hostname ${DEFAULT_SERVE_HOSTNAME}.`)}if(argv["local-control"]!==true&&argv["local-control-address"]!==void 0){throw new Error("--local-control-address requires --local-control.")}if(argv["local-control-address"]===""){throw new Error("--local-control-address must not be empty.")}if(Boolean(argv["agent-host-server"])!==Boolean(argv["agent-host-workspace-id"])){throw new Error("--agent-host-server and --agent-host-workspace-id must be used together.")}if(argv["agent-host-name"]===""){throw new Error("--agent-host-name must not be empty.")}if(argv["join"]!==void 0){if(argv["agent-host-server"]||argv["agent-host-workspace-id"]){throw new Error("--join already names the coordinator and workspace; drop --agent-host-server and --agent-host-workspace-id.")}parseJoinLink(argv["join"])}return true}).option("event-ring-size",{type:"number",default:DEFAULT_RING_SIZE,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("compacted-replay-max-bytes",{type:"number",default:DEFAULT_COMPACTED_REPLAY_MAX_BYTES,description:"Per-session in-memory compacted replay snapshot byte cap for `POST /session/:id/load` late attaches. Larger = more recent history in load snapshots at higher heap cost. Must be a positive safe integer no larger than 256 MiB."}).option("max-journal-events",{type:"number",nargs:1,description:"Per-session baseline cap on replay entries retained in the in-flight live journal (current unfinished turn). Compatible text/thought chunks share bounded entries. When exceeded, the daemon first tries adaptive growth (see --max-journal-bytes); without granted headroom the oldest entries are dropped. Pinning this flag (or --max-journal-bytes) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_EVENTS+" when unset. Must be a positive safe integer."}).option("max-journal-bytes",{type:"number",nargs:1,description:"Per-session baseline source-event byte cap on the in-flight live journal. When a turn outgrows it, adaptive growth raises the session's caps (per-session hard cap "+JOURNAL_GROWTH_HARD_CAP_BYTES/(1024*1024)+" MiB) within a growth pool derived from the daemon memory budget (see --memory-budget-mb); without granted headroom the oldest entries are dropped whole (at least one is always kept), so the retained tail can be much smaller than the cap. Pinning this flag (or --max-journal-events) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_BYTES+" bytes when unset. Must be a positive safe integer."}).option("http-bridge",{type:"boolean",default:true,description:"HTTP bridge mode: attempt to preheat the primary `qwen --acp` child; trusted secondaries start one on demand. Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("memory-budget-mb",{type:"number",description:"Total memory budget in MB for the daemon process tree. When unset, derived as 50% of cgroup-constrained or host memory, and capped at the resolved available memory either way. In `admit` and `enforce` modes it determines managed ACP child capacity; `enforce` also applies the modeled per-child old-space ceiling. It also sizes one daemon-wide pool of "+JOURNAL_GROWTH_POOL_FRACTION*100+"% of the effective budget (capped at "+MAX_JOURNAL_GROWTH_POOL_MB+" MB; 0, growth disabled, when the effective budget falls below the "+MIN_MEMORY_BUDGET_MB+" MB minimum; see --max-journal-bytes). Reported under `limits.memory` in daemon status, alongside a modeled per-child partition under `limits.memory.childHeap`. Must be an integer in [1024, 1048576]."}).option("memory-pressure-mode",{choices:["off","observe"],default:"observe",description:"Whether the daemon derives a memory-pressure level from its own RSS and V8 heap. `observe` (default) reports the level in daemon status and raises a status issue when it leaves normal. `off` still reports the underlying figures but raises no issue, so the overall status rollup is unchanged \u2014 use it while calibrating, or if you alert on the top-level status. Nothing remediates in either mode."}).option("child-heap-mode",{choices:["off","observe","admit","enforce"],default:"observe",description:"Whether the daemon models a per-child heap partition of the memory budget. `observe` (default) reports the partition it would apply \u2014 `limits.memory.childHeap.perChildCeilingMb` and `maxConcurrentChildren` \u2014 and counts spawns that would have exceeded it. Nothing is applied: no child is sized from the budget and no spawn is refused. `off` models nothing. Note a refusal count of 0 does NOT mean the partition would be safe to apply; children still run on the much larger host-derived ceiling, so a workload needing more old space than the modeled ceiling looks healthy here. `admit` rejects starts past the modeled process limit but keeps the existing child heap arguments. Experimental `enforce` also applies the fixed modeled old-space ceiling to each managed child; it does not cap total process RSS."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:true,description:"Cross-origin allowlist for browser clients. Accepts `*`, a canonical origin, or a loopback port wildcard like `http://127.0.0.1:*` (requires a bearer token)."}).option("allow-private-auth-base-url",{type:"boolean",default:false,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to QWEN_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("experimental-paired-engines",{type:"boolean",default:false,description:"Experimental: build workspace runtimes, other than the private Conversations one, with paired Legacy and Managed engines. No Managed engine is available yet, so sessions run on Legacy with a durable owner."}).option("experimental-managed-agents",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-worker",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-auto-local",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-url",{type:"string",requiresArg:true,description:"Reserved experimental Runtime URL; not implemented and rejects startup."}).option("experimental-managed-runtime-token",{type:"string",requiresArg:true,description:"Reserved experimental Runtime credential; not implemented and rejects startup."}).option("managed-runtime-broker-url",{type:"string",requiresArg:true,description:"Private Broker URL for --profile hosted-harness; required together with token for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_URL."}).option("managed-runtime-broker-token",{type:"string",requiresArg:true,description:"Private Broker credential for --profile hosted-harness; required together with URL for Workspace tool turns. Falls back to QWEN_MANAGED_RUNTIME_BROKER_TOKEN; prefer the variable, since this option puts the credential in the process list."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Compatibility auto-reap delay for an idle workspace ACP child. 0 or unset = reap after work drains; keepalive windows may extend it (default)."}).option("initialize-timeout-ms",{type:"number",description:"ACP child request timeout, including the initialize handshake (ms). Default: 10000 (10 s)."}).option("session-restore-timeout-ms",{type:"number",description:"ACP session load/resume timeout (ms). Default: 60000. An explicit --initialize-timeout-ms can raise (but never lower) this default."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("session-prompt-settled-close-grace-ms",{type:"number",description:"Grace period after a prompt settles before an otherwise-idle session may be auto-closed (ms). Poll-based SSE clients use this window to reconnect without triggering a session rebuild. 0 = disabled (immediate close). Default: 0."}).option("permission-response-timeout-ms",{type:"number",description:"Wall-clock timeout for a human permission / ask_user_question response in daemon (ACP) mode (ms). 0 or unset = disabled (wait indefinitely). Default: 0."}).option("external-tool-guard-mode",{choices:["off","required"],default:"off",description:"Managed ACP pre-execution policy mode. Default off preserves current CLI and daemon behavior. Required fails startup unless a compatible loopback provider is available."}).option("external-tool-guard-endpoint",{type:"string",description:"Origin-only loopback HTTP(S) endpoint for required external tool guarding, for example http://127.0.0.1:8787."}).option("external-tool-guard-timeout-ms",{type:"number",description:"Per-handshake/prepare external tool guard timeout in milliseconds. Default: 3000."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),"builder"),handler:__name(async argv=>{if(argv["managed-web-config"]!==void 0){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedWebFlags(process.argv.slice(serveIndex+1));if(argv.managed||argv.profile!=="default"||!argv.web||argv.workspace!==void 0){throw new Error("--managed-web-config cannot be combined with daemon execution or Managed local mode.")}const{runManagedWebServe}=await import("./managed-web-serve-JPJBFJMR.js");const handle=await runManagedWebServe({configFile:argv["managed-web-config"],hostname:argv.hostname,port:argv.port,token:argv.token,allowOrigins:argv["allow-origin"]});writeStdoutLine(`Managed WebShell: ${handle.url}`);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv.managed){try{const serveIndex=process.argv.indexOf("serve");if(serveIndex>=0)validateManagedLocalFlags(process.argv.slice(serveIndex+1));if(argv.hostname!==DEFAULT_SERVE_HOSTNAME||argv.profile!=="default"||!argv.web||argv.workspace!==void 0||argv.token!==void 0||argv["tls-cert"]||argv["tls-key"]||argv["local-control"]||argv.join||argv["agent-host-server"]||argv.channel!==void 0||argv["experimental-paired-engines"]||argv["experimental-managed-agents"]||argv["experimental-managed-runtime-worker"]||argv["experimental-managed-runtime-auto-local"]||argv["experimental-managed-runtime-url"]!==void 0||argv["managed-runtime-broker-url"]!==void 0||argv["managed-runtime-broker-token"]!==void 0||argv["allow-origin"]?.length||argv["enable-session-shell"]||!argv["http-bridge"]){throw new Error("--managed uses its own loopback services, persistent credentials, and application-owned Workspaces. Use --port, --managed-data-dir, and --open; other deployment, workspace-import, or execution modes cannot be combined.")}const{runManagedLocalServe}=await import("./managed-local-serve-X7REHGB4.js");const handle=await runManagedLocalServe({port:argv.port,dataDirectory:argv["managed-data-dir"]});await maybeOpenWebShellBrowser(handle,argv.open||argv["open-with-auth"],argv["open-with-auth"]);process.exit(await handle.finished)}catch(error){writeStderrLine(`qwen serve: ${error instanceof Error?error.message:String(error)}`);process.exit(1)}}if(argv["managed-data-dir"]!==void 0){writeStderrLine("qwen serve: --managed-data-dir requires --managed.");process.exit(1)}const managedRuntimeBrokerUrl=argv["managed-runtime-broker-url"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];const managedRuntimeBrokerToken=argv["managed-runtime-broker-token"]??process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_URL"];delete process.env["QWEN_MANAGED_RUNTIME_BROKER_TOKEN"];const agentHostEnrollmentToken=process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"]?.trim();delete process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"];if(!argv["http-bridge"]){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(argv.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}if(argv["managed-runtime-broker-token"]!==void 0){writeStderrLine("qwen serve: --managed-runtime-broker-token is visible in the process command line; prefer the QWEN_MANAGED_RUNTIME_BROKER_TOKEN env var.")}let channelSelection;try{channelSelection=normalizeServeChannelSelection(argv.channel)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}const mcpClientBudget=argv["mcp-client-budget"];const mcpBudgetMode=argv["mcp-budget-mode"];if(mcpClientBudget!==void 0){if(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0){writeStderrLine("qwen serve: --mcp-client-budget must be a positive integer.");process.exit(1)}}if(mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){writeStderrLine("qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N.");process.exit(1)}const resolvedMcpMode=mcpBudgetMode??(mcpClientBudget!==void 0?"warn":"off");const memoryBudgetMb=argv["memory-budget-mb"];if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){writeStderrLine(memoryBudgetRangeError());process.exit(1)}const maxPendingPromptsPerSession=argv["max-pending-prompts-per-session"];if(maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){writeStderrLine("qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited).");process.exit(1)}if(mcpClientBudget!==void 0){writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}try{const loaded=loadSettings(primaryWorkspaceArg(argv.workspace)??process.cwd());const merged=loaded.merged;const approvalMode=merged.tools?.approvalMode;const sandbox=merged.tools?.sandbox;const sandboxEnv=process.env["SANDBOX"];const suppress=process.env["QWEN_CODE_SUPPRESS_YOLO_WARNING"];const suppressed=suppress==="1"||suppress==="true";if(approvalMode==="yolo"&&!sandbox&&!sandboxEnv&&!suppressed){writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING)}}catch{}const rateLimit=argv["rate-limit"]??(process.env["QWEN_SERVE_RATE_LIMIT"]==="1"||process.env["QWEN_SERVE_RATE_LIMIT"]==="true");let rateLimitPrompt;let rateLimitMutation;let rateLimitRead;let rateLimitWindowMs;if(rateLimit){const envInt=__name(key=>{const raw=process.env[key];if(raw===void 0||raw==="")return void 0;return parsePositiveIntegerEnv(raw,Number.NaN)},"envInt");rateLimitPrompt=argv["rate-limit-prompt"]??envInt("QWEN_SERVE_RATE_LIMIT_PROMPT");rateLimitMutation=argv["rate-limit-mutation"]??envInt("QWEN_SERVE_RATE_LIMIT_MUTATION");rateLimitRead=argv["rate-limit-read"]??envInt("QWEN_SERVE_RATE_LIMIT_READ");rateLimitWindowMs=argv["rate-limit-window-ms"]??envInt("QWEN_SERVE_RATE_LIMIT_WINDOW_MS");for(const[name,value]of[["--rate-limit-prompt",rateLimitPrompt],["--rate-limit-mutation",rateLimitMutation],["--rate-limit-read",rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){writeStderrLine(`qwen serve: ${name} must be a positive integer.`);process.exit(1)}}if(rateLimitWindowMs!==void 0&&(!Number.isFinite(rateLimitWindowMs)||!Number.isInteger(rateLimitWindowMs)||rateLimitWindowMs<1e3)){writeStderrLine("qwen serve: --rate-limit-window-ms must be an integer >= 1000.");process.exit(1)}}const externalToolGuardToken=process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]??"";delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const openWithAuth=argv["open-with-auth"];const open=argv.open||openWithAuth;const{runQwenServe}=await import("./run-qwen-serve-44X262G5.js");try{const serveOptions={port:argv.port,hostname:argv.hostname,profile:argv.profile,token:argv.token,mode:"http-bridge",maxSessions:argv["max-sessions"],...argv["max-total-sessions"]!==void 0?{maxTotalSessions:argv["max-total-sessions"]}:{},maxPendingPromptsPerSession,maxConnections:argv["max-connections"],eventRingSize:argv["event-ring-size"],compactedReplayMaxBytes:argv["compacted-replay-max-bytes"],...argv["max-journal-events"]!==void 0?{maxJournalEvents:argv["max-journal-events"]}:{},...argv["max-journal-bytes"]!==void 0?{maxJournalBytes:argv["max-journal-bytes"]}:{},workspace:argv.workspace,...argv["memory-project-scope"]!==void 0?{memoryProjectScope:argv["memory-project-scope"]}:{},requireAuth:argv["require-auth"],enableSessionShell:argv["enable-session-shell"],serveWebShell:argv.web,...argv["token-qr"]!==void 0?{tokenQr:argv["token-qr"]}:{},...argv["tls-cert"]!==void 0?{tlsCert:argv["tls-cert"]}:{},...argv["tls-key"]!==void 0?{tlsKey:argv["tls-key"]}:{},allowPrivateAuthBaseUrl:argv["allow-private-auth-base-url"],mcpClientBudget,mcpBudgetMode:resolvedMcpMode,...memoryBudgetMb!==void 0?{memoryBudgetMb}:{},memoryPressureMode:argv["memory-pressure-mode"],childHeapMode:argv["child-heap-mode"],...argv["allow-origin"]&&argv["allow-origin"].length>0?{allowOrigins:argv["allow-origin"]}:{},...argv["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:argv["prompt-deadline-ms"]}:{},...argv["experimental-paired-engines"]?{experimentalPairedEngines:true}:{},...argv["experimental-managed-agents"]?{experimentalManagedAgents:true}:{},...argv["experimental-managed-runtime-auto-local"]?{experimentalManagedRuntimeAutoLocal:true}:{},...argv["experimental-managed-runtime-worker"]?{experimentalManagedRuntimeWorker:true}:{},...argv["experimental-managed-runtime-url"]!==void 0?{experimentalManagedRuntimeUrl:argv["experimental-managed-runtime-url"]}:{},...argv["experimental-managed-runtime-token"]!==void 0?{experimentalManagedRuntimeToken:argv["experimental-managed-runtime-token"]}:{},...managedRuntimeBrokerUrl!==void 0?{managedRuntimeBrokerUrl}:{},...managedRuntimeBrokerToken!==void 0?{managedRuntimeBrokerToken}:{},...argv["hosted-harness-capability-digest"]!==void 0?{hostedHarnessCapabilityDigest:argv["hosted-harness-capability-digest"]}:{},...argv["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:argv["writer-idle-timeout-ms"]}:{},...argv["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:argv["channel-idle-timeout-ms"]}:{},...argv["initialize-timeout-ms"]!==void 0?{initializeTimeoutMs:argv["initialize-timeout-ms"]}:{},...argv["session-restore-timeout-ms"]!==void 0?{sessionRestoreTimeoutMs:argv["session-restore-timeout-ms"]}:{},...argv["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:argv["session-reap-interval-ms"]}:{},...argv["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:argv["session-idle-timeout-ms"]}:{},...argv["session-prompt-settled-close-grace-ms"]!==void 0?{sessionPromptSettledCloseGraceMs:argv["session-prompt-settled-close-grace-ms"]}:{},...argv["permission-response-timeout-ms"]!==void 0?{permissionResponseTimeoutMs:argv["permission-response-timeout-ms"]}:{},...argv["external-tool-guard-mode"]==="required"?{externalToolGuard:{mode:"required",endpoint:argv["external-tool-guard-endpoint"]??"",token:externalToolGuardToken,...argv["external-tool-guard-timeout-ms"]!==void 0?{timeoutMs:argv["external-tool-guard-timeout-ms"]}:{}}}:{},...rateLimit?{rateLimit:true}:{},...rateLimitPrompt!==void 0?{rateLimitPrompt}:{},...rateLimitMutation!==void 0?{rateLimitMutation}:{},...rateLimitRead!==void 0?{rateLimitRead}:{},...rateLimitWindowMs!==void 0?{rateLimitWindowMs}:{},...argv.experimentalLsp===true?{experimentalLsp:true}:{},...argv.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},...channelSelection!==void 0?{channelSelection}:{}};if(openWithAuth){const{applyOpenWithAuth}=await import("./open-with-auth-Z6WKB2OO.js");applyOpenWithAuth(serveOptions)}const handle=await runQwenServe(serveOptions,{updateRestartArgv:process.argv.slice(2)});const joined=argv["join"]?parseJoinLink(argv["join"]):void 0;const hostTarget=joined?{...joined,token:agentHostEnrollmentToken}:argv["agent-host-server"]&&argv["agent-host-workspace-id"]?{serverUrl:argv["agent-host-server"],workspaceId:argv["agent-host-workspace-id"],token:agentHostEnrollmentToken}:void 0;if(hostTarget){try{await handle.runtimeReady;const runtime=handle.getPrimaryWorkspaceRuntime();if(!runtime?.trusted||!runtime.generationGuard||runtime.generationGuard.closed){throw new Error("Agent Host join requires a trusted active workspace.")}const{startAgentHostConnection}=await import("./agent-host-client-3R2MAUVE.js");await startAgentHostConnection({bridge:runtime.bridge,serverUrl:hostTarget.serverUrl,workspaceId:hostTarget.workspaceId,workspaceCwd:runtime.workspaceCwd,allowHttp:argv["agent-host-allow-http"]===true,generationGuard:runtime.generationGuard,...hostTarget.token?{enrollmentToken:hostTarget.token}:{},...argv["agent-host-name"]?{name:argv["agent-host-name"]}:{}})}catch(error){await handle.close().catch(()=>void 0);throw error}}if(argv["local-control"]){try{await startLocalControl(handle,argv["local-control-address"])}catch(err){await handle.close().catch(()=>void 0);throw err}}await maybeOpenWebShellBrowser(handle,open,openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await blockForever()},"handler")};export{parseJoinLink,validateManagedLocalFlags,validateManagedWebFlags,maybeOpenWebShellBrowser,serveCommand};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
7
7
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{GlobTool}from"./chunk-M7MGE5IU.js";import{GrepTool}from"./chunk-S7Z7SUH3.js";import{LSTool}from"./chunk-FK5M3433.js";import{NotebookEditTool}from"./chunk-
|
|
3
|
+
import{GlobTool}from"./chunk-M7MGE5IU.js";import{GrepTool}from"./chunk-S7Z7SUH3.js";import{LSTool}from"./chunk-FK5M3433.js";import{NotebookEditTool}from"./chunk-N6EFYQ7M.js";import{TaskStopTool}from"./chunk-GXWDEHFP.js";import{WriteFileTool}from"./chunk-W2CV36HT.js";import{EditTool}from"./chunk-O3TUZQP4.js";import{ShellTool,isModifiableDeclarativeTool}from"./chunk-T3CQ72HC.js";import{stableJson}from"./chunk-FIXDX63I.js";import{ReadFileTool}from"./chunk-ZWPSBU7K.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat}from"node:fs/promises";function createExecutionTools(config){const tools=[new ReadFileTool(config),new WriteFileTool(config),new EditTool(config),new NotebookEditTool(config),new GlobTool(config),new GrepTool(config),new LSTool(config),new ShellTool(config),new TaskStopTool(config)];return new Map(tools.map(tool=>[tool.name,tool]))}__name(createExecutionTools,"createExecutionTools");var LocalExecutionEnvironment=class{constructor(config,options={}){this.config=config;this.toolNames=options.toolNames;this.run=options.run;this.tools=createExecutionTools(config);if(options.toolNames){for(const name of this.tools.keys()){if(!options.toolNames.has(name))this.tools.delete(name)}}}static{__name(this,"LocalExecutionEnvironment")}toolNames;tools;invocations=new Map;controllers=new Set;run;disposed=false;tool(name){if(this.disposed)throw new Error("Execution environment is disposed.");const tool=this.tools.get(name);if(!tool)throw new Error(`Unsupported execution tool: ${name}`);return tool}pending(id){if(this.disposed)throw new Error("Execution environment is disposed.");const pending=this.invocations.get(id);if(!pending)throw new Error(`Unknown execution invocation: ${id}`);if(pending.executing)throw new Error(`Invocation is executing: ${id}`);return pending}toolDefinition(name){const{name:toolName,description,parametersJsonSchema}=this.tool(name).schema;return{name:toolName,description,parametersJsonSchema}}async prepare(request,signal){signal.throwIfAborted();const tool=this.tool(request.toolName);if(this.invocations.has(request.id))throw new Error(`Duplicate invocation: ${request.id}`);if(this.invocations.size>=256)throw new Error("Too many pending execution invocations.");let params=structuredClone(request.params);if(request.modification){if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");params=tool.getModifyContext(signal).createUpdatedParams(request.modification.oldContent,request.modification.newContent,params)}const invocation=tool.build(params);this.invocations.set(request.id,{toolName:request.toolName,invocation,executing:false,...request.callId===void 0?{}:{callId:request.callId}});return{params:invocation.params,description:invocation.getDescription(),locations:invocation.toolLocations()}}async permission(id,signal){signal.throwIfAborted();return this.pending(id).invocation.getDefaultPermission(signal)}async confirmation(id,signal){signal.throwIfAborted();const pending=this.pending(id);const details=await pending.invocation.getConfirmationDetails(signal);pending.confirmation=details;const{onConfirm:_onConfirm,...serializable}=details;return serializable}async confirm(id,outcome,payload,signal){signal.throwIfAborted();const pending=this.pending(id);await pending.confirmation?.onConfirm(outcome,payload);if(outcome==="cancel")this.invocations.delete(id)}async execute(id,signal,updateOutput){signal.throwIfAborted();const pending=this.pending(id);pending.executing=true;const controller=new AbortController;const abort=__name(()=>controller.abort(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});this.controllers.add(controller);try{if(this.run){const params=structuredClone(pending.invocation.params);const rebuilt=this.tool(pending.toolName).build(structuredClone(params)).params;if(stableJson(rebuilt)!==stableJson(params)){throw new Error("The approved parameters change when the tool builds them again; the call did not run.")}return await this.run({id,toolName:pending.toolName,params,...pending.callId===void 0?{}:{callId:pending.callId}},controller.signal,updateOutput)}return await pending.invocation.execute(controller.signal,updateOutput,{...this.config.getShellExecutionConfig(),streamBufferedOutput:true})}finally{signal.removeEventListener("abort",abort);this.controllers.delete(controller);this.invocations.delete(id)}}async modificationContent(toolName,params,signal){signal.throwIfAborted();const tool=this.tool(toolName);if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");const context=tool.getModifyContext(signal);const current=await context.getCurrentContent(params);const proposed=await context.getProposedContent(params);return{current,proposed}}async release(id,signal){signal.throwIfAborted();if(!this.invocations.get(id)?.executing)this.invocations.delete(id)}async invalidateReadCache(paths){const cache=this.config.getFileReadCache();if(!paths){cache.clear();return}await Promise.all(paths.map(async filePath=>{const stats=await stat(filePath).catch(()=>void 0);if(!stats||!cache.markReadEvictedFromHistory(stats))cache.invalidateByPath(filePath)}))}async dispose(){this.disposed=true;for(const controller of this.controllers)controller.abort();this.config.getBackgroundShellRegistry().abortAll();this.invocations.clear();this.tools.clear()}};export{createExecutionTools,LocalExecutionEnvironment};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{assertExternalAgentSpawnPlatformSupported,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit}from"./chunk-
|
|
3
|
+
import{assertExternalAgentSpawnPlatformSupported,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit}from"./chunk-5TWAP4OG.js";import{ProcessRegistry}from"./chunk-ESSOEHTE.js";import"./chunk-BC4C6F32.js";import"./chunk-2QYDBHYZ.js";import"./chunk-LUDNUVSA.js";import"./chunk-VTZZXEWA.js";import"./chunk-L5UULTGF.js";import"./chunk-CFTFKWPW.js";import"./chunk-NIEO2TBE.js";import"./chunk-WSOEJTOC.js";import"./chunk-CK3OKTTL.js";import"./chunk-QS2ZMQIS.js";import"./chunk-S7IKHQ6I.js";import"./chunk-PAD5GPDY.js";import"./chunk-MD3ZEOBX.js";import"./chunk-SSYS5YN5.js";import"./chunk-X5QSFJVS.js";import"./chunk-OMDTFGTX.js";import"./chunk-3EZ5GCUT.js";import"./chunk-46VUDNCL.js";import"./chunk-MKH3EH7O.js";import"./chunk-E3KWSRJN.js";import"./chunk-FRVXSKL4.js";import"./chunk-HW6SU6MX.js";import"./chunk-ZHHFNZ5J.js";import"./chunk-AKWYMQKU.js";import"./chunk-MZUOREFD.js";import"./chunk-BVV7UXES.js";import"./chunk-7XZVMIY5.js";import"./chunk-BY46PCWY.js";import"./chunk-ZZJXFLVM.js";import"./chunk-RKDS7A4H.js";import"./chunk-PMBI46K4.js";import"./chunk-IV3HAIUN.js";import"./chunk-XFMPZINJ.js";import"./chunk-DECUAM3U.js";import"./chunk-QX7W2HY7.js";import"./chunk-HN5UYLPU.js";import"./chunk-PGRN3GZY.js";import"./chunk-HTW7PYHK.js";import"./chunk-AMGUAA4G.js";import"./chunk-YFTVFH2A.js";import"./chunk-ZBHL2CXR.js";import"./chunk-NIOS3B3V.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-T3CQ72HC.js";import"./chunk-R2EHHA2C.js";import"./chunk-YK7NDQKM.js";import"./chunk-ZLZF2ZDD.js";import"./chunk-OMSVOFTC.js";import"./chunk-PHIPLV2I.js";import"./chunk-ZOTKZI2P.js";import"./chunk-A6G5TAIF.js";import"./chunk-YVBHCSZD.js";import"./chunk-FIXDX63I.js";import"./chunk-T7CHK6C2.js";import"./chunk-PT7NZBDY.js";import"./chunk-TWP72VRH.js";import"./chunk-UYEWRLGD.js";import"./chunk-QVPT37XZ.js";import"./chunk-YVD4O5ZB.js";import"./chunk-T6W33SET.js";import"./chunk-WK2IBT6D.js";import"./chunk-QZV4PFQK.js";import"./chunk-ILECDNJX.js";import"./chunk-QXQGUM3Y.js";import"./chunk-UQ7IROJH.js";import"./chunk-SZCBUCNH.js";import"./chunk-BEKROCWN.js";import"./chunk-5SUFJTQQ.js";import"./chunk-BYU42MLK.js";import"./chunk-JWQXU3SR.js";import"./chunk-5LZ2DPLH.js";import"./chunk-XQJOZDV7.js";import"./chunk-CV2UAEZA.js";import"./chunk-FUBDS3AV.js";import"./chunk-HW6AWS7W.js";import"./chunk-KLC3OD2M.js";import"./chunk-Q5IZXKUJ.js";import"./chunk-G5PYYZMM.js";import"./chunk-BG67XABA.js";import"./chunk-OBOU4ZZM.js";import"./chunk-D7XCQWP2.js";import"./chunk-AE5OMKRY.js";import"./chunk-OBV7RNHV.js";import"./chunk-7CQMWEMY.js";import"./chunk-GOZYWU4B.js";import"./chunk-OUC3WICA.js";import"./chunk-JZK2WGXA.js";import"./chunk-MPHSE7M4.js";import"./chunk-S2ZKZXHX.js";import"./chunk-7UK4WJWS.js";import"./chunk-4GP3PH7Z.js";import"./chunk-4QQKOW5M.js";import"./chunk-OV3EBH6J.js";import"./chunk-EBMCWXGZ.js";import"./chunk-XZTE4YTN.js";import"./chunk-LSASUDF2.js";import"./chunk-2V5EKGDK.js";import"./chunk-MOKVM4PT.js";import"./chunk-YIW3H46P.js";import"./chunk-EOMRLUNZ.js";import"./chunk-4ZRCV3JY.js";import"./chunk-TL6MLBXR.js";import"./chunk-NMY3PYNO.js";import"./chunk-YGLM5XPP.js";import"./chunk-WGNF7FPC.js";import"./chunk-4NPYOXJO.js";import"./chunk-MWGB5RCF.js";import"./chunk-SCD5TUBG.js";import"./chunk-NTRFETZB.js";import"./chunk-TL3SF2GA.js";import{sanitizeChildEnv}from"./chunk-LMJPU2JM.js";import"./chunk-VFB6Q74I.js";import"./chunk-4JNHUZ7M.js";import"./chunk-SW54YEPK.js";import"./chunk-ZCRL73DT.js";import"./chunk-A6LT3FIJ.js";import"./chunk-S6RXVOY6.js";import"./chunk-YZFNBUKG.js";import"./chunk-AGEDDL7Z.js";import"./chunk-2NJJHZ52.js";import"./chunk-BN4FIQ77.js";import"./chunk-X64RXJQQ.js";import"./chunk-HETUGUHE.js";import"./chunk-ET2Z7ZGF.js";import"./chunk-XFPYXD2P.js";import"./chunk-3YWXKSOI.js";import"./chunk-5CWTKFI4.js";import"./chunk-C4MVD5OI.js";import"./chunk-Z2W7S4O4.js";import"./chunk-476F6QIM.js";import"./chunk-4R67LXKL.js";import"./chunk-FQRF6B65.js";import"./chunk-ZWPSBU7K.js";import"./chunk-UQFTXKEB.js";import"./chunk-HDGTWJ24.js";import"./chunk-W5NWIGKO.js";import"./chunk-KVA6DHHF.js";import"./chunk-PWOQASXT.js";import"./chunk-K7JCVESI.js";import"./chunk-Y6HHV4LC.js";import"./chunk-RP57XAJ2.js";import"./chunk-Z6AR5XE5.js";import"./chunk-7DOOXUDG.js";import"./chunk-77V43YOE.js";import"./chunk-7U7CWMP7.js";import"./chunk-EFTJIDS3.js";import"./chunk-4DIWAQ5G.js";import"./chunk-Q6UAOTP3.js";import"./chunk-H5EXNXGW.js";import"./chunk-GOR7FFVE.js";import"./chunk-4ZBZL23U.js";import"./chunk-BMHYEQTI.js";import"./chunk-ZZZAYAJW.js";import"./chunk-XMANRGPK.js";import"./chunk-3XVPZY7X.js";import"./chunk-KQX4H2D3.js";import"./chunk-URNNJMIC.js";import"./chunk-GU22I6TY.js";import"./chunk-YEYW7PPR.js";import"./chunk-DBRQGEEI.js";import"./chunk-B3ZFUGTC.js";import"./chunk-IRINPFG7.js";import"./chunk-6GTPLW7K.js";import"./chunk-NGVRCUYD.js";import"./chunk-5DTFN37U.js";import"./chunk-2YUBAWQ6.js";import"./chunk-O5EKX7LG.js";import"./chunk-TM6ZCBR7.js";import"./chunk-SVAPAMMG.js";import"./chunk-3KUHQGOS.js";import"./chunk-I6S7NGX3.js";import"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import"./chunk-I4H7NUVP.js";import"./chunk-EPODBRBP.js";import"./chunk-OKN3Z5C5.js";import"./chunk-XYB7GC5U.js";import"./chunk-2UOMCYQG.js";import"./chunk-I7L2TX4M.js";import"./chunk-MK3OONRA.js";import"./chunk-COGTQ5KZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{createInterface}from"node:readline";var debugLogger=createDebugLogger("EXTERNAL_AGENT");var CodexInterruption=class extends Error{constructor(mode){super(mode==="TIMEOUT"?"Codex task exceeded its time limit.":"Codex task cancelled.");this.mode=mode}static{__name(this,"CodexInterruption")}};function object(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new Error("Codex returned an invalid protocol object.")}return value}__name(object,"object");function id(value){if(typeof value!=="string"||!value){throw new Error("Codex returned an invalid thread or turn ID.")}return value}__name(id,"id");async function runCodex(params,prompt,sandbox,signal){if(signal.aborted)throw new CodexInterruption("CANCELLED");const env=sanitizeChildEnv(process.env);delete env["CODEX_THREAD_ID"];delete env["CLAUDECODE"];delete env["NODE_OPTIONS"];const child=spawn(params.spec.command,params.spec.args??["app-server","--stdio"],{cwd:params.runtimeContext.getTargetDir(),env,stdio:"pipe",detached:process.platform!=="win32",windowsHide:true});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});child.stderr.resume();const lines=createInterface({input:child.stdout,crlfDelay:Infinity});const pending=new Map;let sequence=0;let threadId;let turnId;let finalAnswer;let unphasedAnswer;let terminal=false;let exitDrainTimer;let fail;const failure=new Promise((_resolve,reject)=>{fail=reject});let complete;const completed=new Promise(resolve=>{complete=resolve});const write=__name(frame=>{child.stdin.write(`${JSON.stringify(frame)}
|
|
4
4
|
`)},"write");const request=__name((method,parameters)=>{const requestId=++sequence;return new Promise((resolve,reject)=>{pending.set(requestId,{resolve,reject});write({id:requestId,method,params:parameters})})},"request");const abort=__name(()=>{if(threadId&&turnId){void request("turn/interrupt",{threadId,turnId}).catch(()=>{})}fail(new CodexInterruption("CANCELLED"))},"abort");signal.addEventListener("abort",abort,{once:true});child.once("error",error=>{fail(new Error(error.code==="ENOENT"?`Cannot start ${params.spec.command}. Install Codex and make it available on PATH.`:`Cannot start Codex: ${error.code??"process error"}`))});const onExit=__name((code,exitSignal)=>{exitDrainTimer=setTimeout(()=>fail(new Error(`Codex exited before completion (${exitSignal??code}).`)),1e4)},"onExit");child.once("exit",onExit);child.stdin.on("error",()=>fail(new Error("Codex input stream closed.")));child.stdout.on("error",()=>fail(new Error("Codex output stream failed.")));const associateTurn=__name(value=>{const observed=id(value);if(turnId&&observed!==turnId)throw new Error("Codex returned another turn.");turnId=observed},"associateTurn");lines.on("line",line=>{if(terminal&&pending.size===0)return;try{let frame;try{frame=object(JSON.parse(line))}catch(error){if(terminal)return;throw error}if(typeof frame["method"]!=="string"){const reply=pending.get(frame["id"]);if(!reply)return;pending.delete(frame["id"]);if(frame["error"])reply.reject(new Error("Codex rejected an app-server request."));else reply.resolve(object(frame["result"]));return}if(terminal)return;const method=frame["method"];const parameters=object(frame["params"]??{});if(frame["id"]!==void 0){let result;switch(method){case"item/commandExecution/requestApproval":case"item/fileChange/requestApproval":{const available=parameters["availableDecisions"];const decision=Array.isArray(available)?available.includes("decline")?"decline":available.includes("cancel")?"cancel":void 0:"decline";if(!decision)throw new Error("Codex offered no unattended rejection.");result={decision};break}case"item/permissions/requestApproval":result={permissions:{},scope:"turn"};break;case"item/tool/requestUserInput":result={answers:{}};break;case"mcpServer/elicitation/request":result={action:"decline",content:null,_meta:null};break;default:write({id:frame["id"],error:{code:-32601,message:"Unsupported unattended request."}});throw new Error(`Codex requested unsupported interaction: ${method}`)}write({id:frame["id"],result});return}if(!threadId||parameters["threadId"]!==threadId)return;if(method==="turn/started"||method==="turn/completed"){const turn=object(parameters["turn"]);associateTurn(turn["id"]);if(method==="turn/completed"){terminal=true;complete(turn)}}else if(method==="item/completed"){associateTurn(parameters["turnId"]);const item=object(parameters["item"]);if(item["type"]!=="agentMessage")return;if(typeof item["text"]!=="string")throw new Error("Codex returned an invalid message.");if(item["phase"]==="final_answer")finalAnswer=item["text"];else if(item["phase"]==null)unphasedAnswer=item["text"]}}catch(error){fail(error instanceof Error?error:new Error("Invalid Codex protocol frame."))}});lines.on("close",()=>{if(!terminal||pending.size>0)fail(new Error("Codex protocol closed before completion."))});const initTimer=setTimeout(()=>fail(new Error("Codex initialization timed out.")),1e4);const minutes=params.runConfig.max_time_minutes;const executionTimer=minutes===void 0?void 0:setTimeout(()=>fail(new CodexInterruption("TIMEOUT")),minutes*6e4);const run=__name(async()=>{await request("initialize",{clientInfo:{name:"qwen-code",version:"1.0.0"},capabilities:{experimentalApi:false}});write({method:"initialized"});const started=await request("thread/start",{cwd:params.runtimeContext.getTargetDir(),ephemeral:true,approvalPolicy:"never",sandbox});const thread=object(started["thread"]);threadId=id(thread["id"]);if(thread["ephemeral"]!==true)throw new Error("Codex did not create an ephemeral thread.");clearTimeout(initTimer);const startedTurn=await request("turn/start",{threadId,input:[{type:"text",text:prompt,text_elements:[]}]});associateTurn(object(startedTurn["turn"])["id"]);const turn=await completed;if(turn["status"]!=="completed")throw new Error(`Codex turn ended with status ${String(turn["status"])}.`);const answer=finalAnswer??unphasedAnswer;if(!answer?.trim())throw new Error("Codex completed without a final answer.");return answer},"run");let completedAnswer;let interruption;try{completedAnswer=await Promise.race([run(),failure]);return completedAnswer}catch(error){if(error instanceof CodexInterruption)interruption=error;throw error}finally{clearTimeout(initTimer);clearTimeout(executionTimer);clearTimeout(exitDrainTimer);child.removeListener("exit",onExit);signal.removeEventListener("abort",abort);lines.close();for(const reply of pending.values())reply.reject(new Error("Codex connection closed."));pending.clear();await tracked.terminate().catch(error=>{const detail=error instanceof Error?error.message:String(error);if(isUnprovenExternalAgentTreeExit(error)){const diagnostic=`Codex process tree not proven gone after cleanup: ${detail}`;debugLogger.warn(diagnostic);if(params.eventEmitter?.rawListeners("error").length){params.eventEmitter.emit("error",{subagentId:params.subagentId??params.name,error:diagnostic,timestamp:Date.now()})}}else if(!isExpectedExternalAgentCleanupExit(error)){if(interruption){interruption.message+=`
|
|
5
5
|
|
|
6
6
|
Codex cleanup failed: ${detail}`;throw interruption}throw new Error(`Codex cleanup failed: ${detail}`+(completedAnswer===void 0?"":`
|