gerege-cli 0.26.6 → 0.26.8
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/bundled/gerege-video/SKILL.md +22 -0
- package/bundled/gerege-video/scripts/video.js +137 -0
- package/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LUINLOQW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
- package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
- package/chunks/{acpAgent-67UN66PB.js → acpAgent-XG6SM2VU.js} +3 -3
- package/chunks/{advisor-SAXMI4QZ.js → advisor-SZVPQNPA.js} +1 -1
- package/chunks/{agent-KV7BXY6C.js → agent-N7QF7BJS.js} +1 -1
- package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-GLP5GUEX.js} +1 -1
- package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-H4VOB3M6.js} +1 -1
- package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-E4C3OC4M.js} +1 -1
- package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
- package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-HDYQDJS4.js} +1 -1
- package/chunks/{batch-XFVQ4BLM.js → batch-3CRVN5VJ.js} +1 -1
- package/chunks/{bridge-AE7AFEXB.js → bridge-NZ6WVBLQ.js} +1 -1
- package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-Z7I2JI6M.js} +1 -1
- package/chunks/{chunk-BCI62WSL.js → chunk-236DHGNH.js} +1 -1
- package/chunks/{chunk-JRTOPEM3.js → chunk-2M3ND5WN.js} +1 -1
- package/chunks/{chunk-LBLLWAKK.js → chunk-36A6EXHB.js} +1 -1
- package/chunks/{chunk-H3IR3GIE.js → chunk-3ANIQTDT.js} +1 -1
- package/chunks/{chunk-GSPGIGO5.js → chunk-3QTR2HAE.js} +3 -3
- package/chunks/{chunk-32XHDDIA.js → chunk-3TTHYXT3.js} +1 -1
- package/chunks/{chunk-MTDBCIDA.js → chunk-4CE4GMDL.js} +1 -1
- package/chunks/{chunk-T2YTHAJW.js → chunk-4FVT657Y.js} +1 -1
- package/chunks/{chunk-CGDFZEER.js → chunk-4HSISRRA.js} +1 -1
- package/chunks/{chunk-7453BHJO.js → chunk-4SZUJ5RT.js} +1 -1
- package/chunks/{chunk-B37YY4XU.js → chunk-57D2OB3I.js} +1 -1
- package/chunks/{chunk-WGFX3EL3.js → chunk-5FGBLIXB.js} +1 -1
- package/chunks/{chunk-I6PUY2T3.js → chunk-5HX2QGVR.js} +1 -1
- package/chunks/{chunk-BPFFRPWE.js → chunk-5ZNXAWOG.js} +6 -6
- package/chunks/{chunk-BHIDG6VZ.js → chunk-6CKX56LJ.js} +1 -1
- package/chunks/{chunk-GRAECADD.js → chunk-6NIQFWXP.js} +1 -1
- package/chunks/{chunk-ELDZ4MNL.js → chunk-6PC6MZHL.js} +1 -1
- package/chunks/{chunk-FEP6W4NJ.js → chunk-6VQKGKMJ.js} +1 -1
- package/chunks/{chunk-GBSRWT7J.js → chunk-6ZEMLEK2.js} +1 -1
- package/chunks/{chunk-4NDJKNN6.js → chunk-72VY2PJA.js} +1 -1
- package/chunks/{chunk-BAUMVH4Q.js → chunk-75I3NYBD.js} +1 -1
- package/chunks/{chunk-YH2XRWRF.js → chunk-76L7ZDEK.js} +1 -1
- package/chunks/{chunk-2JGTWRZJ.js → chunk-7XQ5D34E.js} +6 -6
- package/chunks/{chunk-DA6LOBSB.js → chunk-AYX75VXG.js} +1 -1
- package/chunks/{chunk-G6DALGGS.js → chunk-BBDFEMCF.js} +1 -1
- package/chunks/{chunk-VD2GSW64.js → chunk-BOTX7S66.js} +1 -1
- package/chunks/{chunk-M6KB5RVD.js → chunk-CY2QKKZA.js} +1 -1
- package/chunks/{chunk-HTAUIJB4.js → chunk-D5JWQUID.js} +1 -1
- package/chunks/{chunk-P3JEEDQZ.js → chunk-DMIPB7RZ.js} +1 -1
- package/chunks/{chunk-CF6SZJNP.js → chunk-DSKA3P2C.js} +1 -1
- package/chunks/{chunk-LTE4N6L3.js → chunk-DVC65H4X.js} +1 -1
- package/chunks/{chunk-W5Z4BWWA.js → chunk-DVJSDCMX.js} +1 -1
- package/chunks/{chunk-65ME4BOH.js → chunk-E6CPFQX2.js} +1 -1
- package/chunks/{chunk-JEDL4IKF.js → chunk-EIFBGEXJ.js} +1 -1
- package/chunks/{chunk-AYVCT5FF.js → chunk-EQOHDAYU.js} +1 -1
- package/chunks/{chunk-2TAJ5STJ.js → chunk-EZPM4DLR.js} +1 -1
- package/chunks/{chunk-JWNKPINR.js → chunk-F6U6T7QD.js} +1 -1
- package/chunks/{chunk-ET5M5WFN.js → chunk-FCGFBUHS.js} +1 -1
- package/chunks/{chunk-OU7CEG7Q.js → chunk-G2LTZU67.js} +1 -1
- package/chunks/{chunk-2N3NBTYJ.js → chunk-GMJSEK4V.js} +1 -1
- package/chunks/{chunk-NA4ZF2FE.js → chunk-HJMUBVXZ.js} +2 -2
- package/chunks/{chunk-AFO5ER23.js → chunk-HQZTAA2U.js} +1 -1
- package/chunks/{chunk-OK7LBM5G.js → chunk-I63TIQOI.js} +1 -1
- package/chunks/{chunk-OJ4K62S2.js → chunk-I65LBJN7.js} +1 -1
- package/chunks/{chunk-GHIFIXNX.js → chunk-IBDOC27R.js} +1 -1
- package/chunks/{chunk-2LWJGXTW.js → chunk-IKF2HWEV.js} +1 -1
- package/chunks/{chunk-AEZYXPFS.js → chunk-K6NS2HXT.js} +1 -1
- package/chunks/{chunk-T5DKF33F.js → chunk-KTRNYPQP.js} +1 -1
- package/chunks/{chunk-SKGJ26HQ.js → chunk-L3ANU5JZ.js} +1 -1
- package/chunks/{chunk-U3Q72OGV.js → chunk-LKPMADUO.js} +1 -1
- package/chunks/{chunk-MYV7GY3H.js → chunk-M56Y2B6N.js} +1 -1
- package/chunks/{chunk-34HC2AXI.js → chunk-N5KRBAK5.js} +2 -2
- package/chunks/{chunk-EXIFPXMB.js → chunk-NA2WJPOU.js} +1 -1
- package/chunks/{chunk-7RNOS7R4.js → chunk-NGOWLXYK.js} +1 -1
- package/chunks/{chunk-IZ5MWA6E.js → chunk-NL7P73ZP.js} +1 -1
- package/chunks/{chunk-FYBJGRX7.js → chunk-NS3QR7D3.js} +1 -1
- package/chunks/{chunk-XISR37DQ.js → chunk-O5JCCBMQ.js} +1 -1
- package/chunks/{chunk-FKL3V5BO.js → chunk-OOKFFZHF.js} +1 -1
- package/chunks/{chunk-VRKYBH5G.js → chunk-OTYPLLMT.js} +5 -5
- package/chunks/{chunk-W66WWTOP.js → chunk-P7NHWX27.js} +1 -1
- package/chunks/{chunk-AEKEZRIU.js → chunk-PC5QZUKR.js} +1 -1
- package/chunks/{chunk-NEKPQLFY.js → chunk-PS7MQL57.js} +2 -2
- package/chunks/{chunk-TB4AUC2L.js → chunk-PXWHOFAA.js} +1 -1
- package/chunks/{chunk-OOJ2AQT3.js → chunk-Q65LVCDR.js} +1 -1
- package/chunks/{chunk-EFIRES46.js → chunk-QDUDLELH.js} +1 -1
- package/chunks/{chunk-KZNYALFU.js → chunk-QF22ILPV.js} +1 -1
- package/chunks/{chunk-MGATL4OA.js → chunk-QW7MAG2E.js} +1 -1
- package/chunks/{chunk-KJGRCIVY.js → chunk-RXK6XD6F.js} +1 -1
- package/chunks/{chunk-W2RQIZ6B.js → chunk-SVDFCWS7.js} +1 -1
- package/chunks/{chunk-P62S5JGM.js → chunk-TKP3GAUI.js} +1 -1
- package/chunks/{chunk-BQZF3UKI.js → chunk-TUS74LFI.js} +1 -1
- package/chunks/{chunk-JH3V5SPA.js → chunk-U7YGHPSL.js} +1 -1
- package/chunks/{chunk-NONBHCXP.js → chunk-UB37RBSK.js} +1 -1
- package/chunks/{chunk-T53VMDXH.js → chunk-UK5SIRH4.js} +1 -1
- package/chunks/{chunk-3W32X2DH.js → chunk-UTTSBCFR.js} +1 -1
- package/chunks/{chunk-RSLTOIG5.js → chunk-UYV4ZVXY.js} +2 -2
- package/chunks/{chunk-FKZ46GKL.js → chunk-VC3JJL7E.js} +1 -1
- package/chunks/{chunk-SP6CQ3MO.js → chunk-VKWVIWLK.js} +1 -1
- package/chunks/{chunk-N7PWZBXV.js → chunk-VUI6STKU.js} +1 -1
- package/chunks/{chunk-5EXL4TKQ.js → chunk-W3YXE55M.js} +1 -1
- package/chunks/{chunk-NVOI6UDQ.js → chunk-WAIPC47V.js} +1 -1
- package/chunks/{chunk-QDCUR3JB.js → chunk-WMJ6UHDP.js} +1 -1
- package/chunks/{chunk-CBE6ZIHU.js → chunk-WZU2ECUD.js} +1 -1
- package/chunks/{chunk-ZENMAISJ.js → chunk-XAGIZY2Y.js} +1 -1
- package/chunks/{chunk-RXN7DUMP.js → chunk-XGZYVULJ.js} +2 -2
- package/chunks/{chunk-HOG66S6K.js → chunk-XJIHDVPX.js} +1 -1
- package/chunks/{chunk-UKLXKJKL.js → chunk-XVDIHFRH.js} +1 -1
- package/chunks/{chunk-76FSYQTG.js → chunk-YMEW4TTT.js} +1 -1
- package/chunks/{chunk-EYPLBTMI.js → chunk-Z32URWBG.js} +1 -1
- package/chunks/{chunk-CUP2TNJK.js → chunk-Z6HRXHJP.js} +1 -1
- package/chunks/{chunk-MPVQDYPH.js → chunk-ZO4F6ZWR.js} +1 -1
- package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-DDKYNU42.js} +1 -1
- package/chunks/{config-utils-OWY5G5Y2.js → config-utils-S7Z2ZZ2E.js} +1 -1
- package/chunks/{contextCommand-IXFUZH65.js → contextCommand-7F4PGV2A.js} +1 -1
- package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-LBH3U7ZF.js} +1 -1
- package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-56DS2T6L.js} +1 -1
- package/chunks/{cron-create-2422NBSJ.js → cron-create-PBP3C46Q.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
- package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
- package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
- package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
- package/chunks/{edit-E5LEI2LL.js → edit-U7TGKKK3.js} +1 -1
- package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-27HC5AXN.js} +1 -1
- package/chunks/{environment-XBBIB3VA.js → environment-PHWY6C4P.js} +1 -1
- package/chunks/{errors-LNMQ7TUK.js → errors-F2EYYFI3.js} +1 -1
- package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-O4KJ5SMM.js} +1 -1
- package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-AMFXZ7JD.js} +1 -1
- package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-LDYL43PB.js} +1 -1
- package/chunks/{fast-path-M6K2RACY.js → fast-path-HTODEVOR.js} +1 -1
- package/chunks/{glob-N2QT4U7U.js → glob-NKQJJZND.js} +1 -1
- package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-47I455VV.js} +1 -1
- package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
- package/chunks/{i18n-AGOA6MUI.js → i18n-TCOB4TC5.js} +1 -1
- package/chunks/{initializer-FRKYDUSX.js → initializer-NLYOGZZS.js} +1 -1
- package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-TF2RSJOG.js} +1 -1
- package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-5F7R3KSA.js} +1 -1
- package/chunks/{list-DE7VUIR2.js → list-U2AEVLFP.js} +1 -1
- package/chunks/{llm-N3JGJHYC.js → llm-EV2QTQBU.js} +4 -4
- package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-ZXUSPPG2.js} +1 -1
- package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
- package/chunks/{local-BE624O3A.js → local-ZTSBSKWV.js} +1 -1
- package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-F263PSIM.js} +1 -1
- package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
- package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-5ET3JHUT.js} +1 -1
- package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-MJEQ47H2.js} +1 -1
- package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-ODPR5OEH.js} +1 -1
- package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-S5R4Z5OL.js} +1 -1
- package/chunks/managed-npm-update-BUI5APGY.js +8 -0
- package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
- package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
- package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-XSSTLAEY.js} +1 -1
- package/chunks/{mcp-VC4CJPE5.js → mcp-WLHDOKP7.js} +1 -1
- package/chunks/{memory-S6OJA3ZD.js → memory-OUUHPSDD.js} +1 -1
- package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-4A2EB76B.js} +1 -1
- package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-4CGUFKEP.js} +1 -1
- package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-HUEERWBA.js} +1 -1
- package/chunks/{monitor-M3PNLCYP.js → monitor-FXL5UNMP.js} +1 -1
- package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-W7M2O43W.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
- package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-R5RSLSSH.js} +1 -1
- package/chunks/{omni-6YBX4R6K.js → omni-DNZGITTE.js} +1 -1
- package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
- package/chunks/{pidfile-XR4JF2Z6.js → pidfile-5ZNJWMKG.js} +1 -1
- package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JIHQDASW.js} +1 -1
- package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
- package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
- package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-YUXOUQG4.js} +1 -1
- package/chunks/{read-file-VD7OFO2E.js → read-file-FBNU3AVX.js} +1 -1
- package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
- package/chunks/{review-C365WGCW.js → review-NLFYSNM3.js} +1 -1
- package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-JUAPC5LD.js} +1 -1
- package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
- package/chunks/{runtime-J6SPBSCS.js → runtime-D2QUYM6U.js} +1 -1
- package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-7VZJQV6H.js} +1 -1
- package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-PC6EH75E.js} +1 -1
- package/chunks/{scheduler-KCMSPHON.js → scheduler-RUV2FNDR.js} +1 -1
- package/chunks/{search-memory-EUBJ7IAV.js → search-memory-YJTJ7BRU.js} +1 -1
- package/chunks/{send-message-CWWZUPSK.js → send-message-EEEFFTHX.js} +1 -1
- package/chunks/{serve-4CB4BWJ5.js → serve-KMIZDYON.js} +1 -1
- package/chunks/{server-JNANUIGC.js → server-DUPK3V7B.js} +3 -3
- package/chunks/{session-3LQLXPUA.js → session-CW5YMFMP.js} +1 -1
- package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-5H5GFHLI.js} +1 -1
- package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
- package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-4UPONX4L.js} +1 -1
- package/chunks/{sessionService-U7ACD2HP.js → sessionService-GGCYISSL.js} +1 -1
- package/chunks/{settings-FTGWYTUH.js → settings-AASJCESS.js} +1 -1
- package/chunks/{shell-E4RENYQC.js → shell-V4WWLW3Q.js} +1 -1
- package/chunks/{skill-OLNPHRWB.js → skill-NDEBB7VX.js} +1 -1
- package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-YAI3GYU5.js} +1 -1
- package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-6JKVJAXZ.js} +1 -1
- package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-NJP5OCKJ.js} +1 -1
- package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-M4B4SXRM.js} +1 -1
- package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
- package/chunks/{team-create-HAVKHNU5.js → team-create-NLJ7QBLD.js} +1 -1
- package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-XKYPVWNG.js} +1 -1
- package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-47TD747D.js} +1 -1
- package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-AANEBPLJ.js} +1 -1
- package/chunks/{tool-call-LZHZ5RVH.js → tool-call-ETH3LS7Y.js} +1 -1
- package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-EFOEPAF2.js} +1 -1
- package/chunks/{tool-search-K6S3ON7M.js → tool-search-J3CF5PRN.js} +1 -1
- package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-3DC52PLQ.js} +1 -1
- package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-4KPWZZKB.js} +1 -1
- package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-A67BS7QS.js} +1 -1
- package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-X623JRSY.js} +1 -1
- package/chunks/{upload-config-TCCFCNCD.js → upload-config-X2CR3F26.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
- package/chunks/{version-JYWKKMNP.js → version-MFHRMM7W.js} +1 -1
- package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-3GEJ62DH.js} +1 -1
- package/chunks/{web-search-HAI5LW3G.js → web-search-WJZO3Q3A.js} +1 -1
- package/chunks/{workflow-BZ2YFGF6.js → workflow-ML7ITCMH.js} +1 -1
- package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
- package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-YFZMV7EF.js} +1 -1
- package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-3COKLBCI.js} +1 -1
- package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
- package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-F3AGIOBW.js} +1 -1
- package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-QUBL3RW6.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
- package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-UUENTHNO.js} +1 -1
- package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
- package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
- package/chunks/{write-file-HD5LHXGL.js → write-file-DEAFIK4C.js} +1 -1
- package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-YYO22PQG.js} +1 -1
- package/cli-entry.js +2 -3
- 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 +2 -12
- package/chunks/managed-npm-update-CTL6LH5Z.js +0 -8
- package/opentui-assets/@opentui/core/assets/javascript/highlights.scm +0 -205
- package/opentui-assets/@opentui/core/assets/javascript/tree-sitter-javascript.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/markdown/highlights.scm +0 -150
- package/opentui-assets/@opentui/core/assets/markdown/injections.scm +0 -27
- package/opentui-assets/@opentui/core/assets/markdown/tree-sitter-markdown.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/markdown_inline/highlights.scm +0 -115
- package/opentui-assets/@opentui/core/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/typescript/highlights.scm +0 -604
- package/opentui-assets/@opentui/core/assets/typescript/tree-sitter-typescript.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/zig/highlights.scm +0 -284
- package/opentui-assets/@opentui/core/assets/zig/tree-sitter-zig.wasm +0 -0
- package/opentui-assets/@opentui/core/parser.worker.js +0 -4566
- package/opentui-assets/@opentui/core-darwin-arm64/libopentui.dylib +0 -0
- package/opentui-assets/@opentui/core-darwin-x64/libopentui.dylib +0 -0
- package/opentui-assets/@opentui/core-linux-arm64/libopentui.so +0 -0
- package/opentui-assets/@opentui/core-linux-x64/libopentui.so +0 -0
- package/opentui-assets/web-tree-sitter/tree-sitter.wasm +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{buildModelReasoningRoutePreview}from"./chunk-4XF4ZGJG.js";import{snapshotProcessEnv}from"./chunk-DWPCE3QI.js";import{publicAuxModelSelectorValue}from"./chunk-L42NTHIT.js";import{getModelConfigurationKey}from"./chunk-
|
|
3
|
+
import{buildModelReasoningRoutePreview}from"./chunk-4XF4ZGJG.js";import{snapshotProcessEnv}from"./chunk-DWPCE3QI.js";import{publicAuxModelSelectorValue}from"./chunk-L42NTHIT.js";import{getModelConfigurationKey}from"./chunk-Z32URWBG.js";import{STATUS_SCHEMA_VERSION}from"./chunk-LUDNUVSA.js";import{getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-DVC65H4X.js";import{ACP_ROUTE_ID_PREFIX,buildAcpModelOptions,getCurrentAcpModelId,parseAcpBaseModelId,sanitizeProviderBaseUrl}from"./chunk-GT4TCQ3R.js";import{loadSettings}from"./chunk-EZPM4DLR.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ModelsConfig,captureReasoningSnapshot,resolveReasoningForModel}from"./chunk-ET2Z7ZGF.js";import{tokenLimit}from"./chunk-GOR7FFVE.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("WORKSPACE_PROVIDERS_STATUS");function createWorkspaceProvidersStatusProvider(options={}){return async(workspaceCwd,acpChannelLive)=>buildWorkspaceProvidersStatus(workspaceCwd,acpChannelLive,options)}__name(createWorkspaceProvidersStatusProvider,"createWorkspaceProvidersStatusProvider");function buildWorkspaceProvidersStatus(workspaceCwd,acpChannelLive,options){try{const loaded=loadSettings(workspaceCwd,options.env?{skipLoadEnvironment:true,skipWorkspaceSettings:options.workspaceTrusted===false,workspaceTrusted:options.workspaceTrusted}:{consumeCorruptionEnvVars:true,skipLoadEnvironment:options.workspaceTrusted===false,skipWorkspaceSettings:options.workspaceTrusted===false,workspaceTrusted:options.workspaceTrusted});const settings=loaded.merged;const env=options.env??snapshotProcessEnv();const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);const argv={model:options.argv?.model,openaiApiKey:options.argv?.openaiApiKey,openaiBaseUrl:options.argv?.openaiBaseUrl,openaiLogging:options.argv?.openaiLogging,openaiLoggingDir:options.argv?.openaiLoggingDir};const resolvedCliConfig=resolveCliGenerationConfig({argv,settings,selectedAuthType,env});const modelsConfig=new ModelsConfig({initialAuthType:resolvedCliConfig.authType,modelProvidersConfig:settings.modelProviders,providerProtocolConfig:settings.providerProtocol,generationConfig:resolvedCliConfig.generationConfig,generationConfigSources:resolvedCliConfig.sources});const currentAuth=resolvedCliConfig.authType;const currentModelId=(resolvedCliConfig.model||modelsConfig.getModel()||"").trim();const hasCurrentModel=currentModelId.length>0;const modelCameFromSettings=!argv.model&&settings.model?.name?.trim()===currentModelId;const currentBaseUrl=modelCameFromSettings&&settings.model?.baseUrl!==void 0?settings.model.baseUrl||void 0:resolvedCliConfig.sources["baseUrl"]?resolvedCliConfig.baseUrl||void 0:void 0;const currentRegistryBaseUrl=modelCameFromSettings&¤tAuth?settings.model?.baseUrl!==void 0?settings.model.baseUrl||null:modelsConfig.getResolvedModel(currentAuth,currentModelId)?.registryBaseUrl??null:void 0;const models=modelsConfig.getAllConfiguredModels();const modelOptions=buildAcpModelOptions(models);const reasoningSnapshot=captureReasoningSnapshot(models);const currentAcpModelId=hasCurrentModel?getCurrentAcpModelId(modelOptions,currentModelId,currentAuth,currentRegistryBaseUrl):void 0;const fastModelId=typeof settings.fastModel==="string"&&settings.fastModel.length>0?settings.fastModel:void 0;const visionModelId=typeof settings.visionModel==="string"&&settings.visionModel.length>0?settings.visionModel:void 0;const approvalMode=resolveApprovalMode(settings);const providers=new Map;for(const option of modelOptions){const{model,effectiveModelId,modelId}=option;if(model.isRuntimeModel)continue;const authType=String(model.authType);let provider=providers.get(authType);if(!provider){provider={kind:"model_provider",status:"ok",authType,current:false,models:[]};providers.set(authType,provider)}const isCurrent=currentAuth===model.authType&¤tAcpModelId===modelId;const resolved=modelsConfig.getResolvedModel(model.authType,model.id,model.registryBaseUrl);const generation={...resolved?.generationConfig,model:model.id,authType:model.authType,baseUrl:resolved?.baseUrl,reasoningSnapshot,reasoningRouteBaseUrl:model.registryBaseUrl??null};const configOptions=buildModelReasoningRoutePreview(generation,resolveReasoningForModel(void 0,generation),settings.model?.reasoningEffort,modelId.startsWith(ACP_ROUTE_ID_PREFIX));const configurationKey=getModelConfigurationKey(loaded,authType,model.id,model.registryBaseUrl);const providerModel={...configurationKey?{configurationKey}:{},modelId,baseModelId:parseAcpBaseModelId(effectiveModelId),name:model.label,...model.description!==void 0?{description:model.description}:{},contextLimit:model.contextWindowSize!==void 0&&model.contextWindowSize>0?model.contextWindowSize:tokenLimit(effectiveModelId),...model.modalities!==void 0?{modalities:model.modalities}:{},...model.baseUrl!==void 0?{baseUrl:sanitizeProviderBaseUrl(model.baseUrl)}:{},...model.envKey!==void 0?{envKey:model.envKey}:{},isCurrent,isRuntime:false,...configOptions?{configOptions}:{}};provider.models.push(providerModel);if(isCurrent)provider.current=true}const current=buildCurrent(currentAuth,currentAcpModelId,currentBaseUrl,fastModelId,visionModelId);return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:true,acpChannelLive,...current?{current}:{},approvalMode,providers:[...providers.values()],...resolvedCliConfig.warnings.length>0?{errors:resolvedCliConfig.warnings.map(warning=>({kind:"providers",status:"warning",error:sanitizeProviderWarning(warning)}))}:{}}}catch(error){return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:false,acpChannelLive,providers:[],errors:[{kind:"providers",status:"error",error:sanitizeProviderWarning(error instanceof Error?error.message:String(error))}]}}}__name(buildWorkspaceProvidersStatus,"buildWorkspaceProvidersStatus");function resolveApprovalMode(settings){const value=settings.tools?.approvalMode;if(typeof value!=="string")return"auto";const normalized=value.trim().toLowerCase().replaceAll("_","-");const mode=normalized==="autoedit"?"auto-edit":normalized;if(APPROVAL_MODES.includes(mode)){return mode}if(value.trim().length>0){debugLogger.warn(`[workspace-providers-status] unrecognized approvalMode "${value}", falling back to auto`)}return"auto"}__name(resolveApprovalMode,"resolveApprovalMode");var URL_LIKE_PATTERN=/\b[A-Za-z][A-Za-z\d+.-]*:\/\/[^\s'"`<>]+/g;var URL_START_PATTERN=/\b[A-Za-z][A-Za-z\d+.-]*:\/\//g;function sanitizeProviderWarning(warning){let result="";let index=0;let next=findNextUrlStart(warning,index);while(next){result+=warning.slice(index,next.index);const segmentEnd=findUrlSegmentEnd(warning,next.index,next.marker);const segment=warning.slice(next.index,segmentEnd);result+=sanitizeProviderWarningSegment(segment,next.marker.length);index=segmentEnd;next=findNextUrlStart(warning,index)}return result+warning.slice(index)}__name(sanitizeProviderWarning,"sanitizeProviderWarning");function findNextUrlStart(value,from){URL_START_PATTERN.lastIndex=from;const match=URL_START_PATTERN.exec(value);return match?{index:match.index,marker:match[0]}:void 0}__name(findNextUrlStart,"findNextUrlStart");function findUrlSegmentEnd(value,start,marker){const afterMarker=start+marker.length;const carriageReturn=value.indexOf("\r",afterMarker);const lineFeed=value.indexOf("\n",afterMarker);let lineEnd=value.length;if(carriageReturn!==-1)lineEnd=Math.min(lineEnd,carriageReturn);if(lineFeed!==-1)lineEnd=Math.min(lineEnd,lineFeed);const nextUrl=findNextUrlStart(value,afterMarker);return Math.min(lineEnd,nextUrl?.index??value.length)}__name(findUrlSegmentEnd,"findUrlSegmentEnd");function sanitizeProviderWarningSegment(segment,markerLength){const at=segment.indexOf("@",markerLength);if(at!==-1&&hasCredentialPrefix(segment,markerLength,at)&&segment[at+1]!==void 0&&/[A-Za-z0-9.[\]-]/.test(segment[at+1])){return`${segment.slice(0,markerLength)}${segment.slice(at+1)}`}return segment.replace(URL_LIKE_PATTERN,url=>sanitizeProviderBaseUrl(url))}__name(sanitizeProviderWarningSegment,"sanitizeProviderWarningSegment");function hasCredentialPrefix(segment,markerLength,at){const colon=segment.indexOf(":",markerLength);if(colon===-1||colon>at)return false;const username=segment.slice(markerLength,colon);return!/[/?#\s'"`<>]/.test(username)}__name(hasCredentialPrefix,"hasCredentialPrefix");function buildCurrent(authType,modelId,baseUrl,fastModelId,visionModelId){if(!authType&&!modelId&&!baseUrl&&!fastModelId&&!visionModelId)return void 0;return{...authType?{authType:String(authType)}:{},...modelId?{modelId}:{},...baseUrl?{baseUrl:sanitizeProviderBaseUrl(baseUrl)}:{},...fastModelId?{fastModelId:publicAuxModelSelectorValue(fastModelId)}:{},...visionModelId?{visionModelId:publicAuxModelSelectorValue(visionModelId)}:{}}}__name(buildCurrent,"buildCurrent");export{createWorkspaceProvidersStatusProvider};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{LoadedSettings,getNestedProperty,getPersistScopeForModelSelection}from"./chunk-
|
|
3
|
+
import{LoadedSettings,getNestedProperty,getPersistScopeForModelSelection}from"./chunk-EZPM4DLR.js";import{getHomeEnvFallbackVars}from"./chunk-ZO4F6ZWR.js";import{writeWithBackupSync}from"./chunk-4CE4GMDL.js";import{preserveModelProviderPlaceholders}from"./chunk-G2LTZU67.js";import{resolveEnvVarsInObject}from"./chunk-ZOTKZI2P.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs";function findRawModelProviderEntries(settings,providerId){return["System",...settings.isTrusted?["Workspace"]:[],"User","SystemDefaults"].map(source=>settings.forScope(source).originalSettings.modelProviders).find(providers=>providers&&Object.hasOwn(providers,providerId))?.[providerId]}__name(findRawModelProviderEntries,"findRawModelProviderEntries");function getRawModelProviders(settings){return Object.fromEntries(Object.keys(settings.merged.modelProviders??{}).map(providerId=>[providerId,findRawModelProviderEntries(settings,providerId)??[]]))}__name(getRawModelProviders,"getRawModelProviders");function createLoadedSettingsAdapter(settings,scope){const persistScope=scope??getPersistScopeForModelSelection(settings);const settingsFile=settings.forScope(persistScope);let fileSnapshot;let settingsSnapshot=null;let originalSnapshot=null;return{getValue(key){return getNestedProperty(settings.merged,key)},setValue(key,value){for(const part of key.split(".")){if(part==="__proto__"||part==="constructor"||part==="prototype"){throw new Error(`Refusing to write settings key with reserved segment: ${key}`)}}const provider=key.startsWith("modelProviders.")&&key.split(".").length===2?key.slice("modelProviders.".length):void 0;if(!provider||!Array.isArray(value)){settings.setValue(persistScope,key,value);return}const sourceFor=__name(providerId=>findRawModelProviderEntries(settings,providerId),"sourceFor");const ownsBucket=Object.hasOwn(settingsFile.settings.modelProviders??{},provider);const previous=ownsBucket?settingsFile.settings.modelProviders?.[provider]:settings.merged.modelProviders?.[provider];const raw=ownsBucket?settingsFile.originalSettings.modelProviders?.[provider]:sourceFor(provider);const resolvedProviders=provider==="openai"?settings.merged.modelProviders??{}:{[provider]:previous??[]};const rawProviders=provider==="openai"?Object.fromEntries(Object.keys(resolvedProviders).map(id=>[id,sourceFor(id)??[]])):{[provider]:raw??[]};const persisted=preserveModelProviderPlaceholders(value,provider,resolvedProviders,rawProviders,settings.merged.providerProtocol);settings.setValue(persistScope,key,persisted);settingsFile.settings.modelProviders=resolveEnvVarsInObject(settingsFile.originalSettings.modelProviders,getHomeEnvFallbackVars());settings.recomputeMerged()},getModelProviders(){return settings.merged.modelProviders??{}},getModelProvidersForWrite(){const ownProviders=settingsFile.settings.modelProviders??{};const writeView=persistScope==="User"?new LoadedSettings(settings.system,settings.systemDefaults,settings.user,{...settings.workspace,settings:{},originalSettings:{}},false,new Set).merged:settings.merged;return{modelProviders:ownProviders,providerProtocol:writeView.providerProtocol,shadowedProviders:Object.keys(ownProviders).filter(providerId=>["System",...settings.isTrusted?["Workspace"]:[],"User","SystemDefaults"].find(scope2=>Object.hasOwn(settings.forScope(scope2).originalSettings.modelProviders??{},providerId))!==persistScope)}},persist(){},backup(){const contents=fs.existsSync(settingsFile.path)?fs.readFileSync(settingsFile.path,"utf8"):null;settingsSnapshot=structuredClone(settingsFile.settings);originalSnapshot=structuredClone(settingsFile.originalSettings);fileSnapshot=contents},restore(){if(fileSnapshot===void 0)return;try{if(fileSnapshot===null){fs.rmSync(settingsFile.path,{force:true})}else{writeWithBackupSync(settingsFile.path,fileSnapshot)}}finally{if(settingsSnapshot!==null){settingsFile.settings=settingsSnapshot}if(originalSnapshot!==null){settingsFile.originalSettings=originalSnapshot}settings.recomputeMerged()}},cleanupBackup(){fileSnapshot=void 0;settingsSnapshot=null;originalSnapshot=null}}}__name(createLoadedSettingsAdapter,"createLoadedSettingsAdapter");export{findRawModelProviderEntries,getRawModelProviders,createLoadedSettingsAdapter};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{getGitVersion,getNpmVersion}from"./chunk-
|
|
3
|
+
import{getGitVersion,getNpmVersion}from"./chunk-DVJSDCMX.js";import{buildEnvStatusFromEnv,snapshotProcessEnv}from"./chunk-DWPCE3QI.js";import{mapDomainErrorToErrorKind}from"./chunk-LUDNUVSA.js";import{canUseRipgrep}from"./chunk-QZV4PFQK.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{promises as fs}from"node:fs";var REQUIRED_NODE_MAJOR=22;function createDaemonStatusProvider(options={}){const readEnv=__name(()=>options.env??snapshotProcessEnv(),"readEnv");return{async getEnvStatus(boundWorkspace,acpChannelLive){return buildEnvStatusFromEnv(boundWorkspace,acpChannelLive,readEnv())},async getDaemonPreflightCells(boundWorkspace){return buildDaemonPreflightCells(boundWorkspace,readEnv())}}}__name(createDaemonStatusProvider,"createDaemonStatusProvider");async function buildDaemonPreflightCells(boundWorkspace,env){const nodeVersionCell=__name(()=>{try{const nodeVersion=process.versions.node;const major=Number.parseInt(nodeVersion.split(".")[0]??"0",10);if(Number.isFinite(major)&&major>=REQUIRED_NODE_MAJOR){return{kind:"node_version",status:"ok",locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}return{kind:"node_version",status:"error",errorKind:"missing_binary",error:`Node ${nodeVersion} is below the required >=${REQUIRED_NODE_MAJOR}.`,hint:`Upgrade Node to v${REQUIRED_NODE_MAJOR} or newer.`,locality:"daemon",detail:{version:nodeVersion,required:`>=${REQUIRED_NODE_MAJOR}`}}}catch(err){return{kind:"node_version",status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon"}}},"nodeVersionCell");const cliEntryCell=__name(()=>{const cliEntry=env["QWEN_CLI_ENTRY"]||process.argv[1]||"";if(cliEntry){return{kind:"cli_entry",status:"ok",locality:"daemon",detail:{path:cliEntry,source:env["QWEN_CLI_ENTRY"]?"QWEN_CLI_ENTRY":"process.argv[1]"}}}return{kind:"cli_entry",status:"error",errorKind:"missing_binary",error:"Cannot determine CLI entry path for spawning the ACP child.",hint:"Set QWEN_CLI_ENTRY to the absolute path of the qwen entry script.",locality:"daemon"}},"cliEntryCell");const workspaceDirCell=__name(async()=>{try{const stat=await fs.stat(boundWorkspace);if(stat.isDirectory()){return{kind:"workspace_dir",status:"ok",locality:"daemon",detail:{path:boundWorkspace}}}return{kind:"workspace_dir",status:"error",errorKind:"missing_file",error:`Bound workspace path is not a directory: ${boundWorkspace}`,locality:"daemon",detail:{path:boundWorkspace}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind:"workspace_dir",status:"error",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{},locality:"daemon",detail:{path:boundWorkspace}}}},"workspaceDirCell");const slots=[{kind:"node_version",run:nodeVersionCell},{kind:"cli_entry",run:cliEntryCell},{kind:"workspace_dir",run:workspaceDirCell},{kind:"ripgrep",run:__name(()=>safeCheck("ripgrep",async()=>{const ok=await canUseRipgrep(true);return ok?{status:"ok"}:{status:"warning",hint:"Install ripgrep for faster grep tool execution."}}),"run")},{kind:"git",run:__name(()=>safeCheck("git",async()=>{const v=await getGitVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"git not found on PATH."}}),"run")},{kind:"npm",run:__name(()=>safeCheck("npm",async()=>{const v=await getNpmVersion();return v&&v!=="unknown"?{status:"ok",detail:{version:v}}:{status:"warning",hint:"npm not found on PATH."}}),"run")}];const settled=await Promise.allSettled(slots.map(s=>Promise.resolve().then(s.run)));return settled.map((result,i)=>{if(result.status==="fulfilled")return result.value;const err=result.reason;const errorKind=mapDomainErrorToErrorKind(err);return{kind:slots[i].kind,status:"error",locality:"daemon",error:err instanceof Error?err.message:String(err),...errorKind?{errorKind}:{}}})}__name(buildDaemonPreflightCells,"buildDaemonPreflightCells");async function safeCheck(kind,body){try{const r=await body();return{kind,status:r.status,locality:"daemon",...r.detail?{detail:r.detail}:{},...r.hint?{hint:r.hint}:{}}}catch(err){const errorKind=mapDomainErrorToErrorKind(err);return{kind,status:"error",error:err instanceof Error?err.message:String(err),locality:"daemon",...errorKind?{errorKind}:{}}}}__name(safeCheck,"safeCheck");export{createDaemonStatusProvider};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{runExitCleanup}from"./chunk-
|
|
3
|
+
import{runExitCleanup}from"./chunk-EQOHDAYU.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var RELAUNCH_EXIT_CODE=42;var UPDATE_RELAUNCH_EXIT_CODE=43;var UPDATE_COMPLETE_EXIT_CODE=44;var SKIP_UPDATE_CHECK_ENV_VAR="QWEN_CODE_SKIP_UPDATE_CHECK_ONCE";var CUSTOM_SANDBOX_IMAGE_ENV_VAR="QWEN_CODE_CUSTOM_SANDBOX_IMAGE";var HOST_UPDATE_RELAUNCH_ENV_VAR="QWEN_CODE_HOST_UPDATE_RELAUNCH";var UPDATE_ON_EXIT_MESSAGE="qwen-code:update-on-exit";var inProcessUpdateRelaunch;var supervisedInProcess=false;var updateOnExitRequested=false;var updatingOnExit=false;function superviseInProcess(onUpdateRelaunch){supervisedInProcess=true;inProcessUpdateRelaunch=onUpdateRelaunch}__name(superviseInProcess,"superviseInProcess");function getRelaunchExecArgv(){const needsExposeGc=typeof globalThis.gc==="function"&&!process.execArgv.includes("--expose-gc");return needsExposeGc?[...process.execArgv,"--expose-gc"]:[...process.execArgv]}__name(getRelaunchExecArgv,"getRelaunchExecArgv");async function relaunchApp(){await runExitCleanup();const proc=process;if(supervisedInProcess&&proc.execve){proc.execve(process.execPath,[process.execPath,...getRelaunchExecArgv(),...process.argv.slice(1)])}process.exit(RELAUNCH_EXIT_CODE)}__name(relaunchApp,"relaunchApp");async function exitCleanly(code){if(updatingOnExit)return new Promise(()=>{});if(code===0&&updateOnExitRequested&&inProcessUpdateRelaunch){updateOnExitRequested=false;updatingOnExit=true;try{code=await inProcessUpdateRelaunch(false)}catch{code=1}}process.exit(code)}__name(exitCleanly,"exitCleanly");async function relaunchForUpdate(){await runExitCleanup();if(inProcessUpdateRelaunch){process.exit(await inProcessUpdateRelaunch(true))}process.exit(UPDATE_RELAUNCH_EXIT_CODE)}__name(relaunchForUpdate,"relaunchForUpdate");function requestUpdateOnExit(){if(inProcessUpdateRelaunch){updateOnExitRequested=true;return true}if(!process.send)return false;try{process.send({type:UPDATE_ON_EXIT_MESSAGE});return true}catch{return false}}__name(requestUpdateOnExit,"requestUpdateOnExit");export{RELAUNCH_EXIT_CODE,UPDATE_RELAUNCH_EXIT_CODE,UPDATE_COMPLETE_EXIT_CODE,SKIP_UPDATE_CHECK_ENV_VAR,CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,UPDATE_ON_EXIT_MESSAGE,superviseInProcess,getRelaunchExecArgv,relaunchApp,exitCleanly,relaunchForUpdate,requestUpdateOnExit};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-U3Q72OGV.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-UJP2MPBI.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-AKWYMQKU.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-2JGTWRZJ.js";import{backgroundFixHolding}from"./chunk-YVD4O5ZB.js";import{getCurrentAgentId}from"./chunk-YZFNBUKG.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-ZWPSBU7K.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-KVA6DHHF.js";import{fileExists,getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=buildWorkspaceArtifactCandidate(this.config,file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, office documents, CSV, Markdown, JSON, SQL, and Python files are automatically registered as session artifacts. Set record_as_artifact=false for intermediates, such as HTML written only to print a PDF: that does not create an artifact, but one the session already has for the path is still refreshed. Files under .qwen/tmp/ are not registered. Delete intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
|
|
3
|
+
import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-LKPMADUO.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-UJP2MPBI.js";import{buildWorkspaceArtifactCandidate,formatRecordArtifactReminder}from"./chunk-AKWYMQKU.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-7XQ5D34E.js";import{backgroundFixHolding}from"./chunk-YVD4O5ZB.js";import{getCurrentAgentId}from"./chunk-YZFNBUKG.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-ZWPSBU7K.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-KVA6DHHF.js";import{fileExists,getSpecificMimeType}from"./chunk-Y6HHV4LC.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}requiresUserInteraction(){return backgroundFixHolding(this.params.file_path,getCurrentAgentId())!==void 0}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=buildWorkspaceArtifactCandidate(this.config,file_path,{recordAsArtifact:this.params.record_as_artifact,sizeBytes:postWriteSizeBytes});if(artifact&&!artifact.updateOnly){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, office documents, CSV, Markdown, JSON, SQL, and Python files are automatically registered as session artifacts. Set record_as_artifact=false for intermediates, such as HTML written only to print a PDF: that does not create an artifact, but one the session already has for the path is still refreshed. Files under .qwen/tmp/ are not registered. Delete intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
|
|
4
4
|
|
|
5
5
|
${WRITE_FILE_ARTIFACT_DESCRIPTION}
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-26MNTKT2.js";import{t}from"./chunk-NO7VTKRL.js";import{So}from"./chunk-2JGTWRZJ.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
|
|
3
|
+
import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{require_semver}from"./chunk-YZUKMJW7.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-26MNTKT2.js";import{t}from"./chunk-NO7VTKRL.js";import{So}from"./chunk-7XQ5D34E.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
|
|
4
4
|
Original error: ${promoteErr.message}
|
|
5
5
|
Rollback error: ${rollbackErr.message}
|
|
6
6
|
Manual recovery: mv "${oldDir}" "${standaloneDir}"`;throw new Error(detail)}throw promoteErr}return"done"}}__name(atomicReplace,"atomicReplace");function ensureBinWrapper(standaloneDir,target,runtime="node"){const binDir=path.join(path.dirname(standaloneDir),"..","bin");const artifacts={wrapperCreated:false};const{launcher,interpreter,entryPoint}=standaloneRuntimePaths(standaloneDir,target,runtime);const hasLauncher=fs.existsSync(launcher);try{fs.mkdirSync(binDir,{recursive:true});if(target.startsWith("win")){if(UNSAFE_CMD_CHARS.test(standaloneDir)){throw new Error("standaloneDir contains characters unsafe for cmd.exe wrapper")}const wrapperPath=path.join(binDir,"qwen.cmd");artifacts.wrapperPath=wrapperPath;const content=hasLauncher?`@echo off\r
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-KZNYALFU.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-XFMPZINJ.js";import{runStartupRecoveryOnce}from"./chunk-HN5UYLPU.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-HTW7PYHK.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-ZBHL2CXR.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-NIOS3B3V.js";import{isOmniDeliveryActive}from"./chunk-OBV7RNHV.js";import{requireEffectiveOmniUploadConfig}from"./chunk-XZTE4YTN.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{isPermittedRedirect,isPrivateHost,resolveNetworkTarget}from"./chunk-5CWTKFI4.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-Q6UAOTP3.js";import{detectRuntime,loadUndici}from"./chunk-ZZZAYAJW.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
|
|
3
|
+
import{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-QF22ILPV.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-XFMPZINJ.js";import{runStartupRecoveryOnce}from"./chunk-HN5UYLPU.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-HTW7PYHK.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-YFTVFH2A.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-ZBHL2CXR.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-NIOS3B3V.js";import{isOmniDeliveryActive}from"./chunk-OBV7RNHV.js";import{requireEffectiveOmniUploadConfig}from"./chunk-XZTE4YTN.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{isPermittedRedirect,isPrivateHost,resolveNetworkTarget}from"./chunk-5CWTKFI4.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-Q6UAOTP3.js";import{detectRuntime,loadUndici}from"./chunk-ZZZAYAJW.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{isAbortError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|