@hostclubeos/miraos 0.0.7-beta → 0.0.9-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/{MaxSizedBox-CBUPHLMW.js → MaxSizedBox-6CGCRBRO.js} +1 -1
- package/chunks/{StandaloneSessionPicker-EXZJQKTK.js → StandaloneSessionPicker-7VQOS4TU.js} +1 -1
- package/chunks/{acp-subagent-executor-BMIXP52W.js → acp-subagent-executor-BFQRCU7R.js} +1 -1
- package/chunks/{acpAgent-JC4KGTLW.js → acpAgent-PCXQRPNU.js} +3 -3
- package/chunks/{advisor-5RUG3VFZ.js → advisor-WDZ5N5ZP.js} +1 -1
- package/chunks/{agent-SGQ7AEZI.js → agent-I7Q3IPSS.js} +1 -1
- package/chunks/{agent-headless-ZGCZ2DA7.js → agent-headless-6LOYWI5T.js} +1 -1
- package/chunks/{agent-host-client-HY5GPSHM.js → agent-host-client-PZZKCNQF.js} +1 -1
- package/chunks/{agent-host-connections-KGTBS37X.js → agent-host-connections-TWWSRTKJ.js} +1 -1
- package/chunks/{autofix-pr-E62FC67X.js → autofix-pr-RQPGPQ4D.js} +1 -1
- package/chunks/{batch-OUC6FGCQ.js → batch-UJD5TSBN.js} +1 -1
- package/chunks/{bridge-FLEIBB5V.js → bridge-4TYLRPXZ.js} +1 -1
- package/chunks/{channel-settings-store-QG6HREVH.js → channel-settings-store-RENJMOQ5.js} +1 -1
- package/chunks/{chunk-K7VOBDFT.js → chunk-24PHAWM3.js} +1 -1
- package/chunks/{chunk-7F5IYTVE.js → chunk-26JPBN6V.js} +1 -1
- package/chunks/{chunk-V5Z6OEKJ.js → chunk-2MQH3J4U.js} +1 -1
- package/chunks/{chunk-UOYXBAN7.js → chunk-2RXOWQSQ.js} +1 -1
- package/chunks/{chunk-H2QXWIRZ.js → chunk-323HUW2T.js} +1 -1
- package/chunks/{chunk-KNW2OD46.js → chunk-3BHXE7CB.js} +1 -1
- package/chunks/{chunk-RWFOQXPU.js → chunk-3GYAEXAA.js} +1 -1
- package/chunks/{chunk-W6IOHGWW.js → chunk-3YBZW4HP.js} +1 -1
- package/chunks/{chunk-23543L6E.js → chunk-4RJ2RRGZ.js} +1 -1
- package/chunks/{chunk-2PB6TEZU.js → chunk-5DIW4X4P.js} +1 -1
- package/chunks/{chunk-4346FNTB.js → chunk-5GB6JNJX.js} +1 -1
- package/chunks/{chunk-VRAHMOQQ.js → chunk-5HSNCG73.js} +2 -2
- package/chunks/{chunk-PQOQONLN.js → chunk-6HDMM7TJ.js} +1 -1
- package/chunks/{chunk-K7KY7FIB.js → chunk-6STNGEYC.js} +1 -1
- package/chunks/{chunk-7VP4KALB.js → chunk-7EFWNFJJ.js} +1 -1
- package/chunks/{chunk-ATVRF62A.js → chunk-7EWIKIJI.js} +1 -1
- package/chunks/{chunk-T5PDEAU5.js → chunk-7TB6VG72.js} +1 -1
- package/chunks/{chunk-4WYKHP7Q.js → chunk-7TLL4JLR.js} +1 -1
- package/chunks/{chunk-JDABSS6M.js → chunk-AOMXZNMX.js} +1 -1
- package/chunks/{chunk-FK5L2WVV.js → chunk-AUM57JI2.js} +1 -1
- package/chunks/{chunk-KK6SQPYG.js → chunk-AW5UCOZO.js} +1 -1
- package/chunks/{chunk-WC72OWF2.js → chunk-C6HVNDQT.js} +2 -2
- package/chunks/{chunk-BSLIVO6O.js → chunk-CC6E5CQV.js} +1 -1
- package/chunks/{chunk-AIAYQAPA.js → chunk-CLKUQP27.js} +1 -1
- package/chunks/{chunk-2QYFSBJY.js → chunk-DFMQQM4M.js} +1 -1
- package/chunks/{chunk-MMGNOY3U.js → chunk-DP7LJTG2.js} +5 -5
- package/chunks/{chunk-MYS5NQXO.js → chunk-DQT5VL7G.js} +1 -1
- package/chunks/{chunk-FC7SJIAS.js → chunk-E4QOAV5O.js} +1 -1
- package/chunks/{chunk-3MBYQYPC.js → chunk-E4REGDEZ.js} +1 -1
- package/chunks/{chunk-WCLAVBNR.js → chunk-EAG7VZJJ.js} +1 -1
- package/chunks/{chunk-GQ24VFGQ.js → chunk-EFO6J22W.js} +1 -1
- package/chunks/{chunk-6RDYPRV6.js → chunk-EMR4QK2F.js} +1 -1
- package/chunks/{chunk-WZTO3EYG.js → chunk-EYECE2PH.js} +1 -1
- package/chunks/{chunk-UWMLSAQY.js → chunk-EZDXHUHB.js} +1 -1
- package/chunks/{chunk-T3A53XMM.js → chunk-FJFTKA4H.js} +1 -1
- package/chunks/{chunk-W2ZVZ6LS.js → chunk-FSLDNLNU.js} +1 -1
- package/chunks/{chunk-O6Z3KO6R.js → chunk-FSRXTX3N.js} +1 -1
- package/chunks/{chunk-TFITRCIC.js → chunk-FWSXFRIQ.js} +1 -1
- package/chunks/{chunk-TU5QHOJC.js → chunk-G4ATLMDH.js} +1 -1
- package/chunks/{chunk-DF6TBGS2.js → chunk-GAS3HKRX.js} +1 -1
- package/chunks/{chunk-YVN32EUM.js → chunk-GFFL2LR2.js} +1 -1
- package/chunks/{chunk-TLZM3DMY.js → chunk-GYFIY7TD.js} +1 -1
- package/chunks/{chunk-PGKFDR73.js → chunk-GYXRI4P5.js} +1 -1
- package/chunks/{chunk-3KFLO5W3.js → chunk-H3U7DXIU.js} +1 -1
- package/chunks/{chunk-YN6WXB6B.js → chunk-HEDVPRMD.js} +1 -1
- package/chunks/{chunk-JJDF5FHA.js → chunk-HI3644FQ.js} +1 -1
- package/chunks/{chunk-HASJX2YS.js → chunk-HTHYLMBO.js} +1 -1
- package/chunks/{chunk-4MGTY3CJ.js → chunk-IW7RPDV2.js} +1 -1
- package/chunks/{chunk-SCHCTQCG.js → chunk-IXQI4K6O.js} +1 -1
- package/chunks/chunk-IYH3IZL4.js +13 -0
- package/chunks/{chunk-EF3HUB7S.js → chunk-J52J35K4.js} +1 -1
- package/chunks/{chunk-TXL535SJ.js → chunk-J7L5IHLG.js} +1 -1
- package/chunks/{chunk-N7WQH6L4.js → chunk-JHS5B4N7.js} +2 -2
- package/chunks/{chunk-P5543CFV.js → chunk-JRSO5ZGU.js} +1 -1
- package/chunks/{chunk-G35E5UB3.js → chunk-JS6VAGRQ.js} +1 -1
- package/chunks/{chunk-Z4JY3HGO.js → chunk-KAFPULGU.js} +1 -1
- package/chunks/{chunk-RNPVWQ3V.js → chunk-LDP47G5M.js} +1 -1
- package/chunks/{chunk-EW3EVEYN.js → chunk-LMZZWPKA.js} +1 -1
- package/chunks/{chunk-5RYDKYIR.js → chunk-LNCELICB.js} +1 -1
- package/chunks/{chunk-JDHMSERR.js → chunk-LY2DRNTZ.js} +1 -1
- package/chunks/{chunk-7W5DOBKY.js → chunk-MMGGGYSJ.js} +1 -1
- package/chunks/{chunk-CUY6CVSL.js → chunk-MTBU2ZIM.js} +1 -1
- package/chunks/{chunk-TWJ4XBED.js → chunk-N27KICJQ.js} +1 -1
- package/chunks/{chunk-JQOLNQQN.js → chunk-NHYFTK4O.js} +1 -1
- package/chunks/{chunk-NGH27AWP.js → chunk-NRDHXSEE.js} +1 -1
- package/chunks/{chunk-3GJ56V2J.js → chunk-NV5VVTYQ.js} +1 -1
- package/chunks/{chunk-VJUTDS6C.js → chunk-OEDMFKZL.js} +1 -1
- package/chunks/{chunk-PVHBBTAU.js → chunk-OQAVMR6K.js} +1 -1
- package/chunks/{chunk-IF3SWUYT.js → chunk-OY3Y6EMV.js} +1 -1
- package/chunks/{chunk-SOCXRMZM.js → chunk-OZL4ZMGQ.js} +2 -2
- package/chunks/{chunk-GLQWA4W2.js → chunk-PKSPKVFH.js} +1 -1
- package/chunks/{chunk-KYK53GFP.js → chunk-PNFKCYZT.js} +1 -1
- package/chunks/{chunk-7SAR6NXA.js → chunk-PTWHFVGG.js} +2 -2
- package/chunks/{chunk-RBA3TP7L.js → chunk-QJ6ZTZFC.js} +1 -1
- package/chunks/{chunk-PFECH6U6.js → chunk-QRGWB7IX.js} +1 -1
- package/chunks/{chunk-VBJV7T47.js → chunk-QRP2GXQD.js} +1 -1
- package/chunks/{chunk-WJLHLFIR.js → chunk-RES5ET63.js} +1 -1
- package/chunks/{chunk-GY4ID3EB.js → chunk-ROSJCTWB.js} +1 -1
- package/chunks/{chunk-4KIFAVR2.js → chunk-RR3NFNWL.js} +1 -1
- package/chunks/{chunk-2ZWVSKPK.js → chunk-RYQDRFLW.js} +1 -1
- package/chunks/{chunk-NVD63O5H.js → chunk-S7CWSAUQ.js} +1 -1
- package/chunks/{chunk-66DZADDA.js → chunk-SAJKF4WS.js} +1 -1
- package/chunks/chunk-SINRWOVD.js +36 -0
- package/chunks/{chunk-HSN5QUS7.js → chunk-SJNQ6I23.js} +1 -1
- package/chunks/{chunk-3NB3FFLR.js → chunk-T2GM4S4G.js} +3 -3
- package/chunks/{chunk-GN7ODRDE.js → chunk-TCQJO42E.js} +1 -1
- package/chunks/{chunk-67PM7M5R.js → chunk-TIIDF23U.js} +2 -2
- package/chunks/{chunk-USR2Y7B3.js → chunk-TKH5R7RZ.js} +1 -1
- package/chunks/{chunk-GTQULDIL.js → chunk-TSRTZD3X.js} +1 -1
- package/chunks/{chunk-GXNGLDUN.js → chunk-UXSXKLRH.js} +1 -1
- package/chunks/{chunk-JJQJFMPL.js → chunk-UYI5AMPI.js} +1 -1
- package/chunks/{chunk-SHKSVOTG.js → chunk-VO6SPDH4.js} +1 -1
- package/chunks/{chunk-AE6E2YKY.js → chunk-VRIHYTDI.js} +1 -1
- package/chunks/{chunk-6T25QVBX.js → chunk-VT47A26Q.js} +1 -1
- package/chunks/{chunk-2VW4HXVF.js → chunk-VZOZUCZX.js} +1 -1
- package/chunks/{chunk-724YPZRX.js → chunk-WLEGTKGA.js} +1 -1
- package/chunks/{chunk-ZOWMHZWO.js → chunk-XHCJN4A2.js} +1 -1
- package/chunks/{chunk-J773THNP.js → chunk-XTRZ5PHG.js} +1 -1
- package/chunks/{chunk-H65ZVST6.js → chunk-Y4GZOZWD.js} +1 -1
- package/chunks/{chunk-E6LRCLLE.js → chunk-YUCAGV52.js} +2 -2
- package/chunks/{chunk-FS67DOZQ.js → chunk-YWQM4TSO.js} +1 -1
- package/chunks/{chunk-P42MFWO2.js → chunk-YYTOHY4V.js} +1 -1
- package/chunks/{chunk-PSSJDUZB.js → chunk-Z25W2S5N.js} +1 -1
- package/chunks/{chunk-VF2UWWI2.js → chunk-Z6GECBAJ.js} +1 -1
- package/chunks/{chunk-HZ4L4MDM.js → chunk-ZJU4B4WX.js} +1 -1
- package/chunks/{chunk-RRMTSVGU.js → chunk-ZSHDQPAO.js} +1 -1
- package/chunks/{chunk-PFKTTUGS.js → chunk-ZUWLTGSR.js} +6 -6
- package/chunks/{codex-subagent-executor-UCDGQFTR.js → codex-subagent-executor-2V4NB7IR.js} +1 -1
- package/chunks/{config-utils-Z6F4DVLG.js → config-utils-5B2LYCON.js} +1 -1
- package/chunks/{contextCommand-HMVZT56Y.js → contextCommand-UPQGRXWK.js} +1 -1
- package/chunks/{core-runtime-AV7CJXOL.js → core-runtime-DPMH2BXK.js} +1 -1
- package/chunks/{create-sub-session-NNKVHZKT.js → create-sub-session-EJVB3FE5.js} +1 -1
- package/chunks/{cron-create-HWZDFVPA.js → cron-create-V2A7PMQC.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-Q3C45X7T.js → daemon-git-worktree-guard-YEIMR2X7.js} +1 -1
- package/chunks/{daemon-status-provider-UX574XBB.js → daemon-status-provider-6BRB5TG3.js} +1 -1
- package/chunks/{daemon-trust-policy-6D4KJANB.js → daemon-trust-policy-BEXVFO4M.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-BZ46W4IA.js → daemon-trust-policy-monitor-BVS6LXBX.js} +1 -1
- package/chunks/{deferred-core-runtime-YC5XIWEI.js → deferred-core-runtime-NTKFHL5J.js} +1 -1
- package/chunks/{edit-LOWDEKPX.js → edit-LRG3TMHP.js} +1 -1
- package/chunks/{enterPlanMode-NGSATDRH.js → enterPlanMode-KOUSHJHR.js} +1 -1
- package/chunks/{environment-CVIB5DW4.js → environment-54CM3OXE.js} +1 -1
- package/chunks/{errors-USKSVZFO.js → errors-D6XR3NH4.js} +1 -1
- package/chunks/{execution-tool-QSJLRU5N.js → execution-tool-7RZ2JLEK.js} +1 -1
- package/chunks/{execution-worker-TQEIC4AJ.js → execution-worker-LXQ7WAFG.js} +1 -1
- package/chunks/{exitPlanMode-AW2HOTIK.js → exitPlanMode-4FGFA2QC.js} +1 -1
- package/chunks/{fast-path-OQWHYDXC.js → fast-path-4B7OKPYK.js} +1 -1
- package/chunks/{glob-7U6FQSWZ.js → glob-N2D7SY23.js} +1 -1
- package/chunks/{goal-tools-5ZB6GPCJ.js → goal-tools-7RNSDRFO.js} +1 -1
- package/chunks/{handleAutoUpdate-MLUFTWFP.js → handleAutoUpdate-PKKJQAKG.js} +1 -1
- package/chunks/{i18n-QAPQLOC3.js → i18n-F3OAHCLJ.js} +1 -1
- package/chunks/{initializer-B27IZ7K4.js → initializer-OL3DDWR7.js} +1 -1
- package/chunks/{installationInfo-SAMHABWV.js → installationInfo-D2L743RV.js} +1 -1
- package/chunks/{interactive-mod-session-7LQ5CYUR.js → interactive-mod-session-2GXRCQKR.js} +1 -1
- package/chunks/{list-TDMJQDQO.js → list-PU7ZXBY5.js} +1 -1
- package/chunks/{llm-R2RFT63S.js → llm-V42HGUVH.js} +4 -4
- package/chunks/{loadedSettingsAdapter-ZQK5KMEW.js → loadedSettingsAdapter-KAEVWWRX.js} +1 -1
- package/chunks/{local-AONDQYFL.js → local-KM5F5RAB.js} +1 -1
- package/chunks/{local-execution-environment-WJVCE26F.js → local-execution-environment-OEO2KW3M.js} +1 -1
- package/chunks/{loggingContentGenerator-ALSG42YA.js → loggingContentGenerator-DQLXSDZR.js} +1 -1
- package/chunks/{loop-wakeup-LFU4LDJM.js → loop-wakeup-CJICM24Y.js} +1 -1
- package/chunks/{manage-memory-FBL6CHX2.js → manage-memory-7CV6LF4C.js} +1 -1
- package/chunks/{managed-execution-engine-FX7FDAWW.js → managed-execution-engine-JEAIQ7L4.js} +1 -1
- package/chunks/{managed-local-serve-DRNC6PTL.js → managed-local-serve-KA37YWRW.js} +1 -1
- package/chunks/{managed-npm-update-2MKV7UOI.js → managed-npm-update-TSUUH3NN.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-DBAHM5MN.js → managed-runtime-attestation-worker-PUZ2ECM5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-K3GRKDNQ.js → managed-runtime-bootstrap-SERIRKPD.js} +1 -1
- package/chunks/{managed-runtime-session-worker-YN4KML7A.js → managed-runtime-session-worker-UOXK63YX.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-AVNBWFYC.js → managed-runtime-ssh-worker-VKZYIX6R.js} +1 -1
- package/chunks/{managed-session-authority-MFEINLXC.js → managed-session-authority-5FYS3G3M.js} +1 -1
- package/chunks/{mcp-TS5PX5FY.js → mcp-TRPV3K74.js} +1 -1
- package/chunks/{memory-JVT5LAWJ.js → memory-5CMNRPM2.js} +1 -1
- package/chunks/{model-call-collection-TNBMD3YL.js → model-call-collection-S4JKVFUO.js} +1 -1
- package/chunks/{model-configuration-6KTQQTMO.js → model-configuration-NEIDLKWQ.js} +1 -1
- package/chunks/{modelConfigUtils-LCZZ3EQU.js → modelConfigUtils-LZLQOZKJ.js} +1 -1
- package/chunks/{monitor-KCCNIKLE.js → monitor-5MNKK5AO.js} +1 -1
- package/chunks/{nonInteractiveCli-2GHQYHGW.js → nonInteractiveCli-DDTGU2ER.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-R5CTTWKD.js → nonInteractiveToolExecutor-N7PCYCKO.js} +1 -1
- package/chunks/{notebook-edit-KIWE2XOA.js → notebook-edit-7HIBTFFW.js} +1 -1
- package/chunks/{omni-IFTMWBMU.js → omni-MX7BMOL5.js} +1 -1
- package/chunks/{openaiContentGenerator-XP3VPU6C.js → openaiContentGenerator-NOIIZNRX.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-ZJ6C22EA.js → openaiResponsesContentGenerator-5JJ6G7RS.js} +1 -1
- package/chunks/{pidfile-42P24JIA.js → pidfile-OHAGZOTV.js} +1 -1
- package/chunks/{processUtils-I2XOO5U2.js → processUtils-TCDNCYVB.js} +1 -1
- package/chunks/{prompt-terminal-ledger-7EW46VQ4.js → prompt-terminal-ledger-4ZUOCMOS.js} +1 -1
- package/chunks/{reactive-degrade-O4JO7MOX.js → reactive-degrade-C7CGUJNP.js} +1 -1
- package/chunks/{read-file-VGC4O7F2.js → read-file-L4ZF6VDG.js} +1 -1
- package/chunks/{resumeHistoryUtils-QMVIHQRW.js → resumeHistoryUtils-WK3I4OIL.js} +1 -1
- package/chunks/{review-NDK2B7XI.js → review-F6JGI2LP.js} +1 -1
- package/chunks/{ripGrep-JY4PZABK.js → ripGrep-L6M2GPCM.js} +1 -1
- package/chunks/{run-qwen-serve-P5X5OZUH.js → run-qwen-serve-D5HB55SC.js} +1 -1
- package/chunks/{runtime-OL7B72CH.js → runtime-CH3RAOQL.js} +1 -1
- package/chunks/{sandboxConfig-EJTMWZHD.js → sandboxConfig-EADWCO37.js} +1 -1
- package/chunks/{scheduled-tasks-XQSZWZXG.js → scheduled-tasks-PBKD4BHY.js} +1 -1
- package/chunks/{scheduler-3TIRZEVB.js → scheduler-U5K3523K.js} +1 -1
- package/chunks/{search-memory-P5KOTUVV.js → search-memory-Y2IPKBDP.js} +1 -1
- package/chunks/{send-message-KFSKFXLX.js → send-message-JJQG2S6D.js} +1 -1
- package/chunks/{serve-UHEH433U.js → serve-2ZYS47MO.js} +1 -1
- package/chunks/{server-ARYDETSZ.js → server-5GMO4IHU.js} +3 -3
- package/chunks/{session-HKWGCZF2.js → session-LLOOVSHK.js} +1 -1
- package/chunks/{session-attachments-root-O3YQ7HWD.js → session-attachments-root-XCLXH2XO.js} +1 -1
- package/chunks/{session-execution-engine-selector-LZBHS3UO.js → session-execution-engine-selector-5QPWJZSF.js} +1 -1
- package/chunks/{session-pr-refresh-L5Z5WCXS.js → session-pr-refresh-MDBOAN3R.js} +1 -1
- package/chunks/{sessionService-MMPZUN5X.js → sessionService-VKAHCTCC.js} +1 -1
- package/chunks/{settings-7PYHXPN4.js → settings-ULEB2IYZ.js} +1 -1
- package/chunks/{shell-E6QLKRVU.js → shell-RBEKIYKU.js} +1 -1
- package/chunks/{skill-55IZUUM5.js → skill-GEVOEFMZ.js} +1 -1
- package/chunks/{skill-settings-A2M5BPH7.js → skill-settings-4IMGLYJW.js} +1 -1
- package/chunks/{spawnChannel-KWU26CB7.js → spawnChannel-B7L5PWQ6.js} +1 -1
- package/chunks/{standalone-update-32WYZ3BJ.js → standalone-update-SYQM6NOC.js} +1 -1
- package/chunks/{start-opentui-ui-S7A4FBGP.js → start-opentui-ui-N427PLF4.js} +2 -2
- package/chunks/{startInteractiveUI-DY6DWFW7.js → startInteractiveUI-AS6GZKJJ.js} +1 -1
- package/chunks/{team-create-ARICYIQB.js → team-create-MN6FHUHU.js} +1 -1
- package/chunks/{team-plan-approval-JPRE6Q3R.js → team-plan-approval-OUYBIT7H.js} +1 -1
- package/chunks/{terminal-image-renderer-HVIZ2VNE.js → terminal-image-renderer-MXZDUEOS.js} +1 -1
- package/chunks/{theme-manager-UEPLIBUP.js → theme-manager-QOYSKWFK.js} +1 -1
- package/chunks/{tool-call-EFJKXI3Z.js → tool-call-Q5NLEQFD.js} +1 -1
- package/chunks/{tool-result-media-LMIYNXSD.js → tool-result-media-NZJZTOBQ.js} +1 -1
- package/chunks/{tool-search-D7HQTRQG.js → tool-search-D6Y45RNQ.js} +1 -1
- package/chunks/{total-session-admission-67QMR44O.js → total-session-admission-36W7MDHP.js} +1 -1
- package/chunks/{trustedFolders-HARYVS3F.js → trustedFolders-XW5VH6HK.js} +1 -1
- package/chunks/{update-relaunch-NVNPOK5J.js → update-relaunch-KQPR2HAP.js} +1 -1
- package/chunks/{updateCheck-7NMXUCTN.js → updateCheck-SRW67WAX.js} +1 -1
- package/chunks/{upload-config-W2SICJ32.js → upload-config-BTJNYMRX.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-ELMIP4TJ.js → useAutoAcceptIndicator-N3RRUBSL.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-P2F6MYO6.js → validateNonInterActiveAuth-SWNH4FY4.js} +1 -1
- package/chunks/{version-2ZFKVIIW.js → version-6R6LSGXO.js} +1 -1
- package/chunks/{web-fetch-537RS6IX.js → web-fetch-Y7LBAU3R.js} +1 -1
- package/chunks/{web-search-O27MYFSW.js → web-search-IB4NYYUH.js} +1 -1
- package/chunks/{workflow-6QF4RMYM.js → workflow-TR4YIPJO.js} +1 -1
- package/chunks/{workflow-ancestor-trust-CABLU3VV.js → workflow-ancestor-trust-AHDUBOR7.js} +1 -1
- package/chunks/{workspace-agents-5WP3PY7W.js → workspace-agents-MY2NFL6A.js} +1 -1
- package/chunks/{workspace-providers-status-7G2EJJEO.js → workspace-providers-status-DNCCKFVE.js} +1 -1
- package/chunks/{workspace-recovery-worker-ICCIDEWU.js → workspace-recovery-worker-22VK4T4R.js} +1 -1
- package/chunks/{workspace-registration-store-WHXMNQQQ.js → workspace-registration-store-64TGRRGC.js} +1 -1
- package/chunks/{workspace-registry-NXBODLYH.js → workspace-registry-E6LFL5GL.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-CJXS273B.js → workspace-runtime-coordinator-UHJHBIQT.js} +1 -1
- package/chunks/{workspace-service-HUDE2RXN.js → workspace-service-OVEYIQOC.js} +1 -1
- package/chunks/{workspace-skills-status-FJC6U62F.js → workspace-skills-status-3NKXA5SK.js} +1 -1
- package/chunks/{workspace-trust-reconciler-ZIQ3A5ZB.js → workspace-trust-reconciler-JF7YHR52.js} +1 -1
- package/chunks/{write-file-652YGG7I.js → write-file-FSTHYKKZ.js} +1 -1
- package/chunks/{zoom-image-YEH4O74G.js → zoom-image-JP3EUDXE.js} +1 -1
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/package.json +2 -2
- package/chunks/chunk-56PVVXUG.js +0 -8
- package/chunks/chunk-AJ75BPTA.js +0 -31
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-GOZ5FAUV.js";import{t}from"./chunk-FK5L2WVV.js";import{So}from"./chunk-PFKTTUGS.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
|
|
3
|
+
import{loadUndici}from"./chunk-XKSB7VTV.js";import{updateEventEmitter}from"./chunk-VDUNIK4I.js";import{hasStandaloneArchiveLayout,standaloneRuntimePaths}from"./chunk-GOZ5FAUV.js";import{t}from"./chunk-AUM57JI2.js";import{So}from"./chunk-ZUWLTGSR.js";import{require_semver}from"./chunk-73G3MZQR.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import*as fs from"node:fs";import*as os from"node:os";import*as path from"node:path";import{Readable,Transform}from"node:stream";import{spawn,execFile}from"node:child_process";import{pipeline}from"node:stream/promises";var import_semver=__toESM(require_semver(),1);init_esbuild_shims();import{createPublicKey,verify}from"node:crypto";var RELEASE_PUBLIC_KEY_DER_B64="MCowBQYDK2VwAyEAr9WRFLDauibZQKCe1oKfuFZn6zRMaEkD5+KVqN6mKM4=";function verifySignature(sha256sumsContent,signatureBase64){const key=createPublicKey({key:Buffer.from(RELEASE_PUBLIC_KEY_DER_B64,"base64"),format:"der",type:"spki"});const signature=Buffer.from(signatureBase64,"base64");if(signature.length!==64){throw new Error(`Invalid signature length: expected 64 bytes, got ${signature.length}`)}const valid=verify(null,Buffer.from(sha256sumsContent),key,signature);if(!valid){throw new Error("SHA256SUMS signature verification failed \u2014 possible tampering detected")}}__name(verifySignature,"verifySignature");var debugLogger=createDebugLogger("STANDALONE_UPDATE");var OSS_BASE="https://qwen-code-assets.oss-cn-hangzhou.aliyuncs.com/releases/qwen-code";var GITHUB_BASE="https://github.com/QwenLM/qwen-code/releases/download";var FETCH_TIMEOUT_MS=3e4;var ARCHIVE_TIMEOUT_MS=3e5;var VALID_TARGETS=new Set(["darwin-arm64","darwin-x64","linux-arm64","linux-x64","win-x64"]);var SEMVER_RE=/^v?\d+\.\d+\.\d+(-[\w.]+)?$/;function isConcreteVersion(version){return SEMVER_RE.test(version)&&import_semver.default.valid(version)!==null}__name(isConcreteVersion,"isConcreteVersion");function normalizeVersion(version){if(!isConcreteVersion(version)){throw new Error(`Invalid version format: ${version}`)}return version.startsWith("v")?version:`v${version}`}__name(normalizeVersion,"normalizeVersion");function validateTarget(target){if(!VALID_TARGETS.has(target)){throw new Error(`Unknown target: ${target}`)}}__name(validateTarget,"validateTarget");function archiveFilename(target,runtime){const ext=target.startsWith("win")?"zip":"tar.gz";const suffix=runtime==="bun"?"-opentui-preview":"";return`qwen-code-${target}${suffix}.${ext}`}__name(archiveFilename,"archiveFilename");function escapePS(s){return s.replace(/'/g,"''")}__name(escapePS,"escapePS");function resolveUpdateBaseUrl(){const value=process.env["QWEN_UPDATE_BASE_URL"]?.trim();if(!value)return void 0;const invalidUrl=__name(()=>new Error("QWEN_UPDATE_BASE_URL must be an absolute HTTPS URL without credentials, query parameters, or a fragment."),"invalidUrl");let url;try{url=new URL(value)}catch{throw invalidUrl()}if(!/^https:\/\//i.test(value)||url.username||url.password||/[?#\s]/.test(value)){throw invalidUrl()}return url.href.replace(/\/+$/,"")}__name(resolveUpdateBaseUrl,"resolveUpdateBaseUrl");async function tryFetch(url,timeoutMs=FETCH_TIMEOUT_MS){try{const{fetch}=await loadUndici();const res=await fetch(url,{signal:AbortSignal.timeout(timeoutMs)});if(res.ok)return{response:res};await res.body?.cancel().catch(()=>{});return{error:new Error(`HTTP ${res.status} ${res.statusText}`)}}catch(err){const error=err instanceof Error?err:new Error(String(err));debugLogger.debug(`Fetch failed for ${url}: ${error.message}`);return{error}}}__name(tryFetch,"tryFetch");async function downloadWithFallback(versionPath,filename,timeoutMs=FETCH_TIMEOUT_MS,baseUrl){if(baseUrl){const result=await tryFetch(`${baseUrl}/${versionPath}/${filename}`,timeoutMs);if(result.response)return result.response;throw new Error(`Failed to download ${filename} from QWEN_UPDATE_BASE_URL: ${result.error.message}`)}const ossUrl=`${OSS_BASE}/${versionPath}/${filename}`;const ossResult=await tryFetch(ossUrl,timeoutMs);if(ossResult.response)return ossResult.response;const ghUrl=`${GITHUB_BASE}/${versionPath}/${filename}`;const ghResult=await tryFetch(ghUrl,timeoutMs);if(ghResult.response)return ghResult.response;throw new Error(`Failed to download ${filename}: OSS (${ossResult.error?.message??"unknown"}), GitHub (${ghResult.error?.message??"unknown"})`)}__name(downloadWithFallback,"downloadWithFallback");async function verifyChecksum(actualHash,filename,versionPath,baseUrl){const response=await downloadWithFallback(versionPath,"SHA256SUMS",FETCH_TIMEOUT_MS,baseUrl);const text=await response.text();const requireSig=process.env["QWEN_REQUIRE_SIGNATURE"]==="1";let sigResponse;try{sigResponse=await downloadWithFallback(versionPath,"SHA256SUMS.sig",FETCH_TIMEOUT_MS,baseUrl)}catch(err){debugLogger.debug("SHA256SUMS.sig not available:",err)}if(sigResponse){const sigContent=await sigResponse.text();verifySignature(text,sigContent.trim());debugLogger.info("SHA256SUMS signature verified.")}else if(requireSig){throw new Error("SHA256SUMS.sig not found and QWEN_REQUIRE_SIGNATURE=1 is set")}else{debugLogger.warn("SHA256SUMS.sig not available \u2014 update integrity relies on SHA256 checksum only. Set QWEN_REQUIRE_SIGNATURE=1 to enforce signature verification.")}const expectedLine=text.split("\n").find(line=>{const parts=line.trim().split(/\s+/);if(parts.length<2)return false;const name=parts[parts.length-1].replace(/^\*/,"");return name===filename});if(!expectedLine){throw new Error(`No checksum found for ${filename} in SHA256SUMS`)}const expectedHash=expectedLine.trim().split(/\s+/)[0];if(actualHash!==expectedHash){throw new Error(`Checksum mismatch: expected ${expectedHash}, got ${actualHash}`)}}__name(verifyChecksum,"verifyChecksum");var MAX_DOWNLOAD_BYTES=512*1024*1024;async function downloadToFile(versionPath,filename,destPath,baseUrl){const response=await downloadWithFallback(versionPath,filename,ARCHIVE_TIMEOUT_MS,baseUrl);const body=response.body;if(!body)throw new Error("Empty response body");const contentLength=response.headers.get("content-length");if(contentLength&&parseInt(contentLength,10)>MAX_DOWNLOAD_BYTES){await body.cancel().catch(()=>{});throw new Error(`Download too large: ${contentLength} bytes exceeds ${MAX_DOWNLOAD_BYTES} limit`)}const hash=createHash("sha256");let bytesWritten=0;const dest=fs.createWriteStream(destPath);const sizeGuard=new Transform({transform(chunk,_encoding,callback){bytesWritten+=chunk.length;if(bytesWritten>MAX_DOWNLOAD_BYTES){callback(new Error(`Download exceeded ${MAX_DOWNLOAD_BYTES} byte limit`))}else{hash.update(chunk);callback(null,chunk)}}});await pipeline(Readable.fromWeb(body),sizeGuard,dest);return hash.digest("hex")}__name(downloadToFile,"downloadToFile");function isPathInside(base,candidate){const rel=path.relative(base,candidate);return rel===""||!!rel&&rel!==".."&&!rel.startsWith(`..${path.sep}`)&&!path.isAbsolute(rel)}__name(isPathInside,"isPathInside");function normalizeTarEntryPath(entryPath){const parts=entryPath.split(/[\\/]+/).filter(part=>part&&part!==".");if(parts.length===0||parts.includes("..")){return null}return parts.join("/")}__name(normalizeTarEntryPath,"normalizeTarEntryPath");function isSafeTarLinkTarget(entryPath,linkPath,resolvedDest){if(path.posix.isAbsolute(linkPath)||path.win32.isAbsolute(linkPath)){return false}const normalizedEntryPath=normalizeTarEntryPath(entryPath);if(!normalizedEntryPath){return false}const archiveRoot=normalizedEntryPath.split("/")[0];const linkTarget=path.resolve(resolvedDest,path.posix.dirname(normalizedEntryPath),linkPath);return isPathInside(path.join(resolvedDest,archiveRoot),linkTarget)}__name(isSafeTarLinkTarget,"isSafeTarLinkTarget");function getTarEntryType(entry){if("type"in entry)return entry.type;if("isFile"in entry&&entry.isFile())return"File";if("isDirectory"in entry&&entry.isDirectory())return"Directory";if("isSymbolicLink"in entry&&entry.isSymbolicLink()){return"SymbolicLink"}return void 0}__name(getTarEntryType,"getTarEntryType");function isSafeTarEntry(entryPath,entry,resolvedDest){if(!isSafeTarEntryPath(entryPath))return false;const entryType=getTarEntryType(entry);const linkPath="linkpath"in entry?entry.linkpath:void 0;if(entryType!=="File"&&entryType!=="Directory"&&entryType!=="SymbolicLink"){return false}if(entryType==="SymbolicLink"){if(linkPath===void 0)return false;return isSafeTarLinkTarget(entryPath,String(linkPath),resolvedDest)}return true}__name(isSafeTarEntry,"isSafeTarEntry");function isAlreadyExistsError(err){return typeof err==="object"&&err!==null&&"code"in err&&err.code==="EEXIST"}__name(isAlreadyExistsError,"isAlreadyExistsError");function validateExtractedPaths(resolvedDest,options={}){const entries=fs.readdirSync(resolvedDest,{recursive:true,withFileTypes:true});for(const entry of entries){if(options.symlinksOnly&&!entry.isSymbolicLink()){continue}const fullPath=path.join(String(entry.parentPath||entry.path),entry.name);let resolved;try{resolved=fs.realpathSync(fullPath)}catch(err){fs.rmSync(resolvedDest,{recursive:true,force:true});const detail=err instanceof Error?err.message:String(err);throw new Error(`Invalid archive entry: ${entry.name} could not be resolved (${detail})`)}if(!isPathInside(resolvedDest,resolved)){fs.rmSync(resolvedDest,{recursive:true,force:true});throw new Error(`Path traversal detected in archive: ${entry.name} resolves to ${resolved}`)}}}__name(validateExtractedPaths,"validateExtractedPaths");function isSafeTarEntryPath(entryPath){if(entryPath.length===0)return false;if(path.posix.isAbsolute(entryPath)||path.win32.isAbsolute(entryPath)){return false}return normalizeTarEntryPath(entryPath)!==null}__name(isSafeTarEntryPath,"isSafeTarEntryPath");async function extractArchive(archivePath,destDir,target){fs.mkdirSync(destDir,{recursive:true});if(target.startsWith("win")){await new Promise((resolve2,reject)=>{const ps=spawn("powershell.exe",["-NoProfile","-Command",`Expand-Archive -Path '${escapePS(archivePath)}' -DestinationPath '${escapePS(destDir)}' -Force`],{stdio:"ignore"});ps.on("close",code=>code===0?resolve2():reject(new Error(`Expand-Archive exited with code ${code}`)));ps.on("error",reject)});const resolvedDest=fs.realpathSync(destDir);validateExtractedPaths(resolvedDest)}else{const resolvedDest=fs.realpathSync(destDir);await So({file:archivePath,cwd:destDir,preservePaths:false,filter:__name((p,entry)=>isSafeTarEntry(p,entry,resolvedDest),"filter")});validateExtractedPaths(fs.realpathSync(destDir),{symlinksOnly:true})}}__name(extractArchive,"extractArchive");function spawnAndCapture(command,args,timeoutMs,cwd){const env={...process.env};for(const key of Object.keys(env)){if(/^(NODE_OPTIONS|BUN_OPTIONS|CLI_VERSION|QWEN_CODE_RELAUNCH_ARGS)$/i.test(key))delete env[key]}return new Promise((resolve2,reject)=>{let settled=false;const child=execFile(command,args,{env,cwd,timeout:timeoutMs,killSignal:"SIGKILL",maxBuffer:64*1024},(err,out,stderr)=>{if(settled)return;settled=true;if(err&&("killed"in err&&err.killed||"signal"in err&&err.signal)){reject(new Error("Smoke test timed out"));return}if(err){const exitCode="code"in err&&typeof err.code==="number"?err.code:1;resolve2({exitCode,stdout:out||"",stderr:stderr||""});return}resolve2({exitCode:0,stdout:out||"",stderr:stderr||""})});child.on("error",()=>{if(settled)return;settled=true;reject(new Error("Smoke test failed: unable to start new binary"))})})}__name(spawnAndCapture,"spawnAndCapture");async function smokeTest(newInstallDir,target,runtime,expectedVersion){const resolvedInstallDir=path.resolve(newInstallDir);const interpreter=target.startsWith("win")?path.join(resolvedInstallDir,runtime,`${runtime}.exe`):path.join(resolvedInstallDir,runtime,"bin",runtime);const cliBin=path.join(resolvedInstallDir,"lib","cli.js");if(!fs.existsSync(interpreter)){throw new Error(`Smoke test failed: ${runtime} binary not found at ${interpreter}`)}if(!fs.existsSync(cliBin)){throw new Error(`Smoke test failed: CLI entry not found at ${cliBin}`)}const cwd=fs.mkdtempSync(path.join(os.tmpdir(),"qwen-code-smoke-"));try{const identity=await spawnAndCapture(interpreter,["-e",'console.log(JSON.stringify({runtime:process.versions.bun?"bun":"node",platform:process.platform,arch:process.arch}))'],1e4,cwd);let actual;try{actual=JSON.parse(identity.stdout)}catch{throw new Error("Smoke test failed: invalid interpreter identity")}const[platform2,arch2]=target.split("-");if(identity.exitCode!==0||!actual||typeof actual!=="object"||Array.isArray(actual)||Reflect.get(actual,"runtime")!==runtime||Reflect.get(actual,"platform")!==(platform2==="win"?"win32":platform2)||Reflect.get(actual,"arch")!==arch2){throw new Error("Smoke test failed: interpreter identity does not match the expected runtime and target")}const{exitCode,stdout}=await spawnAndCapture(interpreter,[cliBin,"--version"],1e4,cwd);if(exitCode!==0){throw new Error(`Smoke test failed: new binary exited with code ${exitCode}`)}const version=stdout.trim();if(!SEMVER_RE.test(version)){throw new Error("Smoke test failed: unexpected version output")}let versionMatches;try{versionMatches=import_semver.default.eq(version,expectedVersion)}catch{versionMatches=false}if(!versionMatches){throw new Error("Smoke test failed: CLI version does not match the expected version")}const launcher=await spawnAndCapture(interpreter,[path.join(resolvedInstallDir,"lib","cli-entry.js"),"--help"],1e4,cwd);if(launcher.exitCode!==0){throw new Error("Smoke test failed: launcher could not load CLI")}debugLogger.info(`Smoke test passed: ${version}`)}finally{try{fs.rmSync(cwd,{recursive:true,force:true})}catch{debugLogger.warn("Could not remove the smoke test temporary directory")}}}__name(smokeTest,"smokeTest");function pendingSwapError(standaloneDir){return new Error(`A previous update left a pending swap at ${standaloneDir}.new. If no qwen-update.bat process is running, remove the pending swap and .qwen-update.lock, then try again.`)}__name(pendingSwapError,"pendingSwapError");function deferredMarkerError(standaloneDir){return new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If no qwen-update.bat process is running, remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, then try again.`)}__name(deferredMarkerError,"deferredMarkerError");var PENDING_SWAP_STALE_MS=15*60*1e3;function checkDeferredSwap(standaloneDir){const deferredMarker=`${standaloneDir}.deferred`;let swapProvenDead=false;if(fs.existsSync(deferredMarker)){let marker;try{marker=fs.readFileSync(deferredMarker,"utf-8").trim()}catch{throw deferredMarkerError(standaloneDir)}const batPid=parseInt(marker,10);if(!Number.isSafeInteger(batPid)||batPid<=0||batPid>2147483647){throw deferredMarkerError(standaloneDir)}if(!isProcessProvablyGone(batPid)){let markerStale=false;try{markerStale=Date.now()-fs.statSync(deferredMarker).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(markerStale){throw new Error(`A previous update left a deferred-swap marker at ${standaloneDir}.deferred. If a qwen-update.bat process is still running, end it first; then remove the marker, the pending swap at ${standaloneDir}.new, and .qwen-update.lock, and try again.`)}throw new Error("A previous update is still being applied. Please wait a moment and try again.")}swapProvenDead=true;try{fs.unlinkSync(deferredMarker)}catch{}}const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(pendingDir)){if(!swapProvenDead){let stale=false;try{stale=Date.now()-fs.statSync(pendingDir).mtimeMs>PENDING_SWAP_STALE_MS}catch{}if(!stale){throw pendingSwapError(standaloneDir)}}try{fs.rmSync(pendingDir,{recursive:true,force:true})}catch(err){const reason=err instanceof Error?err.message:String(err);throw new Error(`A previous update left a pending swap at ${pendingDir} that could not be removed (${reason}). Remove it and .qwen-update.lock, then try again.`)}}}__name(checkDeferredSwap,"checkDeferredSwap");function acquireLock(lockPath,standaloneDir){try{fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});if(standaloneDir){checkDeferredSwap(standaloneDir)}return true}catch(fastPathErr){if(fastPathErr instanceof Error&&(fastPathErr.message.startsWith("A previous update")||fastPathErr.message.includes("pending swap"))){try{fs.unlinkSync(lockPath)}catch{}throw fastPathErr}let pidStr;try{pidStr=fs.readFileSync(lockPath,"utf-8").trim()}catch{return false}const pid=parseInt(pidStr,10);if(!Number.isNaN(pid)&&isProcessAlive(pid)){return false}if(standaloneDir){checkDeferredSwap(standaloneDir)}try{fs.unlinkSync(lockPath);fs.writeFileSync(lockPath,String(process.pid),{flag:"wx"});return true}catch{return false}}}__name(acquireLock,"acquireLock");function releaseLock(lockPath){try{fs.unlinkSync(lockPath)}catch{}}__name(releaseLock,"releaseLock");function cleanupEmptyStandaloneDir(standaloneDir){const manifestPath=path.join(standaloneDir,"manifest.json");if(fs.existsSync(standaloneDir)&&!fs.existsSync(manifestPath)){fs.rmSync(standaloneDir,{recursive:true,force:true})}}__name(cleanupEmptyStandaloneDir,"cleanupEmptyStandaloneDir");var UNSAFE_SHELL_CHARS=/[\0\n\r]/;var UNSAFE_CMD_CHARS=/[&|<>^%!"`\n\r]/;function assertSafeForSingleQuotedShellPath(p,context){if(UNSAFE_SHELL_CHARS.test(p)){throw new Error(`${context} contains characters unsafe for shell embedding: ${p}`)}}__name(assertSafeForSingleQuotedShellPath,"assertSafeForSingleQuotedShellPath");function shellQuoteForSh(p){return`'${p.replace(/'/g,"'\\''")}'`}__name(shellQuoteForSh,"shellQuoteForSh");function shellQuoteForFish(p){return shellQuoteForSh(p)}__name(shellQuoteForFish,"shellQuoteForFish");function isProcessAlive(pid){try{process.kill(pid,0);return true}catch{return false}}__name(isProcessAlive,"isProcessAlive");function isProcessProvablyGone(pid){try{process.kill(pid,0);return false}catch(err){return err.code==="ESRCH"}}__name(isProcessProvablyGone,"isProcessProvablyGone");function atomicReplace(standaloneDir,newDir,lockPath){const oldDir=`${standaloneDir}.old`;const pendingDir=`${standaloneDir}.new`;if(fs.existsSync(oldDir)){fs.rmSync(oldDir,{recursive:true,force:true})}if(os.platform()==="win32"){if(UNSAFE_CMD_CHARS.test(standaloneDir)||UNSAFE_CMD_CHARS.test(oldDir)||UNSAFE_CMD_CHARS.test(pendingDir)){throw new Error("Installation path contains characters unsafe for deferred update script")}if(fs.existsSync(pendingDir)){fs.rmSync(pendingDir,{recursive:true,force:true})}fs.renameSync(newDir,pendingDir);const lockFile=lockPath;const deferredMarker=`${standaloneDir}.deferred`;const logFile=path.join(path.dirname(standaloneDir),"qwen-update.log");const script=["@echo off","set /a TRIES=0",":wait","set /a TRIES+=1","if %TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.pid}" 2>nul | find "${process.pid}" >nul && (timeout /t 1 >nul & goto wait)`,...process.env["QWEN_CODE_LAUNCHER_PID"]?.match(/^\d+$/)?["set /a LAUNCHER_TRIES=0",":wait_launcher","set /a LAUNCHER_TRIES+=1","if %LAUNCHER_TRIES% GTR 30 goto proceed",`tasklist /FI "PID eq ${process.env["QWEN_CODE_LAUNCHER_PID"]}" 2>nul | find "${process.env["QWEN_CODE_LAUNCHER_PID"]}" >nul && (timeout /t 1 >nul & goto wait_launcher)`]:[],":proceed",`echo [%DATE% %TIME%] starting swap >> "${logFile}"`,`move /Y "${standaloneDir}" "${oldDir}"`,"if errorlevel 1 goto move1_failed",`move /Y "${pendingDir}" "${standaloneDir}"`,"if errorlevel 1 goto move2_failed",`echo [%DATE% %TIME%] swap completed >> "${logFile}"`,"goto cleanup",":move1_failed",`echo [%DATE% %TIME%] ERROR: failed to rename install to .old (errorlevel %errorlevel%) >> "${logFile}"`,"goto cleanup",":move2_failed",`echo [%DATE% %TIME%] ERROR: failed to promote .new; rolling back >> "${logFile}"`,`move /Y "${oldDir}" "${standaloneDir}"`,"if errorlevel 1 (",` echo [%DATE% %TIME%] CRITICAL: rollback also failed; manual recovery: move "${oldDir}" "${standaloneDir}" >> "${logFile}"`,") else (",` echo [%DATE% %TIME%] rollback succeeded >> "${logFile}"`,")",":cleanup",`del /F /Q "${deferredMarker}" 2>nul`,`del /F /Q "${lockFile}" 2>nul`,`del "%~f0"`].join("\r\n");const scriptPath=path.join(path.dirname(standaloneDir),"qwen-update.bat");fs.writeFileSync(scriptPath,script);const child=spawn("cmd.exe",["/c",scriptPath],{detached:true,stdio:"ignore",windowsHide:true});child.on("error",err=>{debugLogger.warn("Deferred bat script failed to spawn:",err)});child.unref();if(!child.pid){throw new Error("Failed to spawn deferred update script. Update was not applied.")}fs.writeFileSync(deferredMarker,String(child.pid));return"deferred"}else{fs.renameSync(standaloneDir,oldDir);try{fs.renameSync(newDir,standaloneDir)}catch(promoteErr){try{fs.renameSync(oldDir,standaloneDir)}catch(rollbackErr){const detail=`Standalone update failed AND rollback failed.
|
|
4
4
|
Original error: ${promoteErr.message}
|
|
5
5
|
Rollback error: ${rollbackErr.message}
|
|
6
6
|
Manual recovery: mv "${oldDir}" "${standaloneDir}"`;throw new Error(detail)}throw promoteErr}return"done"}}__name(atomicReplace,"atomicReplace");function ensureBinWrapper(standaloneDir,target,runtime="node"){const binDir=path.join(path.dirname(standaloneDir),"..","bin");const artifacts={wrapperCreated:false};const{launcher,interpreter,entryPoint}=standaloneRuntimePaths(standaloneDir,target,runtime);const hasLauncher=fs.existsSync(launcher);try{fs.mkdirSync(binDir,{recursive:true});if(target.startsWith("win")){if(UNSAFE_CMD_CHARS.test(standaloneDir)){throw new Error("standaloneDir contains characters unsafe for cmd.exe wrapper")}const wrapperPath=path.join(binDir,"qwen.cmd");artifacts.wrapperPath=wrapperPath;const content=hasLauncher?`@echo off\r
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"use strict";
|
|
3
3
|
import{resolvePolicyToolSettings}from"./chunk-SXO35MFJ.js";import{MEDIA_MEMORY_FILE_NAME}from"./chunk-UGDAT4C4.js";import{DEFAULT_OMNI_PROCESSING_LIMITS,conditionUsesNamespace,evaluateFixedPolicyCondition}from"./chunk-YU67VCCO.js";import{OmniJsonCacheFile}from"./chunk-33P4RB6G.js";import{OBJECT_EXTENSION_RE}from"./chunk-RQHIWFQL.js";import{extensionForMime,hashFileSha256,recognizeMediaFile}from"./chunk-BSFNCIBS.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var AUDIO_TOKENS_PER_SECOND=7;var VISUAL_PIXELS_PER_TOKEN=32*32*2;function usable(value){return value!==void 0&&Number.isFinite(value)&&value>0}__name(usable,"usable");function estimateRawResourceTokens(media){const unavailable={estimatedTokenCount:0,method:"raw-resource-v1",status:"unavailable"};switch(media.modality){case"audio":{const durationMs=media.metadata.durationMs;if(!usable(durationMs))return unavailable;return{estimatedTokenCount:Math.ceil(durationMs/1e3*AUDIO_TOKENS_PER_SECOND),method:"raw-resource-v1",status:"ok"}}case"image":{const{width,height,frameCount}=media.metadata;if(!usable(width)||!usable(height))return unavailable;const frames=usable(frameCount)?frameCount:1;return{estimatedTokenCount:Math.ceil(width*height*frames/VISUAL_PIXELS_PER_TOKEN),method:"raw-resource-v1",status:"ok"}}case"video":{const{width,height,durationMs,frameRate}=media.metadata;if(!usable(width)||!usable(height)||!usable(durationMs)||!usable(frameRate)){return unavailable}const frameCount=Math.ceil(durationMs/1e3*frameRate);return{estimatedTokenCount:Math.ceil(width*height*frameCount/VISUAL_PIXELS_PER_TOKEN),method:"raw-resource-v1",status:"ok"}}default:return unavailable}}__name(estimateRawResourceTokens,"estimateRawResourceTokens");init_esbuild_shims();import{createHash}from"node:crypto";import path from"node:path";var MAX_CACHED_DISCLOSURE_LENGTH=2048;var FINGERPRINT_EXCLUDED_KEYS=new Set(["inputPath","outputDir","resourceId"]);function stableStringify(value){if(Array.isArray(value)){return`[${value.map(stableStringify).join(",")}]`}if(typeof value==="object"&&value!==null){const record=value;const body=Object.keys(record).sort().map(k=>`${JSON.stringify(k)}:${stableStringify(record[k])}`).join(",");return`{${body}}`}return JSON.stringify(value)??"null"}__name(stableStringify,"stableStringify");function computePolicyFingerprint(toolName,args,toolVersion="1"){const tunables={};for(const[k,v]of Object.entries(args)){if(!FINGERPRINT_EXCLUDED_KEYS.has(k)&&v!==void 0){tunables[k]=v}}return createHash("sha256").update(`${toolName}
|
|
4
4
|
${stableStringify(tunables)}
|
|
5
|
-
${toolVersion}`).digest("hex")}__name(computePolicyFingerprint,"computePolicyFingerprint");var OmniDegradationCache=class{static{__name(this,"OmniDegradationCache")}file;constructor(omniRootDir){this.file=new OmniJsonCacheFile(path.join(omniRootDir,"policy-cache.json"),"omni:policy-cache")}key(originalSha256,policyFingerprint){return`${originalSha256}|${policyFingerprint}`}async get(originalSha256,policyFingerprint){return this.file.access(null,entries=>{const key=this.key(originalSha256,policyFingerprint);const entry=entries[key];if(!entry)return{result:null};if(!/^[0-9a-f]{64}$/.test(entry.degradedSha256)||typeof entry.extension!=="string"||!OBJECT_EXTENSION_RE.test(entry.extension)||typeof entry.disclosure!=="string"||entry.disclosure.length===0||entry.disclosure.length>MAX_CACHED_DISCLOSURE_LENGTH||typeof entry.mimeType!=="string"||entry.mimeType.length===0||entry.role!==void 0&&(typeof entry.role!=="string"||entry.role.length===0)){delete entries[key];return{result:null,changed:true}}return{result:entry}})}async put(originalSha256,policyFingerprint,entry){return this.file.access(void 0,entries=>{entries[this.key(originalSha256,policyFingerprint)]={...entry,createdAt:new Date().toISOString()};return{result:void 0,changed:true}})}async removeByOriginalSha256(originalSha256){return this.file.access(void 0,entries=>{const prefix=`${originalSha256}|`;let changed=false;for(const k of Object.keys(entries)){if(k.startsWith(prefix)){delete entries[k];changed=true}}return{result:void 0,changed}})}async removeByDegradedSha256(degradedSha256){return this.file.access(void 0,entries=>{let changed=false;for(const[k,v]of Object.entries(entries)){if(v.degradedSha256===degradedSha256){delete entries[k];changed=true}}return{result:void 0,changed}})}};init_esbuild_shims();var DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES=1024*1024*1024;var OmniTransportGuardError=class extends Error{static{__name(this,"OmniTransportGuardError")}sessionResourceId;constructor(message,options){super(message,options);this.name="OmniTransportGuardError"}};function effectiveMaxUploadFileBytes(config){const configured=config.getOmniMaxUploadFileBytes?.();return configured!==void 0&&configured>0?configured:DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES}__name(effectiveMaxUploadFileBytes,"effectiveMaxUploadFileBytes");function assertWithinByteLimit(config,sizeBytes,displayName){const maxBytes=effectiveMaxUploadFileBytes(config);if(sizeBytes>maxBytes){throw new OmniTransportGuardError(`${displayName} exceeds the omni upload limit: ${sizeBytes} bytes > ${maxBytes} bytes (omni.processing.transportGuard.maxUploadFileBytes). Reduce the file size before retrying.`)}}__name(assertWithinByteLimit,"assertWithinByteLimit");function assertWithinDurationLimit(config,media,displayName){const maxSeconds=config.getOmniMaxDurationSeconds?.();if(maxSeconds===void 0||maxSeconds<=0)return;const durationMs=media.metadata.durationMs;if(durationMs===void 0||!Number.isFinite(durationMs))return;const seconds=durationMs/1e3;if(seconds>maxSeconds){throw new OmniTransportGuardError(`${displayName} exceeds the omni duration limit: ${Math.round(seconds)}s > ${maxSeconds}s (omni.processing.transportGuard.maxDurationSeconds). Clip a shorter span \u2014 downscaling cannot bring a long file within a duration limit.`)}}__name(assertWithinDurationLimit,"assertWithinDurationLimit");function assertWithinTokenLimit(config,media,displayName){const estimate=estimateRawResourceTokens(media);const maxTokens=config.getOmniMaxEstimatedTokens?.();if(maxTokens===void 0||maxTokens<=0)return estimate;if(estimate.status!=="ok")return estimate;if(estimate.estimatedTokenCount>maxTokens){throw new OmniTransportGuardError(`${displayName} exceeds the omni estimated-token limit: ~${estimate.estimatedTokenCount} tokens (${estimate.method}) > ${maxTokens} (omni.processing.transportGuard.maxEstimatedTokens). Reduce duration/resolution or raise the limit.`)}return estimate}__name(assertWithinTokenLimit,"assertWithinTokenLimit");init_esbuild_shims();import fs from"node:fs/promises";import path2 from"node:path";var debugLogger=createDebugLogger("omni:gc");var OBJECT_NAME_RE=/^([0-9a-f]{64})\.[A-Za-z0-9][A-Za-z0-9.]*$/;var SKIPPED={ran:false,deletedObjects:0,deletedBytes:0,remainingBytes:0,derivationsSuspended:false};var gcOnce=new Map;var suspendedRoots=new Set;function effectiveOmniStorageMaxTotalBytes(config){const configured=config.getOmniStorageMaxTotalBytes();const floor=10*effectiveMaxUploadFileBytes(config);if(configured<floor){debugLogger.warn(`omni.storage.maxTotalBytes (${configured}) is below 10\xD7 the transport guard's single-media limit; using ${floor} bytes instead (the budget must hold at least ten normal uploads).`);return floor}return configured}__name(effectiveOmniStorageMaxTotalBytes,"effectiveOmniStorageMaxTotalBytes");function isOmniDerivationSuspended(omniRootDir){return suspendedRoots.has(path2.resolve(omniRootDir))}__name(isOmniDerivationSuspended,"isOmniDerivationSuspended");async function settleOmniGc(omniRootDir){const existing=gcOnce.get(path2.resolve(omniRootDir));if(existing)await existing}__name(settleOmniGc,"settleOmniGc");async function isRealDirectory(p){try{return(await fs.lstat(p)).isDirectory()}catch{return false}}__name(isRealDirectory,"isRealDirectory");async function listObjects(objectsDir){const out=[];if(!await isRealDirectory(objectsDir))return out;let shards;try{shards=await fs.readdir(objectsDir)}catch{return out}for(const shard of shards){const shardDir=path2.join(objectsDir,shard);if(!await isRealDirectory(shardDir))continue;let names;try{names=await fs.readdir(shardDir)}catch{continue}for(const name of names){const match=OBJECT_NAME_RE.exec(name);if(!match)continue;const filePath=path2.join(shardDir,name);try{const st=await fs.lstat(filePath);if(!st.isFile())continue;out.push({sha256:match[1],filePath,mtimeMs:st.mtimeMs,sizeBytes:st.size})}catch{}}}return out}__name(listObjects,"listObjects");async function deleteObject(object,options){try{await fs.rm(object.filePath,{force:true})}catch(err){debugLogger.debug(`gc: failed to delete ${object.sha256}: ${err instanceof Error?err.message:err}`);return false}try{await options.uploadCache?.removeBySha256(object.sha256)}catch{}try{await options.degradationCache?.removeByOriginalSha256(object.sha256);await options.degradationCache?.removeByDegradedSha256(object.sha256)}catch{}debugLogger.debug(`gc: deleted unreferenced object ${object.sha256} (${object.sizeBytes} bytes)`);return true}__name(deleteObject,"deleteObject");function runOmniGcOnce(options){const rootKey=path2.resolve(options.store.getOmniRootDir());const existing=gcOnce.get(rootKey);if(existing)return existing;const run=sweep(options,rootKey).catch(err=>{debugLogger.debug(`gc: run failed, skipped: ${err instanceof Error?err.message:err}`);return SKIPPED});gcOnce.set(rootKey,run);return run}__name(runOmniGcOnce,"runOmniGcOnce");async function recentlyRecoveredFromCorruption(omniRootDir,retentionDays,nowMs){const prefix=`${MEDIA_MEMORY_FILE_NAME}.corrupt-`;let names;try{names=await fs.readdir(omniRootDir)}catch{return false}const cutoff=nowMs-retentionDays*24*36e5;for(const name of names){if(!name.startsWith(prefix))continue;const stamp=Number(name.slice(prefix.length));if(Number.isFinite(stamp)&&stamp>=cutoff)return true;try{const st=await fs.lstat(path2.join(omniRootDir,name));if(st.mtimeMs>=cutoff)return true}catch{return true}}return false}__name(recentlyRecoveredFromCorruption,"recentlyRecoveredFromCorruption");async function sweep(options,rootKey){const nowMsForGuard=options.nowMs??Date.now();const refs=await options.memoryService.collectManagedRefs();if(refs===null){debugLogger.debug("gc: memory snapshot unreadable, skipping run");return SKIPPED}if(await recentlyRecoveredFromCorruption(options.store.getOmniRootDir(),options.retentionDays,nowMsForGuard)){debugLogger.debug("gc: memory ledger recently recovered from corruption, skipping run");return SKIPPED}const objectsDir=options.store.getObjectsDir();for(const fileRef of options.registry?.activeFileRefs()??[]){const name=path2.basename(fileRef);const match=OBJECT_NAME_RE.exec(name);if(match&&fileRef.startsWith(objectsDir))refs.add(match[1])}const nowMs=options.nowMs??Date.now();const cutoffMs=nowMs-options.retentionDays*24*36e5;const objects=await listObjects(objectsDir);let deletedObjects=0;let deletedBytes=0;const survivors=[];const touchedSinceListing=__name(async(object,freshCutoffMs)=>{try{return(await fs.lstat(object.filePath)).mtimeMs>=freshCutoffMs}catch{return true}},"touchedSinceListing");for(const object of objects){if(refs.has(object.sha256)||object.mtimeMs>=cutoffMs){survivors.push(object);continue}if(await touchedSinceListing(object,cutoffMs)){survivors.push(object);continue}if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes}else{survivors.push(object)}}let remainingBytes=survivors.reduce((sum,o)=>sum+o.sizeBytes,0);if(remainingBytes>options.maxTotalBytes){const freshRefs=await options.memoryService.collectManagedRefs();if(freshRefs===null){debugLogger.debug("gc: ledger unreadable at budget pass, skipping budget deletions")}else{const unreferenced=survivors.filter(o=>!refs.has(o.sha256)&&!freshRefs.has(o.sha256)).sort((a,b)=>a.mtimeMs-b.mtimeMs);for(const object of unreferenced){if(remainingBytes<=options.maxTotalBytes)break;if(await touchedSinceListing(object,nowMs))continue;if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes;remainingBytes-=object.sizeBytes}}}}const derivationsSuspended=remainingBytes>options.maxTotalBytes;if(derivationsSuspended){suspendedRoots.add(rootKey);debugLogger.warn(`omni object store over budget with only referenced objects left (${remainingBytes} > ${options.maxTotalBytes} bytes); new policy derivations are suspended for this session. Raise omni.storage.maxTotalBytes or delete memory records you no longer need \u2014 either change takes effect at the next session start (the GC runs once per process).`)}else{suspendedRoots.delete(rootKey)}if(deletedObjects>0){debugLogger.debug(`gc: removed ${deletedObjects} object(s) / ${deletedBytes} bytes; ${remainingBytes} bytes remain`)}return{ran:true,deletedObjects,deletedBytes,remainingBytes,derivationsSuspended}}__name(sweep,"sweep");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import fs2 from"node:fs/promises";import path3 from"node:path";var debugLogger2=createDebugLogger("omni:policy");var MAX_FILE_ARTIFACT_BYTES=256*1024;var OmniPolicyExecutionError=class extends Error{constructor(message,policyId,options){super(message,options);this.policyId=policyId;this.name="OmniPolicyExecutionError"}static{__name(this,"OmniPolicyExecutionError")}};function resolveArtifactSelector(artifacts,kind,role){if(role!==void 0){const byRole=artifacts[`role:${role}`];if(byRole)return byRole}const byKind=artifacts[`kind:${kind}`];if(byKind)return byKind;return artifacts["*"]??"retain"}__name(resolveArtifactSelector,"resolveArtifactSelector");function resourceConditionContext(recognized,shared){const resource={};const set=__name((field,value)=>{if(typeof value==="number"&&!Number.isNaN(value)){resource[field]=value}},"set");const m=recognized.metadata;set("sizeBytes",recognized.sizeBytes);set("durationMs",m.durationMs);set("width",m.width);set("height",m.height);set("maxWidth",m.width);set("maxHeight",m.height);set("frameRate",m.frameRate);set("frameCount",m.frameCount);set("bitRate",m.bitRate);set("sampleRateHz",m.sampleRateHz);set("channels",m.channels);const estimate=estimateRawResourceTokens(recognized);if(estimate.status==="ok"){set("estimatedTokenCount",estimate.estimatedTokenCount)}return{resource,...shared}}__name(resourceConditionContext,"resourceConditionContext");var MEMORY_ROLE_FIELDS={transcript:"hasTranscript",ocr:"hasOcr",caption:"hasCaption",summary:"hasSummary",keyframe:"hasKeyframes",clip:"hasClip"};async function memoryConditionNamespace(memory,binding){if(!memory||!binding)return void 0;const roles=await memory.service.collectVersionOutputRoles(binding);if(!roles)return void 0;const namespace={};for(const field of Object.values(MEMORY_ROLE_FIELDS)){namespace[field]=0}for(const role of roles){const field=MEMORY_ROLE_FIELDS[role];if(field)namespace[field]=1}return namespace}__name(memoryConditionNamespace,"memoryConditionNamespace");function requestConditionNamespace(items){let total=0;for(const item of items){if(!item.deliver)continue;const estimate=estimateRawResourceTokens(item.recognized);if(estimate.status!=="ok")return void 0;total+=estimate.estimatedTokenCount}return{totalEstimatedMediaTokens:total}}__name(requestConditionNamespace,"requestConditionNamespace");function sortPolicies(policies){return[...policies].sort((a,b)=>b.priority-a.priority||a.id.localeCompare(b.id))}__name(sortPolicies,"sortPolicies");var resourceGates=new Map;async function acquireResourceSlot(rootDir,limit){const effectiveLimit=Math.max(1,Math.floor(limit));let gate=resourceGates.get(rootDir);if(!gate){gate={active:0,waiters:[]};resourceGates.set(rootDir,gate)}const heldGate=gate;if(heldGate.active>=effectiveLimit){await new Promise(resolve=>heldGate.waiters.push(resolve))}else{heldGate.active++}let released=false;return()=>{if(released)return;released=true;const next=heldGate.waiters.shift();if(next){next();return}heldGate.active--;if(heldGate.active===0&&heldGate.waiters.length===0){resourceGates.delete(rootDir)}}}__name(acquireResourceSlot,"acquireResourceSlot");async function runFixedPolicies(config,source,options){const policies=sortPolicies(options.policies);const limits=options.limits??DEFAULT_OMNI_PROCESSING_LIMITS;const releaseSlot=await acquireResourceSlot(options.store.getOmniRootDir(),limits.maxConcurrentResources);try{return await runFixedPoliciesUnbounded(config,source,options,{policies,limits})}finally{releaseSlot()}}__name(runFixedPolicies,"runFixedPolicies");async function runFixedPoliciesUnbounded(config,source,options,normalized){const{policies,limits}=normalized;const cache=options.degradationCache??new OmniDegradationCache(options.store.getOmniRootDir());const records=[];const fileDeliveries=[];const items=[{filePath:source.filePath,recognized:source.recognized,label:source.displayName,origin:source.origin,sha256:source.sha256,memoryBinding:options.memory?.sourceBinding,lineageRuns:new Map,depth:0,deliver:true,process:true}];let runsUsed=0;let artifactsProduced=0;let derivedBytesProduced=0;let budgetExhausted=false;const stopOnBudget=__name((policy,item,reason)=>{budgetExhausted=true;records.push({policyId:policy.id,toolName:policy.toolName,outcome:"budget_exhausted",resource:item.label,error:reason});debugLogger2.debug(`per-root policy budget exhausted on ${item.label}: ${reason}; no further derivation for this root (committed deliveries stand)`)},"stopOnBudget");for(let i=0;i<items.length&&!budgetExhausted;i++){const item=items[i];if(!item.process)continue;if(item.recognized.modality==="image"&&(item.recognized.metadata.frameCount??1)>1){debugLogger2.debug(`animated image ${item.label} (${item.recognized.metadata.frameCount} frames) excluded from policy matching (D9)`);continue}const needsMemoryNamespace=policies.some(policy=>policy.when&&conditionUsesNamespace(policy.when,"memory"));const sharedConditionContext={request:options.conditionContext?.request??requestConditionNamespace(items),session:options.conditionContext?.session,memory:needsMemoryNamespace?await memoryConditionNamespace(options.memory,item.memoryBinding):void 0};for(const policy of policies){if(!policy.mediaTypes.includes(item.recognized.modality))continue;if(!policy.origins.includes(item.origin))continue;const runs=item.lineageRuns.get(policy.id)??0;if(runs>=policy.maxRunsPerLineage)continue;if(policy.when){const evaluation=evaluateFixedPolicyCondition(policy.when,resourceConditionContext(item.recognized,sharedConditionContext));if(evaluation.outcome==="no_match")continue;if(evaluation.outcome==="unavailable"&&policy.onConditionUnavailable==="skip"){records.push({policyId:policy.id,toolName:policy.toolName,outcome:"condition_unavailable",resource:item.label,missingFields:evaluation.missingFields});continue}}if(runsUsed>=limits.maxPolicyRunsPerRoot){stopOnBudget(policy,item,`maxPolicyRunsPerRoot (${limits.maxPolicyRunsPerRoot}) reached`);break}runsUsed++;item.lineageRuns.set(policy.id,runs+1);try{const execution=await executePolicy(config,item,policy,options.store,cache,options.signal,options.memory&&item.memoryBinding?{service:options.memory.service,source:item.memoryBinding}:void 0);records.push({policyId:policy.id,toolName:policy.toolName,outcome:execution.outcome,resource:item.label});if(execution.outcome==="no_op")continue;if(policy.output.source==="omit")item.deliver=false;const childDepth=item.depth+1;const depthAllowsReprocess=childDepth<limits.maxLineageDepth;if(policy.output.reprocessMedia&&!depthAllowsReprocess){debugLogger2.debug(`maxLineageDepth (${limits.maxLineageDepth}) reached under ${item.label}; derivatives deliver but do not re-enter policy matching`)}for(const derived of execution.derived){artifactsProduced++;derivedBytesProduced+=derived.recognized.sizeBytes;items.push({...derived,label:`${item.label} \u2192 ${policy.id}`,origin:"policy",lineageRuns:new Map(item.lineageRuns),depth:childDepth,deliver:resolveArtifactSelector(policy.output.artifacts,derived.recognized.modality,derived.role)==="include",process:policy.output.reprocessMedia&&depthAllowsReprocess})}for(const file of execution.derivedFiles){artifactsProduced++;derivedBytesProduced+=file.sizeBytes;if(resolveArtifactSelector(policy.output.artifacts,"file",file.role)==="include"){fileDeliveries.push(file)}}if(artifactsProduced>limits.maxArtifactsPerRoot){stopOnBudget(policy,item,`maxArtifactsPerRoot (${limits.maxArtifactsPerRoot}) exceeded`);break}if(derivedBytesProduced>limits.maxDerivedBytesPerRoot){stopOnBudget(policy,item,`maxDerivedBytesPerRoot (${limits.maxDerivedBytesPerRoot}) exceeded`);break}}catch(err){if(options.signal?.aborted)throw err;const message=err instanceof Error?err.message:String(err);records.push({policyId:policy.id,toolName:policy.toolName,outcome:"failed",resource:item.label,error:message});debugLogger2.debug(`fixed policy ${policy.id} (${policy.toolName}) failed on ${item.label}: ${message}`);if(policy.onFailure==="abort"||policy.stage==="transport_guard"){throw new OmniPolicyExecutionError(`Fixed policy ${policy.id} failed: ${message}`,policy.id,{cause:err})}}}}return{deliveries:items.filter(item=>item.deliver).map(item=>({filePath:item.filePath,recognized:item.recognized,sha256:item.sha256,disclosure:item.disclosure,degraded:item.degraded,memoryBinding:item.memoryBinding})),fileDeliveries,records}}__name(runFixedPoliciesUnbounded,"runFixedPoliciesUnbounded");async function executePolicy(config,item,policy,store,cache,signal,memory){const tool=config.getToolRegistry().getTool(policy.toolName);const descriptor=tool?.mediaPolicyDescriptor;if(!descriptor){throw new Error(`tool ${policy.toolName} is not a registered media-policy tool`)}item.sha256??=await hashFileSha256(item.filePath,signal);const settingsDefaults=resolvePolicyToolSettings(config,policy.toolName);const effectiveArguments={...settingsDefaults,...policy.arguments};const fingerprint=computePolicyFingerprint(policy.toolName,effectiveArguments,descriptor.version);const startedAt=new Date().toISOString();if(memory){const reusable=await memory.service.findReusableOutputs(item.sha256,fingerprint);const rebuilt=reusable?await rebuildReusedOutputs(reusable,descriptor,store,signal):void 0;if(rebuilt){debugLogger2.debug(`memory reuse hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026 outputs=${rebuilt.outputs.length} (tool not executed)`);const commit=await memory.service.commitPolicySucceeded({invocationId:"memory-reuse",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:rebuilt.outputs});return{outcome:"succeeded",derived:rebuilt.derived.map(d=>({...d,memoryBinding:commit?.mediaBindings.get(d.sha256)})),derivedFiles:rebuilt.derivedFiles}}}const hit=await cache.get(item.sha256,fingerprint);if(hit){try{const objectPath=store.objectPathFor(hit.degradedSha256,hit.extension);const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(stat?.isFile()&&!stat.isSymbolicLink()){const actualSha256=await hashFileSha256(objectPath,signal);if(actualSha256===hit.degradedSha256){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(declared){debugLogger2.debug(`degradation cache hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026`);const commit=memory?await memory.service.commitPolicySucceeded({invocationId:"cache-hit",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:[{kind:"media",objectPath,sha256:hit.degradedSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:hit.role,disclosure:hit.disclosure}]}):void 0;return{outcome:"cache_hit",derived:[{filePath:objectPath,recognized,sha256:hit.degradedSha256,disclosure:hit.disclosure,degraded:true,role:hit.role,memoryBinding:commit?.mediaBindings.get(hit.degradedSha256)}],derivedFiles:[]}}debugLogger2.debug(`degradation cache hit for policy=${policy.id} recognized as undeclared media type ${recognized.detectedMimeType}; dropping the entry and re-transcoding`)}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`degradation cache hit could not be verified for policy=${policy.id}: ${err instanceof Error?err.message:String(err)}; dropping the entry and re-transcoding`)}await cache.removeByDegradedSha256(hit.degradedSha256)}await settleOmniGc(store.getOmniRootDir());if(isOmniDerivationSuspended(store.getOmniRootDir())){throw new Error(`omni object store is over its byte budget with only memory-referenced objects left; new policy derivations are suspended. Raise omni.storage.maxTotalBytes or delete memory records you no longer need, then start a new session \u2014 the budget is re-evaluated once per process.`)}const invocationId=randomBytes(8).toString("hex");const stagingDir=await store.createStagingDir(invocationId);let failure;try{const request={callId:invocationId,name:policy.toolName,args:{...effectiveArguments,inputPath:item.filePath,outputDir:stagingDir},isClientInitiated:true,prompt_id:`omni-fixed-policy-${invocationId}`,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage}};const{executeToolCall}=await import("./nonInteractiveToolExecutor-R5CTTWKD.js");const response=await executeToolCall(config,request,signal??new AbortController().signal,{recordToolResult:false});if(response.error){throw new Error(response.error.message,{cause:response.error})}const batch=response.policyArtifacts;if(!batch||batch.artifacts.length===0){throw new Error(`tool ${policy.toolName} succeeded but produced no policy artifacts`)}const validated=await Promise.all(batch.artifacts.map(artifact=>validateArtifact(artifact,descriptor,stagingDir,signal)));assertRequiredOutputsPresent(descriptor,validated,policy.toolName);if(validated.every(a=>a.sha256===item.sha256)){return{outcome:"no_op",derived:[],derivedFiles:[]}}const promoted=await Promise.all(validated.map(async artifact=>{const mimeType=artifact.kind==="media"?artifact.recognized.detectedMimeType:artifact.mimeType;const put=await store.putFile(artifact.absolutePath,artifact.sha256,extensionForMime(mimeType),signal);return{artifact,objectPath:put.objectPath}}));const derived=[];const derivedFiles=[];for(const{artifact,objectPath}of promoted){if(artifact.kind==="media"){derived.push({filePath:objectPath,recognized:artifact.recognized,sha256:artifact.sha256,disclosure:artifact.disclosure,degraded:artifact.lossy,role:artifact.role})}else{derivedFiles.push({filePath:objectPath,role:artifact.role,mimeType:artifact.mimeType,text:artifact.text,sha256:artifact.sha256,sizeBytes:artifact.sizeBytes,disclosure:artifact.disclosure})}}if(memory){const outputs=promoted.map(({artifact,objectPath})=>artifact.kind==="media"?{kind:"media",objectPath,sha256:artifact.sha256,mediaType:artifact.recognized.modality,metadata:artifact.recognized.metadata,sizeBytes:artifact.recognized.sizeBytes,mimeType:artifact.recognized.detectedMimeType,role:artifact.role,disclosure:artifact.disclosure}:{kind:"text",objectPath,sha256:artifact.sha256,mimeType:artifact.mimeType,text:artifact.text,sizeBytes:artifact.sizeBytes,role:artifact.role,disclosure:artifact.disclosure});const commit=await memory.service.commitPolicySucceeded({invocationId,source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs});if(commit){for(const entry of derived){entry.memoryBinding=commit.mediaBindings.get(entry.sha256)}}}if(validated.length===1&&validated[0].kind==="media"&&validated[0].disclosure){await cache.put(item.sha256,fingerprint,{degradedSha256:validated[0].sha256,extension:extensionForMime(validated[0].recognized.detectedMimeType),disclosure:validated[0].disclosure,mimeType:validated[0].recognized.detectedMimeType,...validated[0].role!==void 0?{role:validated[0].role}:{}})}return{outcome:"succeeded",derived,derivedFiles}}catch(err){failure=err;throw err}finally{if(failure===void 0||signal?.aborted){await store.removeStagingDir(invocationId).catch(()=>{})}else{try{await store.quarantineInvocation(invocationId,{policyId:policy.id,toolName:policy.toolName,reason:failure instanceof Error?failure.message:String(failure)})}catch{await store.removeStagingDir(invocationId).catch(()=>{})}}}}__name(executePolicy,"executePolicy");async function rebuildReusedOutputs(reusable,descriptor,store,signal){const outputs=[];const derived=[];const derivedFiles=[];try{for(const record of reusable.outputs){const objectPath=record.objectPath??store.objectPathFor(record.sha256,extensionForMime(record.mimeType));const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink())return void 0;if(await hashFileSha256(objectPath,signal)!==record.sha256){return void 0}if(record.kind==="media"){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!declared)return void 0;outputs.push({kind:"media",objectPath,sha256:record.sha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:record.role,disclosure:record.disclosure});derived.push({filePath:objectPath,recognized,sha256:record.sha256,disclosure:record.disclosure,degraded:record.disclosure!==void 0,role:record.role})}else{const text=await fs2.readFile(objectPath,"utf8");outputs.push({kind:"text",objectPath,sha256:record.sha256,mimeType:record.mimeType,text,sizeBytes:record.sizeBytes,role:record.role,disclosure:record.disclosure});derivedFiles.push({filePath:objectPath,role:record.role,mimeType:record.mimeType,text,sha256:record.sha256,sizeBytes:record.sizeBytes,disclosure:record.disclosure})}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`memory reuse could not be verified, re-deriving: ${err instanceof Error?err.message:String(err)}`);return void 0}return{outputs,derived,derivedFiles}}__name(rebuildReusedOutputs,"rebuildReusedOutputs");async function validateArtifact(artifact,descriptor,stagingDir,signal){if(artifact.storage!=="workspace"||!artifact.workspacePath){throw new Error(`policy artifact "${artifact.title}" is not a workspace file`)}const absolutePath=path3.resolve(stagingDir,artifact.workspacePath);if(!absolutePath.startsWith(stagingDir+path3.sep)){throw new Error(`policy artifact "${artifact.title}" escapes the staging directory`)}const stat=await fs2.lstat(absolutePath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink()){throw new Error(`policy artifact "${artifact.title}" is missing or not a regular file`)}const rawRole=artifact.metadata?.["omniRole"];const role=typeof rawRole==="string"&&rawRole?rawRole:void 0;const rawDisclosure=artifact.metadata?.["omniDisclosure"];const disclosure=typeof rawDisclosure==="string"&&rawDisclosure?rawDisclosure:void 0;if(artifact.kind==="file"){const spec2=descriptor.outputs.find(o=>o.kind==="file"&&(o.role===void 0||o.role===role)&&artifact.mimeType!==void 0&&o.mimeTypes?.includes(artifact.mimeType));if(!spec2){throw new Error(`policy artifact "${artifact.title}" (file, role ${role??"none"}, ${artifact.mimeType??"no mimeType"}) matches no declared file output`)}if(stat.size>MAX_FILE_ARTIFACT_BYTES){throw new Error(`policy artifact "${artifact.title}" exceeds the file-artifact size budget (${stat.size} > ${MAX_FILE_ARTIFACT_BYTES} bytes)`)}const bytes=await fs2.readFile(absolutePath);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new Error(`policy artifact "${artifact.title}" is not valid UTF-8 text`)}if(spec2.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"file",absolutePath,mimeType:artifact.mimeType,text,sizeBytes:bytes.byteLength,sha256:createHash2("sha256").update(bytes).digest("hex"),disclosure,lossy:spec2.lossy===true,role}}const recognized=await recognizeMediaFile(absolutePath,{signal});const spec=descriptor.outputs.find(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!spec){throw new Error(`policy artifact "${artifact.title}" has undeclared media type ${recognized.detectedMimeType}`)}if(artifact.kind!==recognized.modality){throw new Error(`policy artifact "${artifact.title}" declares kind ${String(artifact.kind)} but contains ${recognized.modality} content`)}if(spec.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"media",absolutePath,recognized,sha256:await hashFileSha256(absolutePath,signal),disclosure,lossy:spec.lossy===true,role}}__name(validateArtifact,"validateArtifact");function assertRequiredOutputsPresent(descriptor,validated,toolName){for(const spec of descriptor.outputs){if(!spec.required)continue;let produced;if(spec.kind==="media"){produced=validated.some(a=>a.kind==="media"&&spec.mimeTypes?.includes(a.recognized.detectedMimeType))}else if(spec.kind==="file"){produced=validated.some(a=>a.kind==="file"&&(spec.role===void 0||a.role===spec.role)&&spec.mimeTypes?.includes(a.mimeType))}else{continue}if(!produced){throw new Error(`tool ${toolName} did not produce its required ${spec.kind} ${spec.mimeTypes?.join("/")??spec.role??""} output`)}}}__name(assertRequiredOutputsPresent,"assertRequiredOutputsPresent");export{estimateRawResourceTokens,computePolicyFingerprint,OmniDegradationCache,DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES,OmniTransportGuardError,effectiveMaxUploadFileBytes,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveOmniStorageMaxTotalBytes,runOmniGcOnce,OmniPolicyExecutionError,runFixedPolicies,validateArtifact,assertRequiredOutputsPresent};
|
|
5
|
+
${toolVersion}`).digest("hex")}__name(computePolicyFingerprint,"computePolicyFingerprint");var OmniDegradationCache=class{static{__name(this,"OmniDegradationCache")}file;constructor(omniRootDir){this.file=new OmniJsonCacheFile(path.join(omniRootDir,"policy-cache.json"),"omni:policy-cache")}key(originalSha256,policyFingerprint){return`${originalSha256}|${policyFingerprint}`}async get(originalSha256,policyFingerprint){return this.file.access(null,entries=>{const key=this.key(originalSha256,policyFingerprint);const entry=entries[key];if(!entry)return{result:null};if(!/^[0-9a-f]{64}$/.test(entry.degradedSha256)||typeof entry.extension!=="string"||!OBJECT_EXTENSION_RE.test(entry.extension)||typeof entry.disclosure!=="string"||entry.disclosure.length===0||entry.disclosure.length>MAX_CACHED_DISCLOSURE_LENGTH||typeof entry.mimeType!=="string"||entry.mimeType.length===0||entry.role!==void 0&&(typeof entry.role!=="string"||entry.role.length===0)){delete entries[key];return{result:null,changed:true}}return{result:entry}})}async put(originalSha256,policyFingerprint,entry){return this.file.access(void 0,entries=>{entries[this.key(originalSha256,policyFingerprint)]={...entry,createdAt:new Date().toISOString()};return{result:void 0,changed:true}})}async removeByOriginalSha256(originalSha256){return this.file.access(void 0,entries=>{const prefix=`${originalSha256}|`;let changed=false;for(const k of Object.keys(entries)){if(k.startsWith(prefix)){delete entries[k];changed=true}}return{result:void 0,changed}})}async removeByDegradedSha256(degradedSha256){return this.file.access(void 0,entries=>{let changed=false;for(const[k,v]of Object.entries(entries)){if(v.degradedSha256===degradedSha256){delete entries[k];changed=true}}return{result:void 0,changed}})}};init_esbuild_shims();var DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES=1024*1024*1024;var OmniTransportGuardError=class extends Error{static{__name(this,"OmniTransportGuardError")}sessionResourceId;constructor(message,options){super(message,options);this.name="OmniTransportGuardError"}};function effectiveMaxUploadFileBytes(config){const configured=config.getOmniMaxUploadFileBytes?.();return configured!==void 0&&configured>0?configured:DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES}__name(effectiveMaxUploadFileBytes,"effectiveMaxUploadFileBytes");function assertWithinByteLimit(config,sizeBytes,displayName){const maxBytes=effectiveMaxUploadFileBytes(config);if(sizeBytes>maxBytes){throw new OmniTransportGuardError(`${displayName} exceeds the omni upload limit: ${sizeBytes} bytes > ${maxBytes} bytes (omni.processing.transportGuard.maxUploadFileBytes). Reduce the file size before retrying.`)}}__name(assertWithinByteLimit,"assertWithinByteLimit");function assertWithinDurationLimit(config,media,displayName){const maxSeconds=config.getOmniMaxDurationSeconds?.();if(maxSeconds===void 0||maxSeconds<=0)return;const durationMs=media.metadata.durationMs;if(durationMs===void 0||!Number.isFinite(durationMs))return;const seconds=durationMs/1e3;if(seconds>maxSeconds){throw new OmniTransportGuardError(`${displayName} exceeds the omni duration limit: ${Math.round(seconds)}s > ${maxSeconds}s (omni.processing.transportGuard.maxDurationSeconds). Clip a shorter span \u2014 downscaling cannot bring a long file within a duration limit.`)}}__name(assertWithinDurationLimit,"assertWithinDurationLimit");function assertWithinTokenLimit(config,media,displayName){const estimate=estimateRawResourceTokens(media);const maxTokens=config.getOmniMaxEstimatedTokens?.();if(maxTokens===void 0||maxTokens<=0)return estimate;if(estimate.status!=="ok")return estimate;if(estimate.estimatedTokenCount>maxTokens){throw new OmniTransportGuardError(`${displayName} exceeds the omni estimated-token limit: ~${estimate.estimatedTokenCount} tokens (${estimate.method}) > ${maxTokens} (omni.processing.transportGuard.maxEstimatedTokens). Reduce duration/resolution or raise the limit.`)}return estimate}__name(assertWithinTokenLimit,"assertWithinTokenLimit");init_esbuild_shims();import fs from"node:fs/promises";import path2 from"node:path";var debugLogger=createDebugLogger("omni:gc");var OBJECT_NAME_RE=/^([0-9a-f]{64})\.[A-Za-z0-9][A-Za-z0-9.]*$/;var SKIPPED={ran:false,deletedObjects:0,deletedBytes:0,remainingBytes:0,derivationsSuspended:false};var gcOnce=new Map;var suspendedRoots=new Set;function effectiveOmniStorageMaxTotalBytes(config){const configured=config.getOmniStorageMaxTotalBytes();const floor=10*effectiveMaxUploadFileBytes(config);if(configured<floor){debugLogger.warn(`omni.storage.maxTotalBytes (${configured}) is below 10\xD7 the transport guard's single-media limit; using ${floor} bytes instead (the budget must hold at least ten normal uploads).`);return floor}return configured}__name(effectiveOmniStorageMaxTotalBytes,"effectiveOmniStorageMaxTotalBytes");function isOmniDerivationSuspended(omniRootDir){return suspendedRoots.has(path2.resolve(omniRootDir))}__name(isOmniDerivationSuspended,"isOmniDerivationSuspended");async function settleOmniGc(omniRootDir){const existing=gcOnce.get(path2.resolve(omniRootDir));if(existing)await existing}__name(settleOmniGc,"settleOmniGc");async function isRealDirectory(p){try{return(await fs.lstat(p)).isDirectory()}catch{return false}}__name(isRealDirectory,"isRealDirectory");async function listObjects(objectsDir){const out=[];if(!await isRealDirectory(objectsDir))return out;let shards;try{shards=await fs.readdir(objectsDir)}catch{return out}for(const shard of shards){const shardDir=path2.join(objectsDir,shard);if(!await isRealDirectory(shardDir))continue;let names;try{names=await fs.readdir(shardDir)}catch{continue}for(const name of names){const match=OBJECT_NAME_RE.exec(name);if(!match)continue;const filePath=path2.join(shardDir,name);try{const st=await fs.lstat(filePath);if(!st.isFile())continue;out.push({sha256:match[1],filePath,mtimeMs:st.mtimeMs,sizeBytes:st.size})}catch{}}}return out}__name(listObjects,"listObjects");async function deleteObject(object,options){try{await fs.rm(object.filePath,{force:true})}catch(err){debugLogger.debug(`gc: failed to delete ${object.sha256}: ${err instanceof Error?err.message:err}`);return false}try{await options.uploadCache?.removeBySha256(object.sha256)}catch{}try{await options.degradationCache?.removeByOriginalSha256(object.sha256);await options.degradationCache?.removeByDegradedSha256(object.sha256)}catch{}debugLogger.debug(`gc: deleted unreferenced object ${object.sha256} (${object.sizeBytes} bytes)`);return true}__name(deleteObject,"deleteObject");function runOmniGcOnce(options){const rootKey=path2.resolve(options.store.getOmniRootDir());const existing=gcOnce.get(rootKey);if(existing)return existing;const run=sweep(options,rootKey).catch(err=>{debugLogger.debug(`gc: run failed, skipped: ${err instanceof Error?err.message:err}`);return SKIPPED});gcOnce.set(rootKey,run);return run}__name(runOmniGcOnce,"runOmniGcOnce");async function recentlyRecoveredFromCorruption(omniRootDir,retentionDays,nowMs){const prefix=`${MEDIA_MEMORY_FILE_NAME}.corrupt-`;let names;try{names=await fs.readdir(omniRootDir)}catch{return false}const cutoff=nowMs-retentionDays*24*36e5;for(const name of names){if(!name.startsWith(prefix))continue;const stamp=Number(name.slice(prefix.length));if(Number.isFinite(stamp)&&stamp>=cutoff)return true;try{const st=await fs.lstat(path2.join(omniRootDir,name));if(st.mtimeMs>=cutoff)return true}catch{return true}}return false}__name(recentlyRecoveredFromCorruption,"recentlyRecoveredFromCorruption");async function sweep(options,rootKey){const nowMsForGuard=options.nowMs??Date.now();const refs=await options.memoryService.collectManagedRefs();if(refs===null){debugLogger.debug("gc: memory snapshot unreadable, skipping run");return SKIPPED}if(await recentlyRecoveredFromCorruption(options.store.getOmniRootDir(),options.retentionDays,nowMsForGuard)){debugLogger.debug("gc: memory ledger recently recovered from corruption, skipping run");return SKIPPED}const objectsDir=options.store.getObjectsDir();for(const fileRef of options.registry?.activeFileRefs()??[]){const name=path2.basename(fileRef);const match=OBJECT_NAME_RE.exec(name);if(match&&fileRef.startsWith(objectsDir))refs.add(match[1])}const nowMs=options.nowMs??Date.now();const cutoffMs=nowMs-options.retentionDays*24*36e5;const objects=await listObjects(objectsDir);let deletedObjects=0;let deletedBytes=0;const survivors=[];const touchedSinceListing=__name(async(object,freshCutoffMs)=>{try{return(await fs.lstat(object.filePath)).mtimeMs>=freshCutoffMs}catch{return true}},"touchedSinceListing");for(const object of objects){if(refs.has(object.sha256)||object.mtimeMs>=cutoffMs){survivors.push(object);continue}if(await touchedSinceListing(object,cutoffMs)){survivors.push(object);continue}if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes}else{survivors.push(object)}}let remainingBytes=survivors.reduce((sum,o)=>sum+o.sizeBytes,0);if(remainingBytes>options.maxTotalBytes){const freshRefs=await options.memoryService.collectManagedRefs();if(freshRefs===null){debugLogger.debug("gc: ledger unreadable at budget pass, skipping budget deletions")}else{const unreferenced=survivors.filter(o=>!refs.has(o.sha256)&&!freshRefs.has(o.sha256)).sort((a,b)=>a.mtimeMs-b.mtimeMs);for(const object of unreferenced){if(remainingBytes<=options.maxTotalBytes)break;if(await touchedSinceListing(object,nowMs))continue;if(await deleteObject(object,options)){deletedObjects+=1;deletedBytes+=object.sizeBytes;remainingBytes-=object.sizeBytes}}}}const derivationsSuspended=remainingBytes>options.maxTotalBytes;if(derivationsSuspended){suspendedRoots.add(rootKey);debugLogger.warn(`omni object store over budget with only referenced objects left (${remainingBytes} > ${options.maxTotalBytes} bytes); new policy derivations are suspended for this session. Raise omni.storage.maxTotalBytes or delete memory records you no longer need \u2014 either change takes effect at the next session start (the GC runs once per process).`)}else{suspendedRoots.delete(rootKey)}if(deletedObjects>0){debugLogger.debug(`gc: removed ${deletedObjects} object(s) / ${deletedBytes} bytes; ${remainingBytes} bytes remain`)}return{ran:true,deletedObjects,deletedBytes,remainingBytes,derivationsSuspended}}__name(sweep,"sweep");init_esbuild_shims();import{createHash as createHash2,randomBytes}from"node:crypto";import fs2 from"node:fs/promises";import path3 from"node:path";var debugLogger2=createDebugLogger("omni:policy");var MAX_FILE_ARTIFACT_BYTES=256*1024;var OmniPolicyExecutionError=class extends Error{constructor(message,policyId,options){super(message,options);this.policyId=policyId;this.name="OmniPolicyExecutionError"}static{__name(this,"OmniPolicyExecutionError")}};function resolveArtifactSelector(artifacts,kind,role){if(role!==void 0){const byRole=artifacts[`role:${role}`];if(byRole)return byRole}const byKind=artifacts[`kind:${kind}`];if(byKind)return byKind;return artifacts["*"]??"retain"}__name(resolveArtifactSelector,"resolveArtifactSelector");function resourceConditionContext(recognized,shared){const resource={};const set=__name((field,value)=>{if(typeof value==="number"&&!Number.isNaN(value)){resource[field]=value}},"set");const m=recognized.metadata;set("sizeBytes",recognized.sizeBytes);set("durationMs",m.durationMs);set("width",m.width);set("height",m.height);set("maxWidth",m.width);set("maxHeight",m.height);set("frameRate",m.frameRate);set("frameCount",m.frameCount);set("bitRate",m.bitRate);set("sampleRateHz",m.sampleRateHz);set("channels",m.channels);const estimate=estimateRawResourceTokens(recognized);if(estimate.status==="ok"){set("estimatedTokenCount",estimate.estimatedTokenCount)}return{resource,...shared}}__name(resourceConditionContext,"resourceConditionContext");var MEMORY_ROLE_FIELDS={transcript:"hasTranscript",ocr:"hasOcr",caption:"hasCaption",summary:"hasSummary",keyframe:"hasKeyframes",clip:"hasClip"};async function memoryConditionNamespace(memory,binding){if(!memory||!binding)return void 0;const roles=await memory.service.collectVersionOutputRoles(binding);if(!roles)return void 0;const namespace={};for(const field of Object.values(MEMORY_ROLE_FIELDS)){namespace[field]=0}for(const role of roles){const field=MEMORY_ROLE_FIELDS[role];if(field)namespace[field]=1}return namespace}__name(memoryConditionNamespace,"memoryConditionNamespace");function requestConditionNamespace(items){let total=0;for(const item of items){if(!item.deliver)continue;const estimate=estimateRawResourceTokens(item.recognized);if(estimate.status!=="ok")return void 0;total+=estimate.estimatedTokenCount}return{totalEstimatedMediaTokens:total}}__name(requestConditionNamespace,"requestConditionNamespace");function sortPolicies(policies){return[...policies].sort((a,b)=>b.priority-a.priority||a.id.localeCompare(b.id))}__name(sortPolicies,"sortPolicies");var resourceGates=new Map;async function acquireResourceSlot(rootDir,limit){const effectiveLimit=Math.max(1,Math.floor(limit));let gate=resourceGates.get(rootDir);if(!gate){gate={active:0,waiters:[]};resourceGates.set(rootDir,gate)}const heldGate=gate;if(heldGate.active>=effectiveLimit){await new Promise(resolve=>heldGate.waiters.push(resolve))}else{heldGate.active++}let released=false;return()=>{if(released)return;released=true;const next=heldGate.waiters.shift();if(next){next();return}heldGate.active--;if(heldGate.active===0&&heldGate.waiters.length===0){resourceGates.delete(rootDir)}}}__name(acquireResourceSlot,"acquireResourceSlot");async function runFixedPolicies(config,source,options){const policies=sortPolicies(options.policies);const limits=options.limits??DEFAULT_OMNI_PROCESSING_LIMITS;const releaseSlot=await acquireResourceSlot(options.store.getOmniRootDir(),limits.maxConcurrentResources);try{return await runFixedPoliciesUnbounded(config,source,options,{policies,limits})}finally{releaseSlot()}}__name(runFixedPolicies,"runFixedPolicies");async function runFixedPoliciesUnbounded(config,source,options,normalized){const{policies,limits}=normalized;const cache=options.degradationCache??new OmniDegradationCache(options.store.getOmniRootDir());const records=[];const fileDeliveries=[];const items=[{filePath:source.filePath,recognized:source.recognized,label:source.displayName,origin:source.origin,sha256:source.sha256,memoryBinding:options.memory?.sourceBinding,lineageRuns:new Map,depth:0,deliver:true,process:true}];let runsUsed=0;let artifactsProduced=0;let derivedBytesProduced=0;let budgetExhausted=false;const stopOnBudget=__name((policy,item,reason)=>{budgetExhausted=true;records.push({policyId:policy.id,toolName:policy.toolName,outcome:"budget_exhausted",resource:item.label,error:reason});debugLogger2.debug(`per-root policy budget exhausted on ${item.label}: ${reason}; no further derivation for this root (committed deliveries stand)`)},"stopOnBudget");for(let i=0;i<items.length&&!budgetExhausted;i++){const item=items[i];if(!item.process)continue;if(item.recognized.modality==="image"&&(item.recognized.metadata.frameCount??1)>1){debugLogger2.debug(`animated image ${item.label} (${item.recognized.metadata.frameCount} frames) excluded from policy matching (D9)`);continue}const needsMemoryNamespace=policies.some(policy=>policy.when&&conditionUsesNamespace(policy.when,"memory"));const sharedConditionContext={request:options.conditionContext?.request??requestConditionNamespace(items),session:options.conditionContext?.session,memory:needsMemoryNamespace?await memoryConditionNamespace(options.memory,item.memoryBinding):void 0};for(const policy of policies){if(!policy.mediaTypes.includes(item.recognized.modality))continue;if(!policy.origins.includes(item.origin))continue;const runs=item.lineageRuns.get(policy.id)??0;if(runs>=policy.maxRunsPerLineage)continue;if(policy.when){const evaluation=evaluateFixedPolicyCondition(policy.when,resourceConditionContext(item.recognized,sharedConditionContext));if(evaluation.outcome==="no_match")continue;if(evaluation.outcome==="unavailable"&&policy.onConditionUnavailable==="skip"){records.push({policyId:policy.id,toolName:policy.toolName,outcome:"condition_unavailable",resource:item.label,missingFields:evaluation.missingFields});continue}}if(runsUsed>=limits.maxPolicyRunsPerRoot){stopOnBudget(policy,item,`maxPolicyRunsPerRoot (${limits.maxPolicyRunsPerRoot}) reached`);break}runsUsed++;item.lineageRuns.set(policy.id,runs+1);try{const execution=await executePolicy(config,item,policy,options.store,cache,options.signal,options.memory&&item.memoryBinding?{service:options.memory.service,source:item.memoryBinding}:void 0);records.push({policyId:policy.id,toolName:policy.toolName,outcome:execution.outcome,resource:item.label});if(execution.outcome==="no_op")continue;if(policy.output.source==="omit")item.deliver=false;const childDepth=item.depth+1;const depthAllowsReprocess=childDepth<limits.maxLineageDepth;if(policy.output.reprocessMedia&&!depthAllowsReprocess){debugLogger2.debug(`maxLineageDepth (${limits.maxLineageDepth}) reached under ${item.label}; derivatives deliver but do not re-enter policy matching`)}for(const derived of execution.derived){artifactsProduced++;derivedBytesProduced+=derived.recognized.sizeBytes;items.push({...derived,label:`${item.label} \u2192 ${policy.id}`,origin:"policy",lineageRuns:new Map(item.lineageRuns),depth:childDepth,deliver:resolveArtifactSelector(policy.output.artifacts,derived.recognized.modality,derived.role)==="include",process:policy.output.reprocessMedia&&depthAllowsReprocess})}for(const file of execution.derivedFiles){artifactsProduced++;derivedBytesProduced+=file.sizeBytes;if(resolveArtifactSelector(policy.output.artifacts,"file",file.role)==="include"){fileDeliveries.push(file)}}if(artifactsProduced>limits.maxArtifactsPerRoot){stopOnBudget(policy,item,`maxArtifactsPerRoot (${limits.maxArtifactsPerRoot}) exceeded`);break}if(derivedBytesProduced>limits.maxDerivedBytesPerRoot){stopOnBudget(policy,item,`maxDerivedBytesPerRoot (${limits.maxDerivedBytesPerRoot}) exceeded`);break}}catch(err){if(options.signal?.aborted)throw err;const message=err instanceof Error?err.message:String(err);records.push({policyId:policy.id,toolName:policy.toolName,outcome:"failed",resource:item.label,error:message});debugLogger2.debug(`fixed policy ${policy.id} (${policy.toolName}) failed on ${item.label}: ${message}`);if(policy.onFailure==="abort"||policy.stage==="transport_guard"){throw new OmniPolicyExecutionError(`Fixed policy ${policy.id} failed: ${message}`,policy.id,{cause:err})}}}}return{deliveries:items.filter(item=>item.deliver).map(item=>({filePath:item.filePath,recognized:item.recognized,sha256:item.sha256,disclosure:item.disclosure,degraded:item.degraded,memoryBinding:item.memoryBinding})),fileDeliveries,records}}__name(runFixedPoliciesUnbounded,"runFixedPoliciesUnbounded");async function executePolicy(config,item,policy,store,cache,signal,memory){const tool=config.getToolRegistry().getTool(policy.toolName);const descriptor=tool?.mediaPolicyDescriptor;if(!descriptor){throw new Error(`tool ${policy.toolName} is not a registered media-policy tool`)}item.sha256??=await hashFileSha256(item.filePath,signal);const settingsDefaults=resolvePolicyToolSettings(config,policy.toolName);const effectiveArguments={...settingsDefaults,...policy.arguments};const fingerprint=computePolicyFingerprint(policy.toolName,effectiveArguments,descriptor.version);const startedAt=new Date().toISOString();if(memory){const reusable=await memory.service.findReusableOutputs(item.sha256,fingerprint);const rebuilt=reusable?await rebuildReusedOutputs(reusable,descriptor,store,signal):void 0;if(rebuilt){debugLogger2.debug(`memory reuse hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026 outputs=${rebuilt.outputs.length} (tool not executed)`);const commit=await memory.service.commitPolicySucceeded({invocationId:"memory-reuse",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:rebuilt.outputs});return{outcome:"succeeded",derived:rebuilt.derived.map(d=>({...d,memoryBinding:commit?.mediaBindings.get(d.sha256)})),derivedFiles:rebuilt.derivedFiles}}}const hit=await cache.get(item.sha256,fingerprint);if(hit){try{const objectPath=store.objectPathFor(hit.degradedSha256,hit.extension);const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(stat?.isFile()&&!stat.isSymbolicLink()){const actualSha256=await hashFileSha256(objectPath,signal);if(actualSha256===hit.degradedSha256){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(declared){debugLogger2.debug(`degradation cache hit: policy=${policy.id} sha256=${item.sha256.slice(0,12)}\u2026`);const commit=memory?await memory.service.commitPolicySucceeded({invocationId:"cache-hit",source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs:[{kind:"media",objectPath,sha256:hit.degradedSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:hit.role,disclosure:hit.disclosure}]}):void 0;return{outcome:"cache_hit",derived:[{filePath:objectPath,recognized,sha256:hit.degradedSha256,disclosure:hit.disclosure,degraded:true,role:hit.role,memoryBinding:commit?.mediaBindings.get(hit.degradedSha256)}],derivedFiles:[]}}debugLogger2.debug(`degradation cache hit for policy=${policy.id} recognized as undeclared media type ${recognized.detectedMimeType}; dropping the entry and re-transcoding`)}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`degradation cache hit could not be verified for policy=${policy.id}: ${err instanceof Error?err.message:String(err)}; dropping the entry and re-transcoding`)}await cache.removeByDegradedSha256(hit.degradedSha256)}await settleOmniGc(store.getOmniRootDir());if(isOmniDerivationSuspended(store.getOmniRootDir())){throw new Error(`omni object store is over its byte budget with only memory-referenced objects left; new policy derivations are suspended. Raise omni.storage.maxTotalBytes or delete memory records you no longer need, then start a new session \u2014 the budget is re-evaluated once per process.`)}const invocationId=randomBytes(8).toString("hex");const stagingDir=await store.createStagingDir(invocationId);let failure;try{const request={callId:invocationId,name:policy.toolName,args:{...effectiveArguments,inputPath:item.filePath,outputDir:stagingDir},isClientInitiated:true,prompt_id:`omni-fixed-policy-${invocationId}`,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage}};const{executeToolCall}=await import("./nonInteractiveToolExecutor-N7PCYCKO.js");const response=await executeToolCall(config,request,signal??new AbortController().signal,{recordToolResult:false});if(response.error){throw new Error(response.error.message,{cause:response.error})}const batch=response.policyArtifacts;if(!batch||batch.artifacts.length===0){throw new Error(`tool ${policy.toolName} succeeded but produced no policy artifacts`)}const validated=await Promise.all(batch.artifacts.map(artifact=>validateArtifact(artifact,descriptor,stagingDir,signal)));assertRequiredOutputsPresent(descriptor,validated,policy.toolName);if(validated.every(a=>a.sha256===item.sha256)){return{outcome:"no_op",derived:[],derivedFiles:[]}}const promoted=await Promise.all(validated.map(async artifact=>{const mimeType=artifact.kind==="media"?artifact.recognized.detectedMimeType:artifact.mimeType;const put=await store.putFile(artifact.absolutePath,artifact.sha256,extensionForMime(mimeType),signal);return{artifact,objectPath:put.objectPath}}));const derived=[];const derivedFiles=[];for(const{artifact,objectPath}of promoted){if(artifact.kind==="media"){derived.push({filePath:objectPath,recognized:artifact.recognized,sha256:artifact.sha256,disclosure:artifact.disclosure,degraded:artifact.lossy,role:artifact.role})}else{derivedFiles.push({filePath:objectPath,role:artifact.role,mimeType:artifact.mimeType,text:artifact.text,sha256:artifact.sha256,sizeBytes:artifact.sizeBytes,disclosure:artifact.disclosure})}}if(memory){const outputs=promoted.map(({artifact,objectPath})=>artifact.kind==="media"?{kind:"media",objectPath,sha256:artifact.sha256,mediaType:artifact.recognized.modality,metadata:artifact.recognized.metadata,sizeBytes:artifact.recognized.sizeBytes,mimeType:artifact.recognized.detectedMimeType,role:artifact.role,disclosure:artifact.disclosure}:{kind:"text",objectPath,sha256:artifact.sha256,mimeType:artifact.mimeType,text:artifact.text,sizeBytes:artifact.sizeBytes,role:artifact.role,disclosure:artifact.disclosure});const commit=await memory.service.commitPolicySucceeded({invocationId,source:memory.source,executionOrigin:{kind:"fixed_policy",policyId:policy.id,stage:policy.stage},toolName:policy.toolName,toolVersion:descriptor.version,finalArguments:effectiveArguments,omniConfigHash:fingerprint,startedAt,completedAt:new Date().toISOString(),outputs});if(commit){for(const entry of derived){entry.memoryBinding=commit.mediaBindings.get(entry.sha256)}}}if(validated.length===1&&validated[0].kind==="media"&&validated[0].disclosure){await cache.put(item.sha256,fingerprint,{degradedSha256:validated[0].sha256,extension:extensionForMime(validated[0].recognized.detectedMimeType),disclosure:validated[0].disclosure,mimeType:validated[0].recognized.detectedMimeType,...validated[0].role!==void 0?{role:validated[0].role}:{}})}return{outcome:"succeeded",derived,derivedFiles}}catch(err){failure=err;throw err}finally{if(failure===void 0||signal?.aborted){await store.removeStagingDir(invocationId).catch(()=>{})}else{try{await store.quarantineInvocation(invocationId,{policyId:policy.id,toolName:policy.toolName,reason:failure instanceof Error?failure.message:String(failure)})}catch{await store.removeStagingDir(invocationId).catch(()=>{})}}}}__name(executePolicy,"executePolicy");async function rebuildReusedOutputs(reusable,descriptor,store,signal){const outputs=[];const derived=[];const derivedFiles=[];try{for(const record of reusable.outputs){const objectPath=record.objectPath??store.objectPathFor(record.sha256,extensionForMime(record.mimeType));const stat=await fs2.lstat(objectPath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink())return void 0;if(await hashFileSha256(objectPath,signal)!==record.sha256){return void 0}if(record.kind==="media"){const recognized=await recognizeMediaFile(objectPath,{signal});const declared=descriptor.outputs.some(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!declared)return void 0;outputs.push({kind:"media",objectPath,sha256:record.sha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,role:record.role,disclosure:record.disclosure});derived.push({filePath:objectPath,recognized,sha256:record.sha256,disclosure:record.disclosure,degraded:record.disclosure!==void 0,role:record.role})}else{const text=await fs2.readFile(objectPath,"utf8");outputs.push({kind:"text",objectPath,sha256:record.sha256,mimeType:record.mimeType,text,sizeBytes:record.sizeBytes,role:record.role,disclosure:record.disclosure});derivedFiles.push({filePath:objectPath,role:record.role,mimeType:record.mimeType,text,sha256:record.sha256,sizeBytes:record.sizeBytes,disclosure:record.disclosure})}}}catch(err){if(signal?.aborted)throw err;debugLogger2.debug(`memory reuse could not be verified, re-deriving: ${err instanceof Error?err.message:String(err)}`);return void 0}return{outputs,derived,derivedFiles}}__name(rebuildReusedOutputs,"rebuildReusedOutputs");async function validateArtifact(artifact,descriptor,stagingDir,signal){if(artifact.storage!=="workspace"||!artifact.workspacePath){throw new Error(`policy artifact "${artifact.title}" is not a workspace file`)}const absolutePath=path3.resolve(stagingDir,artifact.workspacePath);if(!absolutePath.startsWith(stagingDir+path3.sep)){throw new Error(`policy artifact "${artifact.title}" escapes the staging directory`)}const stat=await fs2.lstat(absolutePath).catch(()=>void 0);if(!stat?.isFile()||stat.isSymbolicLink()){throw new Error(`policy artifact "${artifact.title}" is missing or not a regular file`)}const rawRole=artifact.metadata?.["omniRole"];const role=typeof rawRole==="string"&&rawRole?rawRole:void 0;const rawDisclosure=artifact.metadata?.["omniDisclosure"];const disclosure=typeof rawDisclosure==="string"&&rawDisclosure?rawDisclosure:void 0;if(artifact.kind==="file"){const spec2=descriptor.outputs.find(o=>o.kind==="file"&&(o.role===void 0||o.role===role)&&artifact.mimeType!==void 0&&o.mimeTypes?.includes(artifact.mimeType));if(!spec2){throw new Error(`policy artifact "${artifact.title}" (file, role ${role??"none"}, ${artifact.mimeType??"no mimeType"}) matches no declared file output`)}if(stat.size>MAX_FILE_ARTIFACT_BYTES){throw new Error(`policy artifact "${artifact.title}" exceeds the file-artifact size budget (${stat.size} > ${MAX_FILE_ARTIFACT_BYTES} bytes)`)}const bytes=await fs2.readFile(absolutePath);let text;try{text=new TextDecoder("utf-8",{fatal:true}).decode(bytes)}catch{throw new Error(`policy artifact "${artifact.title}" is not valid UTF-8 text`)}if(spec2.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"file",absolutePath,mimeType:artifact.mimeType,text,sizeBytes:bytes.byteLength,sha256:createHash2("sha256").update(bytes).digest("hex"),disclosure,lossy:spec2.lossy===true,role}}const recognized=await recognizeMediaFile(absolutePath,{signal});const spec=descriptor.outputs.find(o=>o.kind==="media"&&o.mimeTypes?.includes(recognized.detectedMimeType));if(!spec){throw new Error(`policy artifact "${artifact.title}" has undeclared media type ${recognized.detectedMimeType}`)}if(artifact.kind!==recognized.modality){throw new Error(`policy artifact "${artifact.title}" declares kind ${String(artifact.kind)} but contains ${recognized.modality} content`)}if(spec.lossy&&!disclosure){throw new Error(`policy artifact "${artifact.title}" is lossy but carries no omniDisclosure`)}return{kind:"media",absolutePath,recognized,sha256:await hashFileSha256(absolutePath,signal),disclosure,lossy:spec.lossy===true,role}}__name(validateArtifact,"validateArtifact");function assertRequiredOutputsPresent(descriptor,validated,toolName){for(const spec of descriptor.outputs){if(!spec.required)continue;let produced;if(spec.kind==="media"){produced=validated.some(a=>a.kind==="media"&&spec.mimeTypes?.includes(a.recognized.detectedMimeType))}else if(spec.kind==="file"){produced=validated.some(a=>a.kind==="file"&&(spec.role===void 0||a.role===spec.role)&&spec.mimeTypes?.includes(a.mimeType))}else{continue}if(!produced){throw new Error(`tool ${toolName} did not produce its required ${spec.kind} ${spec.mimeTypes?.join("/")??spec.role??""} output`)}}}__name(assertRequiredOutputsPresent,"assertRequiredOutputsPresent");export{estimateRawResourceTokens,computePolicyFingerprint,OmniDegradationCache,DEFAULT_OMNI_MAX_UPLOAD_FILE_BYTES,OmniTransportGuardError,effectiveMaxUploadFileBytes,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveOmniStorageMaxTotalBytes,runOmniGcOnce,OmniPolicyExecutionError,runFixedPolicies,validateArtifact,assertRequiredOutputsPresent};
|
|
6
6
|
/**
|
|
7
7
|
* @license
|
|
8
8
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{DEFAULT_DARK_THEME_NAME,DEFAULT_LIGHT_THEME_NAME}from"./chunk-UWCF7JIF.js";import{customDeepMerge,getSettingsSchema}from"./chunk-
|
|
3
|
+
import{DEFAULT_DARK_THEME_NAME,DEFAULT_LIGHT_THEME_NAME}from"./chunk-UWCF7JIF.js";import{customDeepMerge,getSettingsSchema}from"./chunk-S7CWSAUQ.js";import{CONSOLIDATED_DISABLE_KEYS,V1_INDICATOR_KEYS,V1_TO_V2_MIGRATION_MAP,V1_TO_V2_PRESERVE_DISABLE_MAP,V2_CONTAINER_KEYS}from"./chunk-LMUSSYJH.js";import{t}from"./chunk-AUM57JI2.js";import{SUPPORTED_LANGUAGES,getLanguageNameFromLocale}from"./chunk-EZDXHUHB.js";import{SETTINGS_DIRECTORY_NAME,getHomeEnvFallbackVars,loadEnvironment,preResolveHomeEnvOverrides}from"./chunk-QJ6ZTZFC.js";import{ENV_CORRUPTED_PATH,ENV_WAS_RECOVERED,applyVerifyPrCoordinateEnv}from"./chunk-AJTR5LAF.js";import{parseExecutionSandboxSettings,readBareModeOperatorSettings,readOperatorSandboxSettings,require_strip_json_comments,selectOperatorCatalogRefresh,selectOperatorExecutionSandbox,stripUtf8Bom}from"./chunk-EKRCICRK.js";import{getGlobalQwenDirLite,getSystemDefaultsPath,getSystemSettingsPath,spawnedEnvironmentView}from"./chunk-ERGT5BD3.js";import{isWorkspaceTrusted,updateSettingsFilePreservingFormat}from"./chunk-EYECE2PH.js";import{isValidAdvisorMaxUses}from"./chunk-ZUWLTGSR.js";import{resolveEnvVarsInObject}from"./chunk-HW7ZRPZU.js";import{stripRuntimeSnapshotPrefix}from"./chunk-SINRWOVD.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{FatalConfigError,getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs3 from"node:fs";import*as path2 from"node:path";import{homedir}from"node:os";import process from"node:process";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);init_esbuild_shims();function hasOwnModelProviders(settingsObj){if(!settingsObj||typeof settingsObj!=="object"){return false}const obj=settingsObj;return Object.prototype.hasOwnProperty.call(obj,"modelProviders")}__name(hasOwnModelProviders,"hasOwnModelProviders");function getModelProvidersOwnerScope(settings){if(settings.isTrusted&&hasOwnModelProviders(settings.workspace.settings)){return"Workspace"}if(hasOwnModelProviders(settings.user.settings)){return"User"}return void 0}__name(getModelProvidersOwnerScope,"getModelProvidersOwnerScope");function getPersistScopeForModelSelection(settings){if(settings.isTrusted&&settings.workspace.settings.security?.auth?.selectedType==="qwen-subscription"){return"Workspace"}return getModelProvidersOwnerScope(settings)??"User"}__name(getPersistScopeForModelSelection,"getPersistScopeForModelSelection");function getWritableScopes(settings){return settings.isTrusted?["Workspace","User"]:["User"]}__name(getWritableScopes,"getWritableScopes");function getOwnKeyScope(settings,key){for(const scope of getWritableScopes(settings)){const obj=settings.forScope(scope).settings;if(Object.prototype.hasOwnProperty.call(obj,key))return scope}return void 0}__name(getOwnKeyScope,"getOwnKeyScope");init_esbuild_shims();init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var LLM_OUTPUT_LANGUAGE_RULE_FILENAME="output-language.md";var LLM_OUTPUT_LANGUAGE_MARKER_PREFIX="qwen-code:llm-output-language:";var OUTPUT_LANGUAGE_AUTO="auto";function isAutoLanguage(value){return!value||value.toLowerCase()===OUTPUT_LANGUAGE_AUTO}__name(isAutoLanguage,"isAutoLanguage");function normalizeOutputLanguage(language){const normalized=language.trim().replace(/_/g,"-").toLowerCase();const knownLanguageName=SUPPORTED_LANGUAGES.find(supportedLanguage=>supportedLanguage.fullName.toLowerCase()===normalized);if(knownLanguageName){return knownLanguageName.fullName}const knownLocaleCode=SUPPORTED_LANGUAGES.some(supportedLanguage=>{const code=supportedLanguage.code.toLowerCase();const id=supportedLanguage.id.toLowerCase();return normalized===code||normalized===id||normalized.startsWith(`${code}-`)||normalized.startsWith(`${id}-`)||normalized.startsWith(`${code}.`)||normalized.startsWith(`${id}.`)||normalized.startsWith(`${code}@`)||normalized.startsWith(`${id}@`)});if(!knownLocaleCode){return language}return getLanguageNameFromLocale(normalized)}__name(normalizeOutputLanguage,"normalizeOutputLanguage");function resolveOutputLanguage(value){if(isAutoLanguage(value)){throw new Error("resolveOutputLanguage does not accept auto; use resolveOutputLanguageOrPreserveAuto instead.")}return normalizeOutputLanguage(value)}__name(resolveOutputLanguage,"resolveOutputLanguage");function resolveOutputLanguageOrPreserveAuto(value){return isAutoLanguage(value)?OUTPUT_LANGUAGE_AUTO:resolveOutputLanguage(value)}__name(resolveOutputLanguageOrPreserveAuto,"resolveOutputLanguageOrPreserveAuto");function getOutputLanguageFilePath(){return path.join(Storage.getGlobalQwenDir(),LLM_OUTPUT_LANGUAGE_RULE_FILENAME)}__name(getOutputLanguageFilePath,"getOutputLanguageFilePath");function sanitizeForMarker(language){return language.replace(/[\r\n]/g," ").replace(/--!?>/g,"").replace(/--/g,"")}__name(sanitizeForMarker,"sanitizeForMarker");function generateOutputLanguageFileContent(language){const safeLanguage=sanitizeForMarker(language);if(isAutoLanguage(language)){return`# Output language preference: ${OUTPUT_LANGUAGE_AUTO}
|
|
4
4
|
<!-- ${LLM_OUTPUT_LANGUAGE_MARKER_PREFIX} ${OUTPUT_LANGUAGE_AUTO} -->
|
|
5
5
|
|
|
6
6
|
## Rule
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{HistoryReplayer,observeAcpToolResultProjection}from"./chunk-SOCXRMZM.js";import{JSON_STRING_DELIMITER_BYTES,jsonStringJsonByteLength,jsonStringPayloadByteLength,truncateJsonStringPayload}from"./chunk-WQUA4G2X.js";import{isA2uiToolMeta}from"./chunk-JDHMSERR.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{getResponseText,lastHistoryContentFromRecords,restorableAskUserQuestionCallIds}from"./chunk-PFKTTUGS.js";import{isShellResultDisplay,mapShellResultText}from"./chunk-T7CHK6C2.js";import{parseGoalSnapshotV2,parseGoalStateCause}from"./chunk-7Z2ZH5CW.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var MAX_REMEMBER_ERROR_DETAILS_CHARS=1e3;var MAX_REMEMBER_ERROR_CAUSE_DEPTH=50;var REMEMBER_ERROR_FORMAT_RE=new RegExp("[\\p{Cf}]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_SPACE_SEPARATOR_RE=/[\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/gu;var REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE=new RegExp("[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE=new RegExp("\\b(Bearer|QQBot)(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+(?=[A-Za-z0-9._~+/=-])","giu");var REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(Bearer|QQBot)(?:\\s|[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+((?:[A-Za-z0-9._~+/=-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9._~+/=-]+)","giu");var REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(?:sk-|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xox[b]-|xox[p]-)(?:[A-Za-z0-9_-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9_-]+","gu");var REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE=new RegExp("\\b(?:AKIA|ASIA)(?:[A-Z0-9]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Z0-9]+","gu");var REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("((?:api[_-]?key|token|secret|password|pwd)[_-]?[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","giu");var REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("([A-Z][A-Z0-9]{0,50}(?:_[A-Z0-9]{1,50}){0,10}_(?:KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","gu");var REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE=new RegExp("(\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/)([^/@\\s]*(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+[^/@\\s]*)@","giu");var REMEMBER_ERROR_CONTROL_RE=/[\x00-\x1f\x7f-\x9f]/g;var DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES=new Set(["managed_memory_unavailable"]);function createWorkspaceMemoryExtractionErrorLogger(logger){return(target,err)=>{logger.warn(`Failed to extract workspace memory error ${target}:`,{extractionError:err instanceof Error?err.message:String(err)})}}__name(createWorkspaceMemoryExtractionErrorLogger,"createWorkspaceMemoryExtractionErrorLogger");function reportRememberErrorExtractionFailure(onExtractionError,target,err){try{onExtractionError?.(target,err)}catch{}}__name(reportRememberErrorExtractionFailure,"reportRememberErrorExtractionFailure");function errorCodeFromRecord(record){if(typeof record["code"]==="string")return record["code"];const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;if(typeof dataRecord["errorKind"]==="string"){return dataRecord["errorKind"]}if(typeof dataRecord["code"]==="string")return dataRecord["code"]}return void 0}__name(errorCodeFromRecord,"errorCodeFromRecord");function rawRememberErrorCode(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);const record=err;const direct=errorCodeFromRecord(record);if(direct)return direct;const cause=record["cause"];if(cause!=null){return rawRememberErrorCode(cause,seen,depth+1)}return void 0}__name(rawRememberErrorCode,"rawRememberErrorCode");function extractRememberErrorCode(err,fallback="remember_failed"){return rawRememberErrorCode(err,new WeakSet,0)??fallback}__name(extractRememberErrorCode,"extractRememberErrorCode");function workspaceMemoryFailureCode(err,fallback="remember_failed",onExtractionError){try{return extractRememberErrorCode(err,fallback)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"code",extractionErr);return fallback}}__name(workspaceMemoryFailureCode,"workspaceMemoryFailureCode");function detailFromRecord(record,seen,depth){const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;const details=dataRecord["details"];if(typeof details==="string"&&details.length>0)return details;const message2=dataRecord["message"];if(typeof message2==="string"&&message2.length>0)return message2}const message=record["message"];if(typeof message==="string"&&message.length>0)return message;if(typeof data==="string"&&data.length>0)return data;const cause=record["cause"];if(cause!=null){return rawRememberErrorDetails(cause,seen,depth+1)}return void 0}__name(detailFromRecord,"detailFromRecord");function rawRememberErrorDetails(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(typeof err==="string"&&err.length>0)return err;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);return detailFromRecord(err,seen,depth)}__name(rawRememberErrorDetails,"rawRememberErrorDetails");function replaceControlChars(details){return details.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE," ")}__name(replaceControlChars,"replaceControlChars");function replaceStackControlChars(stack){return stack.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE,char=>char==="\n"||char==="\r"||char===" "?char:" ")}__name(replaceStackControlChars,"replaceStackControlChars");function collapseCredentialSeparators(text){return text.replace(REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE,(_match,scheme,userinfo)=>`${scheme}${userinfo.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}@`).replace(REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE,(_match,scheme,token)=>`${scheme} ${token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`)}__name(collapseCredentialSeparators,"collapseCredentialSeparators");function collapseCredentialSeparatorsByStackLine(stack){return stack.split(/(\r\n|\n|\r)/).map(part=>part==="\r\n"||part==="\n"||part==="\r"?part:collapseCredentialSeparators(part)).join("")}__name(collapseCredentialSeparatorsByStackLine,"collapseCredentialSeparatorsByStackLine");function isHighSurrogate(codeUnit){return codeUnit>=55296&&codeUnit<=56319}__name(isHighSurrogate,"isHighSurrogate");function isLowSurrogate(codeUnit){return codeUnit>=56320&&codeUnit<=57343}__name(isLowSurrogate,"isLowSurrogate");function truncateBeforeDanglingSurrogate(details,cutPoint){const beforeCut=details.charCodeAt(cutPoint-1);const atCut=details.charCodeAt(cutPoint);if(isHighSurrogate(beforeCut)&&isLowSurrogate(atCut)){return cutPoint-1}return cutPoint}__name(truncateBeforeDanglingSurrogate,"truncateBeforeDanglingSurrogate");function capRememberErrorText(redacted){if(redacted.length<=MAX_REMEMBER_ERROR_DETAILS_CHARS)return redacted;const truncationSuffix="... [truncated]";const cutPoint=truncateBeforeDanglingSurrogate(redacted,MAX_REMEMBER_ERROR_DETAILS_CHARS-truncationSuffix.length);return`${redacted.slice(0,cutPoint)}${truncationSuffix}`}__name(capRememberErrorText,"capRememberErrorText");function redactAndCapRememberErrorText(normalized){const redacted=redactLogCredentials(normalized).trim();if(!redacted)return void 0;return capRememberErrorText(redacted)}__name(redactAndCapRememberErrorText,"redactAndCapRememberErrorText");function sanitizeRememberErrorDetails(details){return redactAndCapRememberErrorText(replaceControlChars(collapseCredentialSeparators(details)))}__name(sanitizeRememberErrorDetails,"sanitizeRememberErrorDetails");function sanitizeRememberErrorStack(stack){return redactAndCapRememberErrorText(replaceStackControlChars(collapseCredentialSeparatorsByStackLine(stack)))}__name(sanitizeRememberErrorStack,"sanitizeRememberErrorStack");function extractRememberErrorDetails(err){const raw=rawRememberErrorDetails(err,new WeakSet,0);if(!raw)return void 0;return sanitizeRememberErrorDetails(raw)}__name(extractRememberErrorDetails,"extractRememberErrorDetails");function extractRememberErrorStack(err){if(!(err instanceof Error)||!err.stack)return void 0;return sanitizeRememberErrorStack(err.stack)}__name(extractRememberErrorStack,"extractRememberErrorStack");function shouldSuppressRememberErrorDetails(code){return DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES.has(code)}__name(shouldSuppressRememberErrorDetails,"shouldSuppressRememberErrorDetails");function workspaceMemoryFailureDiagnostics(err,onExtractionError){let details;let stack;try{details=extractRememberErrorDetails(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"details",extractionErr);details=void 0}try{stack=extractRememberErrorStack(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"stack",extractionErr);stack=void 0}return{...details?{details}:{},debugDetails:details??"<details unavailable>",...stack?{stack}:{}}}__name(workspaceMemoryFailureDiagnostics,"workspaceMemoryFailureDiagnostics");init_esbuild_shims();var MAX_REMEMBER_CONTENT_BYTES=64*1024;init_esbuild_shims();function formatWorkspaceMemoryForgetSummary(removedEntryCount){return removedEntryCount>0?`Forgot ${removedEntryCount} memory entr${removedEntryCount===1?"y":"ies"}.`:"No managed auto-memory entries matched."}__name(formatWorkspaceMemoryForgetSummary,"formatWorkspaceMemoryForgetSummary");function formatWorkspaceMemoryDreamSummary(touchedTopicCount){return touchedTopicCount>0?"Managed auto-memory dream completed.":"No managed auto-memory topics changed."}__name(formatWorkspaceMemoryDreamSummary,"formatWorkspaceMemoryDreamSummary");init_esbuild_shims();var VALID_SERVER_NAME=/^[A-Za-z0-9_-]+$/;var RESERVED_SERVER_NAMES=new Set(["__proto__","constructor","prototype"]);function isValidServerName(name){return typeof name==="string"&&name.length>0&&name.length<=256&&VALID_SERVER_NAME.test(name)&&!RESERVED_SERVER_NAMES.has(name)}__name(isValidServerName,"isValidServerName");init_esbuild_shims();var GENERATION_MAX_PROMPT_BYTES=32*1024;var GENERATION_TIMEOUT_MS=6e4;async function executeGeneration(config,requestId,prompt,signal,emit){const fastModel=config.getFastModel();const mainModel=config.getModel();const client=config.getBaseLlmClient();let modelSource=fastModel?"fast":"main";let resolved;if(fastModel){try{resolved=await client.resolveForModel(fastModel,{failClosed:true})}catch{modelSource="main"}}resolved??=await client.resolveForModel(mainModel,{failClosed:true});const{contentGenerator,model}=resolved;await emit({type:"started",model,modelSource});const stream=await contentGenerator.generateContentStream({model,contents:[{role:"user",parts:[{text:prompt}]}],config:{abortSignal:signal,tools:[],thinkingConfig:{thinkingBudget:0,includeThoughts:false},temperature:.2}},`generation:${requestId}`);let seq=0;let thinkingEmitted=false;let usage;for await(const chunk of stream){if(!thinkingEmitted&&chunk.candidates?.some(candidate=>candidate.content?.parts?.some(part=>part.thought===true))){thinkingEmitted=true;await emit({type:"thinking"})}const text=getResponseText(chunk)??"";if(text){await emit({type:"delta",seq:seq++,text})}if(chunk.usageMetadata)usage=chunk.usageMetadata}return{model,modelSource,...usage?.promptTokenCount!==void 0?{inputTokens:usage.promptTokenCount}:{},...usage?.candidatesTokenCount!==void 0?{outputTokens:usage.candidatesTokenCount}:{}}}__name(executeGeneration,"executeGeneration");init_esbuild_shims();import{Buffer as Buffer2}from"node:buffer";init_esbuild_shims();import{Buffer}from"node:buffer";import{isDeepStrictEqual}from"node:util";var ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for ACP transport ...]\n";var EMPTY_CONTENT_ARRAY_JSON_BYTES=Buffer.byteLength("[]","utf8");var EMPTY_TEXT_BLOCK_JSON_BYTES=Buffer.byteLength(JSON.stringify(createTextBlock("")),"utf8");var JSON_ARRAY_SEPARATOR_BYTES=1;var TRUNCATION_MARKER_PAYLOAD_BYTES=jsonStringJsonByteLength(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)-JSON_STRING_DELIMITER_BYTES;var MAX_CANONICAL_TEXT_BLOCKS=Math.floor((ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-EMPTY_CONTENT_ARRAY_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES)/(EMPTY_TEXT_BLOCK_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES));function createTextBlock(text){return{type:"content",content:{type:"text",text}}}__name(createTextBlock,"createTextBlock");function isObjectRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord,"isObjectRecord");function hasExactKeys(value,first,second){const keys=Object.keys(value);return keys.length===2&&Object.hasOwn(value,first)&&Object.hasOwn(value,second)}__name(hasExactKeys,"hasExactKeys");function canonicalTextBlocks(value){if(!Array.isArray(value))return void 0;for(const block of value){if(!isObjectRecord(block)||!hasExactKeys(block,"type","content")||block["type"]!=="content"||!isObjectRecord(block["content"])||!hasExactKeys(block["content"],"type","text")||block["content"]["type"]!=="text"||typeof block["content"]["text"]!=="string"){return void 0}}return value}__name(canonicalTextBlocks,"canonicalTextBlocks");function contentSkeletonBytes(blockCount){if(blockCount===0)return EMPTY_CONTENT_ARRAY_JSON_BYTES;return EMPTY_CONTENT_ARRAY_JSON_BYTES+blockCount*EMPTY_TEXT_BLOCK_JSON_BYTES+(blockCount-1)*JSON_ARRAY_SEPARATOR_BYTES}__name(contentSkeletonBytes,"contentSkeletonBytes");function fallbackContent(){return[createTextBlock(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)]}__name(fallbackContent,"fallbackContent");function jsonByteLength(value){return Buffer.byteLength(JSON.stringify(value),"utf8")}__name(jsonByteLength,"jsonByteLength");function allocatePayloadBudgets(payloadBytes,availableBytes){const base=payloadBytes.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));let remaining=availableBytes-base.reduce((sum,bytes)=>sum+bytes,0);if(remaining<0)return void 0;const capacities=payloadBytes.map((bytes,index)=>({index,capacity:bytes-base[index]}));const sorted=capacities.filter(({capacity})=>capacity>0).sort((left,right)=>left.capacity===right.capacity?left.index-right.index:left.capacity-right.capacity);let active=sorted.length;let position=0;let level=0;let remainder=0;while(position<sorted.length&&active>0&&remaining>0){const nextLevel=sorted[position].capacity;const cost=(nextLevel-level)*active;if(cost>remaining){level+=Math.floor(remaining/active);remainder=remaining%active;remaining=0;break}level=nextLevel;remaining-=cost;while(position<sorted.length&&sorted[position].capacity===nextLevel){position++;active--}}const allocations=base.map((bytes,index)=>bytes+Math.min(capacities[index].capacity,level));if(remainder>0){for(const{index,capacity}of capacities){if(remainder===0)break;if(capacity>level){allocations[index]++;remainder--}}}return allocations}__name(allocatePayloadBudgets,"allocatePayloadBudgets");function projectContent(original){if(original.length>MAX_CANONICAL_TEXT_BLOCKS)return fallbackContent();const skeletonBytes=contentSkeletonBytes(original.length);const availablePayloadBytes=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-skeletonBytes;let remainingPayloadBytes=availablePayloadBytes;let needsProjection=false;for(const block of original){const payloadBytes2=jsonStringPayloadByteLength(block.content.text,remainingPayloadBytes);if(payloadBytes2>remainingPayloadBytes){needsProjection=true;break}remainingPayloadBytes-=payloadBytes2}if(!needsProjection)return original;const baseScans=original.map(block=>jsonStringPayloadByteLength(block.content.text,TRUNCATION_MARKER_PAYLOAD_BYTES));const basePayloadBytes=baseScans.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));const baseTotal=basePayloadBytes.reduce((sum,bytes)=>sum+bytes,0);if(baseTotal>availablePayloadBytes)return fallbackContent();const payloadBytes=original.map((block,index)=>{if(baseScans[index]<=TRUNCATION_MARKER_PAYLOAD_BYTES){return baseScans[index]}const maximumAllocation=availablePayloadBytes-baseTotal+basePayloadBytes[index];const bytes=jsonStringPayloadByteLength(block.content.text,maximumAllocation);return bytes<=maximumAllocation?bytes:maximumAllocation+1});const allocations=allocatePayloadBudgets(payloadBytes,availablePayloadBytes);if(!allocations)return fallbackContent();const projected=original.map((block,index)=>{if(payloadBytes[index]<=allocations[index])return block;return createTextBlock(truncateJsonStringPayload(block.content.text,payloadBytes[index],allocations[index],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))});return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:fallbackContent()}__name(projectContent,"projectContent");function projectRawOutput(value){const payloadBudget=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-JSON_STRING_DELIMITER_BYTES;const payloadBytes=jsonStringPayloadByteLength(value,payloadBudget);if(payloadBytes<=payloadBudget)return value;const projected=truncateJsonStringPayload(value,payloadBytes,payloadBudget,ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER);return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER}__name(projectRawOutput,"projectRawOutput");function a2uiMeta(meta){if(!meta)return void 0;const toolName=typeof meta["toolName"]==="string"?meta["toolName"]:void 0;const serverId=typeof meta["serverId"]==="string"?meta["serverId"]:void 0;return toolName===void 0&&serverId===void 0?void 0:{...toolName===void 0?{}:{toolName},...serverId===void 0?{}:{serverId}}}__name(a2uiMeta,"a2uiMeta");function projectAcpToolResultUpdate(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return update;const meta=isObjectRecord(record["_meta"])?record["_meta"]:void 0;if(isA2uiToolMeta(a2uiMeta(meta)))return update;const content=canonicalTextBlocks(record["content"]);const rawOutput=record["rawOutput"];if(content?.length===1&&typeof rawOutput==="string"&&rawOutput===content[0].content.text){const projectedContent2=projectContent(content);if(projectedContent2===content)return update;const projectedText=projectedContent2[0].content.text;return{...record,content:projectedContent2,rawOutput:projectedText}}const projectedContent=content?projectContent(content):void 0;let projectedRawOutput=typeof rawOutput==="string"?projectRawOutput(rawOutput):void 0;if(isShellResultDisplay(rawOutput)){const structured=mapShellResultText(rawOutput,text=>text);projectedRawOutput=isDeepStrictEqual(structured,rawOutput)?rawOutput:structured;if(Buffer.byteLength(JSON.stringify(structured),"utf8")>ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET){const payloadBytes=[];const skeleton=mapShellResultText(structured,text=>{payloadBytes.push(jsonStringPayloadByteLength(text));return""});const budgets=allocatePayloadBudgets(payloadBytes,ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-Buffer.byteLength(JSON.stringify(skeleton),"utf8"));let index=0;projectedRawOutput=mapShellResultText(structured,text=>truncateJsonStringPayload(text,jsonStringPayloadByteLength(text),budgets[index++],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))}}const contentChanged=projectedContent!==void 0&&projectedContent!==content;const rawOutputChanged=projectedRawOutput!==void 0&&projectedRawOutput!==rawOutput;if(!contentChanged&&!rawOutputChanged)return update;return{...record,...contentChanged?{content:projectedContent}:{},...rawOutputChanged?{rawOutput:projectedRawOutput}:{}}}__name(projectAcpToolResultUpdate,"projectAcpToolResultUpdate");var HistoryReplayLimitError=class extends Error{constructor(sessionId,reason,observed,limit){super(`Transcript replay for session ${sessionId} exceeds the ${reason} limit (${observed}, max ${limit})`);this.sessionId=sessionId;this.reason=reason;this.observed=observed;this.limit=limit;this.name="HistoryReplayLimitError"}static{__name(this,"HistoryReplayLimitError")}};function createReplayCumulativeUsage(){return{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0}}__name(createReplayCumulativeUsage,"createReplayCumulativeUsage");function copyCumulativeUsage(target,source){target.promptTokens=source.promptTokens;target.cachedTokens=source.cachedTokens;target.candidateTokens=source.candidateTokens;target.apiTimeMs=source.apiTimeMs}__name(copyCumulativeUsage,"copyCumulativeUsage");function isObjectRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord2,"isObjectRecord");function isCumulativeUsage(value){if(!isObjectRecord2(value))return false;return typeof value["promptTokens"]==="number"&&Number.isFinite(value["promptTokens"])&&typeof value["cachedTokens"]==="number"&&Number.isFinite(value["cachedTokens"])&&typeof value["candidateTokens"]==="number"&&Number.isFinite(value["candidateTokens"])&&typeof value["apiTimeMs"]==="number"&&Number.isFinite(value["apiTimeMs"])}__name(isCumulativeUsage,"isCumulativeUsage");function isPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&(value["timestamp"]===void 0||typeof value["timestamp"]==="string")&&typeof value["recordId"]==="string"}__name(isPendingReplayToolCall,"isPendingReplayToolCall");function isCurrentPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&typeof value["sourceRecordId"]==="string"&&(value["sourceTimestamp"]===void 0||typeof value["sourceTimestamp"]==="string")}__name(isCurrentPendingReplayToolCall,"isCurrentPendingReplayToolCall");function parseTranscriptReplayState(replay,logger){if(!isObjectRecord2(replay)){return{pendingToolCalls:[],cumulativeUsage:createReplayCumulativeUsage()}}if("v"in replay&&replay["v"]!==1){throw new TypeError("Unsupported transcript replay state version.")}const rawPending=replay["pendingToolCalls"];const pendingToolCalls=Array.isArray(rawPending)?rawPending.flatMap(pending=>{if(isPendingReplayToolCall(pending))return[pending];if(isCurrentPendingReplayToolCall(pending)){return[{callId:pending.callId,toolName:pending.toolName,...pending.resolvedToolName?{resolvedToolName:pending.resolvedToolName}:{},recordId:pending.sourceRecordId,...pending.sourceTimestamp?{timestamp:pending.sourceTimestamp}:{},...pending.rawCallId?{rawCallId:pending.rawCallId}:{},...pending.timingMatched?{timingMatched:true}:{}}]}return[]}):[];if(logger&&Array.isArray(rawPending)&&pendingToolCalls.length!==rawPending.length){const dropped=rawPending.length-pendingToolCalls.length;logger.warn(`[transcript] replay state dropped ${dropped} of ${rawPending.length} malformed pending tool calls`)}const cumulativeUsage=isCumulativeUsage(replay["cumulativeUsage"])?{...replay["cumulativeUsage"]}:createReplayCumulativeUsage();const rawGoalState=replay["goalState"];const goalState=rawGoalState===void 0?void 0:parseGoalSnapshotV2(rawGoalState);if(logger&&rawGoalState!==void 0&&!goalState){logger.warn("[transcript] replay state dropped a malformed Goal state")}const rawGoalCause=replay["goalCause"];const goalCause=rawGoalCause===void 0?void 0:parseGoalStateCause(rawGoalCause);if(logger&&rawGoalCause!==void 0&&!goalCause){logger.warn("[transcript] replay state dropped a malformed Goal cause")}return{pendingToolCalls,cumulativeUsage,...goalState?{goalState}:{},...goalCause?{goalCause}:{}}}__name(parseTranscriptReplayState,"parseTranscriptReplayState");function blankReplayedMcpAppHtml(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return void 0;const rawOutput=record["rawOutput"];if(!isObjectRecord2(rawOutput)||rawOutput["type"]!=="mcp_app"||typeof rawOutput["html"]!=="string"||rawOutput["html"]===""){return void 0}const blanked={...record,rawOutput:{...rawOutput,html:"",fallbackText:rawOutput["fallbackText"]||"MCP App HTML omitted because the restored page exceeds its size limit."}};if(Buffer2.byteLength(JSON.stringify(blanked),"utf8")>=Buffer2.byteLength(JSON.stringify(record),"utf8")){return void 0}return blanked}__name(blankReplayedMcpAppHtml,"blankReplayedMcpAppHtml");function degradeReplayEnvelopeAppHtml(envelope,maxBytes){let pageBytes=Buffer2.byteLength(JSON.stringify(envelope),"utf8");for(let i=0;i<envelope.updates.length&&pageBytes>maxBytes;i++){const update=envelope.updates[i];const blanked=blankReplayedMcpAppHtml(update);if(blanked===void 0)continue;pageBytes+=Buffer2.byteLength(JSON.stringify(blanked),"utf8")-Buffer2.byteLength(JSON.stringify(update),"utf8");envelope.updates[i]=blanked}}__name(degradeReplayEnvelopeAppHtml,"degradeReplayEnvelopeAppHtml");function replayContext(sessionId,updates,cumulativeUsage,config,limits){let activeRecordId=null;let serializedUpdateBytes=2;return{sessionId,sendUpdate:__name(async update=>{const projectedUpdate=projectAcpToolResultUpdate(update);const updateWithRecordId=(()=>{if(activeRecordId===null)return projectedUpdate;const record=projectedUpdate;const meta=isObjectRecord2(record["_meta"])?record["_meta"]:{};return{...record,_meta:{...meta,"qwen.session.recordId":activeRecordId}}})();let deliveredUpdate=liftSessionUpdateTimestamp(updateWithRecordId);observeAcpToolResultProjection(update,projectedUpdate,sessionId,deliveredUpdate);if(limits){const updateCount=updates.length+1;if(updateCount>limits.maxUpdates){throw new HistoryReplayLimitError(sessionId,"updates",updateCount,limits.maxUpdates)}let updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(deliveredUpdate),"utf8");if(serializedUpdateBytes+updateBytes>limits.maxBytes){for(let i=0;i<updates.length&&serializedUpdateBytes+updateBytes>limits.maxBytes;i++){const blanked=blankReplayedMcpAppHtml(updates[i]);if(blanked===void 0)continue;serializedUpdateBytes-=Buffer2.byteLength(JSON.stringify(updates[i]),"utf8")-Buffer2.byteLength(JSON.stringify(blanked),"utf8");updates[i]=blanked}if(serializedUpdateBytes+updateBytes>limits.maxBytes){const blanked=blankReplayedMcpAppHtml(deliveredUpdate);if(blanked!==void 0){deliveredUpdate=blanked;updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(blanked),"utf8")}}}serializedUpdateBytes+=updateBytes;if(serializedUpdateBytes>limits.maxBytes){throw new HistoryReplayLimitError(sessionId,"bytes",serializedUpdateBytes,limits.maxBytes)}}updates.push(deliveredUpdate)},"sendUpdate"),setActiveRecordId:__name(recordId=>{activeRecordId=recordId},"setActiveRecordId"),cumulativeUsage,...config?{config}:{}}}__name(replayContext,"replayContext");async function collectHistoryReplayUpdates({sessionId,config,records,gaps,cumulativeUsage,logger,replayState,goalBootstrap,limits,suppressRestoreAskUserQuestion,finalizeDangling,branchPointsByAssistantUuid}){const updates=[];let replayError;try{const initial=parseTranscriptReplayState(replayState,logger);let skipFinalizeCallIds;if(suppressRestoreAskUserQuestion!==true&&config?.getRestoreAskUserQuestion?.()===true){const replayClient=config.getLlmClient?.();const lastHistoryContent=replayClient?.isInitialized?.()===true?replayClient.getChat?.()?.peekLastHistoryEntry?.()??lastHistoryContentFromRecords(records):lastHistoryContentFromRecords(records);skipFinalizeCallIds=restorableAskUserQuestionCallIds(lastHistoryContent)}await new HistoryReplayer(replayContext(sessionId,updates,cumulativeUsage,config,limits)).replay(records,gaps,{...initial.goalState?{initialGoalState:initial.goalState}:{},...initial.goalCause?{initialGoalCause:initial.goalCause}:{},...goalBootstrap?{goalBootstrap}:{},...skipFinalizeCallIds?{skipFinalizeCallIds}:{},...finalizeDangling===void 0?{}:{finalizeDangling}})}catch(error){if(error instanceof HistoryReplayLimitError)throw error;replayError=error instanceof Error?error.message:String(error);logger?.warn("[historyReplay] History replay failed for session %s (partial updates: %d):",sessionId,updates.length,error)}if(branchPointsByAssistantUuid){stampBranchPoints(updates,branchPointsByAssistantUuid)}return replayError===void 0?{updates}:{updates,replayError}}__name(collectHistoryReplayUpdates,"collectHistoryReplayUpdates");function liftSessionUpdateTimestamp(update){const record=update;const meta=record["_meta"];const timestamp=isObjectRecord2(meta)?meta["timestamp"]:void 0;return typeof timestamp==="number"||typeof timestamp==="string"?{...record,timestamp}:update}__name(liftSessionUpdateTimestamp,"liftSessionUpdateTimestamp");function readTranscriptSourceRecordIds(update){const value=update;const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;const sourceRecordIds=transcript?.["sourceRecordIds"];if(!Array.isArray(sourceRecordIds))return void 0;return sourceRecordIds.filter(id=>typeof id==="string")}__name(readTranscriptSourceRecordIds,"readTranscriptSourceRecordIds");function stampBranchPoints(updates,branchPoints){const lastChunkIndexByRecordId=new Map;updates.forEach((update,index)=>{if(update.sessionUpdate!=="agent_message_chunk")return;const text=update.content?.text;if(typeof text!=="string"||text.length===0)return;for(const recordId of readTranscriptSourceRecordIds(update)??[]){if(Object.hasOwn(branchPoints,recordId)){lastChunkIndexByRecordId.set(recordId,index)}}});const decoratedIndexes=new Set;for(const[recordId,index]of lastChunkIndexByRecordId){if(decoratedIndexes.has(index))continue;decoratedIndexes.add(index);const value=updates[index];const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;value["_meta"]={...meta,qwenTranscript:{...transcript,branchRecordId:branchPoints[recordId]}}}}__name(stampBranchPoints,"stampBranchPoints");async function replayTranscriptRecordPage({sessionId,page,config,encodeCursor,logger,finalizeDangling=true}){const state=parseTranscriptReplayState(page.replay,logger);const updates=[];const replayer=new HistoryReplayer(replayContext(sessionId,updates,state.cumulativeUsage,config));let replayState;let replayError;try{const replayPageState=await replayer.replayPage(page.records,{pendingToolCalls:page.direction==="backward"?[]:state.pendingToolCalls,finalizeDangling:finalizeDangling&&(page.direction==="backward"||!page.hasMore),gaps:page.gaps,includeTiming:true,...state.goalState?{goalState:state.goalState}:{},...state.goalCause?{goalCause:state.goalCause}:{}});replayState=replayPageState.replay}catch(error){logger?.warn("[historyReplay] Paged history replay failed for session %s (partial updates: %d):",sessionId,updates.length,error);replayState=replayer.getReplayState();replayError="Replay conversion failed for this page"}if(page.branchPointsByAssistantUuid){stampBranchPoints(updates,page.branchPointsByAssistantUuid)}const nextCursor=page.nextCursorState&&replayError===void 0?encodeCursor({...page.nextCursorState,...page.direction==="backward"?{}:{replay:replayState}}):void 0;return{updates,...nextCursor?{nextCursor}:{},hasMore:replayError===void 0&&page.hasMore,startTime:page.startTime,lastUpdated:page.lastUpdated,...replayError?{partial:true,replayError}:{}}}__name(replayTranscriptRecordPage,"replayTranscriptRecordPage");export{createWorkspaceMemoryExtractionErrorLogger,extractRememberErrorCode,workspaceMemoryFailureCode,shouldSuppressRememberErrorDetails,workspaceMemoryFailureDiagnostics,MAX_REMEMBER_CONTENT_BYTES,formatWorkspaceMemoryForgetSummary,formatWorkspaceMemoryDreamSummary,isValidServerName,GENERATION_MAX_PROMPT_BYTES,GENERATION_TIMEOUT_MS,executeGeneration,projectAcpToolResultUpdate,HistoryReplayLimitError,createReplayCumulativeUsage,copyCumulativeUsage,degradeReplayEnvelopeAppHtml,collectHistoryReplayUpdates,replayTranscriptRecordPage};
|
|
3
|
+
import{HistoryReplayer,observeAcpToolResultProjection}from"./chunk-OZL4ZMGQ.js";import{JSON_STRING_DELIMITER_BYTES,jsonStringJsonByteLength,jsonStringPayloadByteLength,truncateJsonStringPayload}from"./chunk-WQUA4G2X.js";import{isA2uiToolMeta}from"./chunk-LY2DRNTZ.js";import{redactLogCredentials}from"./chunk-CFTFKWPW.js";import{getResponseText,lastHistoryContentFromRecords,restorableAskUserQuestionCallIds}from"./chunk-ZUWLTGSR.js";import{isShellResultDisplay,mapShellResultText}from"./chunk-T7CHK6C2.js";import{parseGoalSnapshotV2,parseGoalStateCause}from"./chunk-7Z2ZH5CW.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var MAX_REMEMBER_ERROR_DETAILS_CHARS=1e3;var MAX_REMEMBER_ERROR_CAUSE_DEPTH=50;var REMEMBER_ERROR_FORMAT_RE=new RegExp("[\\p{Cf}]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_SPACE_SEPARATOR_RE=/[\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/gu;var REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE=new RegExp("[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector}","gu");var REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE=new RegExp("\\b(Bearer|QQBot)(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+(?=[A-Za-z0-9._~+/=-])","giu");var REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(Bearer|QQBot)(?:\\s|[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+((?:[A-Za-z0-9._~+/=-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9._~+/=-]+)","giu");var REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE=new RegExp("\\b(?:sk-|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xox[b]-|xox[p]-)(?:[A-Za-z0-9_-]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Za-z0-9_-]+","gu");var REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE=new RegExp("\\b(?:AKIA|ASIA)(?:[A-Z0-9]+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*[A-Z0-9]+","gu");var REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("((?:api[_-]?key|token|secret|password|pwd)[_-]?[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","giu");var REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE=new RegExp("([A-Z][A-Z0-9]{0,50}(?:_[A-Z0-9]{1,50}){0,10}_(?:KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]\\s*)((?:\\S+(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+)*\\S+)","gu");var REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE=new RegExp("(\\b[a-z][a-z0-9+.-]{0,31}:\\/\\/)([^/@\\s]*(?:[\\x00-\\x1f\\x7f-\\x9f\\p{Cf}\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]|\\p{Variation_Selector})+[^/@\\s]*)@","giu");var REMEMBER_ERROR_CONTROL_RE=/[\x00-\x1f\x7f-\x9f]/g;var DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES=new Set(["managed_memory_unavailable"]);function createWorkspaceMemoryExtractionErrorLogger(logger){return(target,err)=>{logger.warn(`Failed to extract workspace memory error ${target}:`,{extractionError:err instanceof Error?err.message:String(err)})}}__name(createWorkspaceMemoryExtractionErrorLogger,"createWorkspaceMemoryExtractionErrorLogger");function reportRememberErrorExtractionFailure(onExtractionError,target,err){try{onExtractionError?.(target,err)}catch{}}__name(reportRememberErrorExtractionFailure,"reportRememberErrorExtractionFailure");function errorCodeFromRecord(record){if(typeof record["code"]==="string")return record["code"];const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;if(typeof dataRecord["errorKind"]==="string"){return dataRecord["errorKind"]}if(typeof dataRecord["code"]==="string")return dataRecord["code"]}return void 0}__name(errorCodeFromRecord,"errorCodeFromRecord");function rawRememberErrorCode(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);const record=err;const direct=errorCodeFromRecord(record);if(direct)return direct;const cause=record["cause"];if(cause!=null){return rawRememberErrorCode(cause,seen,depth+1)}return void 0}__name(rawRememberErrorCode,"rawRememberErrorCode");function extractRememberErrorCode(err,fallback="remember_failed"){return rawRememberErrorCode(err,new WeakSet,0)??fallback}__name(extractRememberErrorCode,"extractRememberErrorCode");function workspaceMemoryFailureCode(err,fallback="remember_failed",onExtractionError){try{return extractRememberErrorCode(err,fallback)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"code",extractionErr);return fallback}}__name(workspaceMemoryFailureCode,"workspaceMemoryFailureCode");function detailFromRecord(record,seen,depth){const data=record["data"];if(data&&typeof data==="object"){const dataRecord=data;const details=dataRecord["details"];if(typeof details==="string"&&details.length>0)return details;const message2=dataRecord["message"];if(typeof message2==="string"&&message2.length>0)return message2}const message=record["message"];if(typeof message==="string"&&message.length>0)return message;if(typeof data==="string"&&data.length>0)return data;const cause=record["cause"];if(cause!=null){return rawRememberErrorDetails(cause,seen,depth+1)}return void 0}__name(detailFromRecord,"detailFromRecord");function rawRememberErrorDetails(err,seen,depth){if(depth>MAX_REMEMBER_ERROR_CAUSE_DEPTH)return void 0;if(typeof err==="string"&&err.length>0)return err;if(!err||typeof err!=="object")return void 0;if(seen.has(err))return void 0;seen.add(err);return detailFromRecord(err,seen,depth)}__name(rawRememberErrorDetails,"rawRememberErrorDetails");function replaceControlChars(details){return details.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE," ")}__name(replaceControlChars,"replaceControlChars");function replaceStackControlChars(stack){return stack.replace(REMEMBER_ERROR_AUTH_SCHEME_INVISIBLE_RE,"$1 ").replace(REMEMBER_ERROR_FORMAT_RE,"").replace(REMEMBER_ERROR_SPACE_SEPARATOR_RE," ").replace(REMEMBER_ERROR_CONTROL_RE,char=>char==="\n"||char==="\r"||char===" "?char:" ")}__name(replaceStackControlChars,"replaceStackControlChars");function collapseCredentialSeparators(text){return text.replace(REMEMBER_ERROR_URL_CREDENTIALS_WITH_SEPARATORS_RE,(_match,scheme,userinfo)=>`${scheme}${userinfo.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}@`).replace(REMEMBER_ERROR_AUTH_TOKEN_WITH_SEPARATORS_RE,(_match,scheme,token)=>`${scheme} ${token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_BARE_TOKEN_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_AWS_KEY_WITH_SEPARATORS_RE,token=>token.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")).replace(REMEMBER_ERROR_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`).replace(REMEMBER_ERROR_ENV_SECRET_ASSIGNMENT_WITH_SEPARATORS_RE,(_match,prefix,value)=>`${prefix}${value.replace(REMEMBER_ERROR_CREDENTIAL_SEPARATOR_RE,"")}`)}__name(collapseCredentialSeparators,"collapseCredentialSeparators");function collapseCredentialSeparatorsByStackLine(stack){return stack.split(/(\r\n|\n|\r)/).map(part=>part==="\r\n"||part==="\n"||part==="\r"?part:collapseCredentialSeparators(part)).join("")}__name(collapseCredentialSeparatorsByStackLine,"collapseCredentialSeparatorsByStackLine");function isHighSurrogate(codeUnit){return codeUnit>=55296&&codeUnit<=56319}__name(isHighSurrogate,"isHighSurrogate");function isLowSurrogate(codeUnit){return codeUnit>=56320&&codeUnit<=57343}__name(isLowSurrogate,"isLowSurrogate");function truncateBeforeDanglingSurrogate(details,cutPoint){const beforeCut=details.charCodeAt(cutPoint-1);const atCut=details.charCodeAt(cutPoint);if(isHighSurrogate(beforeCut)&&isLowSurrogate(atCut)){return cutPoint-1}return cutPoint}__name(truncateBeforeDanglingSurrogate,"truncateBeforeDanglingSurrogate");function capRememberErrorText(redacted){if(redacted.length<=MAX_REMEMBER_ERROR_DETAILS_CHARS)return redacted;const truncationSuffix="... [truncated]";const cutPoint=truncateBeforeDanglingSurrogate(redacted,MAX_REMEMBER_ERROR_DETAILS_CHARS-truncationSuffix.length);return`${redacted.slice(0,cutPoint)}${truncationSuffix}`}__name(capRememberErrorText,"capRememberErrorText");function redactAndCapRememberErrorText(normalized){const redacted=redactLogCredentials(normalized).trim();if(!redacted)return void 0;return capRememberErrorText(redacted)}__name(redactAndCapRememberErrorText,"redactAndCapRememberErrorText");function sanitizeRememberErrorDetails(details){return redactAndCapRememberErrorText(replaceControlChars(collapseCredentialSeparators(details)))}__name(sanitizeRememberErrorDetails,"sanitizeRememberErrorDetails");function sanitizeRememberErrorStack(stack){return redactAndCapRememberErrorText(replaceStackControlChars(collapseCredentialSeparatorsByStackLine(stack)))}__name(sanitizeRememberErrorStack,"sanitizeRememberErrorStack");function extractRememberErrorDetails(err){const raw=rawRememberErrorDetails(err,new WeakSet,0);if(!raw)return void 0;return sanitizeRememberErrorDetails(raw)}__name(extractRememberErrorDetails,"extractRememberErrorDetails");function extractRememberErrorStack(err){if(!(err instanceof Error)||!err.stack)return void 0;return sanitizeRememberErrorStack(err.stack)}__name(extractRememberErrorStack,"extractRememberErrorStack");function shouldSuppressRememberErrorDetails(code){return DETAIL_SUPPRESSED_REMEMBER_ERROR_CODES.has(code)}__name(shouldSuppressRememberErrorDetails,"shouldSuppressRememberErrorDetails");function workspaceMemoryFailureDiagnostics(err,onExtractionError){let details;let stack;try{details=extractRememberErrorDetails(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"details",extractionErr);details=void 0}try{stack=extractRememberErrorStack(err)}catch(extractionErr){reportRememberErrorExtractionFailure(onExtractionError,"stack",extractionErr);stack=void 0}return{...details?{details}:{},debugDetails:details??"<details unavailable>",...stack?{stack}:{}}}__name(workspaceMemoryFailureDiagnostics,"workspaceMemoryFailureDiagnostics");init_esbuild_shims();var MAX_REMEMBER_CONTENT_BYTES=64*1024;init_esbuild_shims();function formatWorkspaceMemoryForgetSummary(removedEntryCount){return removedEntryCount>0?`Forgot ${removedEntryCount} memory entr${removedEntryCount===1?"y":"ies"}.`:"No managed auto-memory entries matched."}__name(formatWorkspaceMemoryForgetSummary,"formatWorkspaceMemoryForgetSummary");function formatWorkspaceMemoryDreamSummary(touchedTopicCount){return touchedTopicCount>0?"Managed auto-memory dream completed.":"No managed auto-memory topics changed."}__name(formatWorkspaceMemoryDreamSummary,"formatWorkspaceMemoryDreamSummary");init_esbuild_shims();var VALID_SERVER_NAME=/^[A-Za-z0-9_-]+$/;var RESERVED_SERVER_NAMES=new Set(["__proto__","constructor","prototype"]);function isValidServerName(name){return typeof name==="string"&&name.length>0&&name.length<=256&&VALID_SERVER_NAME.test(name)&&!RESERVED_SERVER_NAMES.has(name)}__name(isValidServerName,"isValidServerName");init_esbuild_shims();var GENERATION_MAX_PROMPT_BYTES=32*1024;var GENERATION_TIMEOUT_MS=6e4;async function executeGeneration(config,requestId,prompt,signal,emit){const fastModel=config.getFastModel();const mainModel=config.getModel();const client=config.getBaseLlmClient();let modelSource=fastModel?"fast":"main";let resolved;if(fastModel){try{resolved=await client.resolveForModel(fastModel,{failClosed:true})}catch{modelSource="main"}}resolved??=await client.resolveForModel(mainModel,{failClosed:true});const{contentGenerator,model}=resolved;await emit({type:"started",model,modelSource});const stream=await contentGenerator.generateContentStream({model,contents:[{role:"user",parts:[{text:prompt}]}],config:{abortSignal:signal,tools:[],thinkingConfig:{thinkingBudget:0,includeThoughts:false},temperature:.2}},`generation:${requestId}`);let seq=0;let thinkingEmitted=false;let usage;for await(const chunk of stream){if(!thinkingEmitted&&chunk.candidates?.some(candidate=>candidate.content?.parts?.some(part=>part.thought===true))){thinkingEmitted=true;await emit({type:"thinking"})}const text=getResponseText(chunk)??"";if(text){await emit({type:"delta",seq:seq++,text})}if(chunk.usageMetadata)usage=chunk.usageMetadata}return{model,modelSource,...usage?.promptTokenCount!==void 0?{inputTokens:usage.promptTokenCount}:{},...usage?.candidatesTokenCount!==void 0?{outputTokens:usage.candidatesTokenCount}:{}}}__name(executeGeneration,"executeGeneration");init_esbuild_shims();import{Buffer as Buffer2}from"node:buffer";init_esbuild_shims();import{Buffer}from"node:buffer";import{isDeepStrictEqual}from"node:util";var ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for ACP transport ...]\n";var EMPTY_CONTENT_ARRAY_JSON_BYTES=Buffer.byteLength("[]","utf8");var EMPTY_TEXT_BLOCK_JSON_BYTES=Buffer.byteLength(JSON.stringify(createTextBlock("")),"utf8");var JSON_ARRAY_SEPARATOR_BYTES=1;var TRUNCATION_MARKER_PAYLOAD_BYTES=jsonStringJsonByteLength(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)-JSON_STRING_DELIMITER_BYTES;var MAX_CANONICAL_TEXT_BLOCKS=Math.floor((ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-EMPTY_CONTENT_ARRAY_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES)/(EMPTY_TEXT_BLOCK_JSON_BYTES+JSON_ARRAY_SEPARATOR_BYTES));function createTextBlock(text){return{type:"content",content:{type:"text",text}}}__name(createTextBlock,"createTextBlock");function isObjectRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord,"isObjectRecord");function hasExactKeys(value,first,second){const keys=Object.keys(value);return keys.length===2&&Object.hasOwn(value,first)&&Object.hasOwn(value,second)}__name(hasExactKeys,"hasExactKeys");function canonicalTextBlocks(value){if(!Array.isArray(value))return void 0;for(const block of value){if(!isObjectRecord(block)||!hasExactKeys(block,"type","content")||block["type"]!=="content"||!isObjectRecord(block["content"])||!hasExactKeys(block["content"],"type","text")||block["content"]["type"]!=="text"||typeof block["content"]["text"]!=="string"){return void 0}}return value}__name(canonicalTextBlocks,"canonicalTextBlocks");function contentSkeletonBytes(blockCount){if(blockCount===0)return EMPTY_CONTENT_ARRAY_JSON_BYTES;return EMPTY_CONTENT_ARRAY_JSON_BYTES+blockCount*EMPTY_TEXT_BLOCK_JSON_BYTES+(blockCount-1)*JSON_ARRAY_SEPARATOR_BYTES}__name(contentSkeletonBytes,"contentSkeletonBytes");function fallbackContent(){return[createTextBlock(ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER)]}__name(fallbackContent,"fallbackContent");function jsonByteLength(value){return Buffer.byteLength(JSON.stringify(value),"utf8")}__name(jsonByteLength,"jsonByteLength");function allocatePayloadBudgets(payloadBytes,availableBytes){const base=payloadBytes.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));let remaining=availableBytes-base.reduce((sum,bytes)=>sum+bytes,0);if(remaining<0)return void 0;const capacities=payloadBytes.map((bytes,index)=>({index,capacity:bytes-base[index]}));const sorted=capacities.filter(({capacity})=>capacity>0).sort((left,right)=>left.capacity===right.capacity?left.index-right.index:left.capacity-right.capacity);let active=sorted.length;let position=0;let level=0;let remainder=0;while(position<sorted.length&&active>0&&remaining>0){const nextLevel=sorted[position].capacity;const cost=(nextLevel-level)*active;if(cost>remaining){level+=Math.floor(remaining/active);remainder=remaining%active;remaining=0;break}level=nextLevel;remaining-=cost;while(position<sorted.length&&sorted[position].capacity===nextLevel){position++;active--}}const allocations=base.map((bytes,index)=>bytes+Math.min(capacities[index].capacity,level));if(remainder>0){for(const{index,capacity}of capacities){if(remainder===0)break;if(capacity>level){allocations[index]++;remainder--}}}return allocations}__name(allocatePayloadBudgets,"allocatePayloadBudgets");function projectContent(original){if(original.length>MAX_CANONICAL_TEXT_BLOCKS)return fallbackContent();const skeletonBytes=contentSkeletonBytes(original.length);const availablePayloadBytes=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-skeletonBytes;let remainingPayloadBytes=availablePayloadBytes;let needsProjection=false;for(const block of original){const payloadBytes2=jsonStringPayloadByteLength(block.content.text,remainingPayloadBytes);if(payloadBytes2>remainingPayloadBytes){needsProjection=true;break}remainingPayloadBytes-=payloadBytes2}if(!needsProjection)return original;const baseScans=original.map(block=>jsonStringPayloadByteLength(block.content.text,TRUNCATION_MARKER_PAYLOAD_BYTES));const basePayloadBytes=baseScans.map(bytes=>Math.min(bytes,TRUNCATION_MARKER_PAYLOAD_BYTES));const baseTotal=basePayloadBytes.reduce((sum,bytes)=>sum+bytes,0);if(baseTotal>availablePayloadBytes)return fallbackContent();const payloadBytes=original.map((block,index)=>{if(baseScans[index]<=TRUNCATION_MARKER_PAYLOAD_BYTES){return baseScans[index]}const maximumAllocation=availablePayloadBytes-baseTotal+basePayloadBytes[index];const bytes=jsonStringPayloadByteLength(block.content.text,maximumAllocation);return bytes<=maximumAllocation?bytes:maximumAllocation+1});const allocations=allocatePayloadBudgets(payloadBytes,availablePayloadBytes);if(!allocations)return fallbackContent();const projected=original.map((block,index)=>{if(payloadBytes[index]<=allocations[index])return block;return createTextBlock(truncateJsonStringPayload(block.content.text,payloadBytes[index],allocations[index],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))});return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:fallbackContent()}__name(projectContent,"projectContent");function projectRawOutput(value){const payloadBudget=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-JSON_STRING_DELIMITER_BYTES;const payloadBytes=jsonStringPayloadByteLength(value,payloadBudget);if(payloadBytes<=payloadBudget)return value;const projected=truncateJsonStringPayload(value,payloadBytes,payloadBudget,ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER);return jsonByteLength(projected)<=ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET?projected:ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER}__name(projectRawOutput,"projectRawOutput");function a2uiMeta(meta){if(!meta)return void 0;const toolName=typeof meta["toolName"]==="string"?meta["toolName"]:void 0;const serverId=typeof meta["serverId"]==="string"?meta["serverId"]:void 0;return toolName===void 0&&serverId===void 0?void 0:{...toolName===void 0?{}:{toolName},...serverId===void 0?{}:{serverId}}}__name(a2uiMeta,"a2uiMeta");function projectAcpToolResultUpdate(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return update;const meta=isObjectRecord(record["_meta"])?record["_meta"]:void 0;if(isA2uiToolMeta(a2uiMeta(meta)))return update;const content=canonicalTextBlocks(record["content"]);const rawOutput=record["rawOutput"];if(content?.length===1&&typeof rawOutput==="string"&&rawOutput===content[0].content.text){const projectedContent2=projectContent(content);if(projectedContent2===content)return update;const projectedText=projectedContent2[0].content.text;return{...record,content:projectedContent2,rawOutput:projectedText}}const projectedContent=content?projectContent(content):void 0;let projectedRawOutput=typeof rawOutput==="string"?projectRawOutput(rawOutput):void 0;if(isShellResultDisplay(rawOutput)){const structured=mapShellResultText(rawOutput,text=>text);projectedRawOutput=isDeepStrictEqual(structured,rawOutput)?rawOutput:structured;if(Buffer.byteLength(JSON.stringify(structured),"utf8")>ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET){const payloadBytes=[];const skeleton=mapShellResultText(structured,text=>{payloadBytes.push(jsonStringPayloadByteLength(text));return""});const budgets=allocatePayloadBudgets(payloadBytes,ACP_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET-Buffer.byteLength(JSON.stringify(skeleton),"utf8"));let index=0;projectedRawOutput=mapShellResultText(structured,text=>truncateJsonStringPayload(text,jsonStringPayloadByteLength(text),budgets[index++],ACP_TOOL_RESULT_TEXT_TRUNCATION_MARKER))}}const contentChanged=projectedContent!==void 0&&projectedContent!==content;const rawOutputChanged=projectedRawOutput!==void 0&&projectedRawOutput!==rawOutput;if(!contentChanged&&!rawOutputChanged)return update;return{...record,...contentChanged?{content:projectedContent}:{},...rawOutputChanged?{rawOutput:projectedRawOutput}:{}}}__name(projectAcpToolResultUpdate,"projectAcpToolResultUpdate");var HistoryReplayLimitError=class extends Error{constructor(sessionId,reason,observed,limit){super(`Transcript replay for session ${sessionId} exceeds the ${reason} limit (${observed}, max ${limit})`);this.sessionId=sessionId;this.reason=reason;this.observed=observed;this.limit=limit;this.name="HistoryReplayLimitError"}static{__name(this,"HistoryReplayLimitError")}};function createReplayCumulativeUsage(){return{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0}}__name(createReplayCumulativeUsage,"createReplayCumulativeUsage");function copyCumulativeUsage(target,source){target.promptTokens=source.promptTokens;target.cachedTokens=source.cachedTokens;target.candidateTokens=source.candidateTokens;target.apiTimeMs=source.apiTimeMs}__name(copyCumulativeUsage,"copyCumulativeUsage");function isObjectRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isObjectRecord2,"isObjectRecord");function isCumulativeUsage(value){if(!isObjectRecord2(value))return false;return typeof value["promptTokens"]==="number"&&Number.isFinite(value["promptTokens"])&&typeof value["cachedTokens"]==="number"&&Number.isFinite(value["cachedTokens"])&&typeof value["candidateTokens"]==="number"&&Number.isFinite(value["candidateTokens"])&&typeof value["apiTimeMs"]==="number"&&Number.isFinite(value["apiTimeMs"])}__name(isCumulativeUsage,"isCumulativeUsage");function isPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&(value["timestamp"]===void 0||typeof value["timestamp"]==="string")&&typeof value["recordId"]==="string"}__name(isPendingReplayToolCall,"isPendingReplayToolCall");function isCurrentPendingReplayToolCall(value){if(!isObjectRecord2(value))return false;return typeof value["callId"]==="string"&&typeof value["toolName"]==="string"&&typeof value["sourceRecordId"]==="string"&&(value["sourceTimestamp"]===void 0||typeof value["sourceTimestamp"]==="string")}__name(isCurrentPendingReplayToolCall,"isCurrentPendingReplayToolCall");function parseTranscriptReplayState(replay,logger){if(!isObjectRecord2(replay)){return{pendingToolCalls:[],cumulativeUsage:createReplayCumulativeUsage()}}if("v"in replay&&replay["v"]!==1){throw new TypeError("Unsupported transcript replay state version.")}const rawPending=replay["pendingToolCalls"];const pendingToolCalls=Array.isArray(rawPending)?rawPending.flatMap(pending=>{if(isPendingReplayToolCall(pending))return[pending];if(isCurrentPendingReplayToolCall(pending)){return[{callId:pending.callId,toolName:pending.toolName,...pending.resolvedToolName?{resolvedToolName:pending.resolvedToolName}:{},recordId:pending.sourceRecordId,...pending.sourceTimestamp?{timestamp:pending.sourceTimestamp}:{},...pending.rawCallId?{rawCallId:pending.rawCallId}:{},...pending.timingMatched?{timingMatched:true}:{}}]}return[]}):[];if(logger&&Array.isArray(rawPending)&&pendingToolCalls.length!==rawPending.length){const dropped=rawPending.length-pendingToolCalls.length;logger.warn(`[transcript] replay state dropped ${dropped} of ${rawPending.length} malformed pending tool calls`)}const cumulativeUsage=isCumulativeUsage(replay["cumulativeUsage"])?{...replay["cumulativeUsage"]}:createReplayCumulativeUsage();const rawGoalState=replay["goalState"];const goalState=rawGoalState===void 0?void 0:parseGoalSnapshotV2(rawGoalState);if(logger&&rawGoalState!==void 0&&!goalState){logger.warn("[transcript] replay state dropped a malformed Goal state")}const rawGoalCause=replay["goalCause"];const goalCause=rawGoalCause===void 0?void 0:parseGoalStateCause(rawGoalCause);if(logger&&rawGoalCause!==void 0&&!goalCause){logger.warn("[transcript] replay state dropped a malformed Goal cause")}return{pendingToolCalls,cumulativeUsage,...goalState?{goalState}:{},...goalCause?{goalCause}:{}}}__name(parseTranscriptReplayState,"parseTranscriptReplayState");function blankReplayedMcpAppHtml(update){const record=update;if(record["sessionUpdate"]!=="tool_call_update")return void 0;const rawOutput=record["rawOutput"];if(!isObjectRecord2(rawOutput)||rawOutput["type"]!=="mcp_app"||typeof rawOutput["html"]!=="string"||rawOutput["html"]===""){return void 0}const blanked={...record,rawOutput:{...rawOutput,html:"",fallbackText:rawOutput["fallbackText"]||"MCP App HTML omitted because the restored page exceeds its size limit."}};if(Buffer2.byteLength(JSON.stringify(blanked),"utf8")>=Buffer2.byteLength(JSON.stringify(record),"utf8")){return void 0}return blanked}__name(blankReplayedMcpAppHtml,"blankReplayedMcpAppHtml");function degradeReplayEnvelopeAppHtml(envelope,maxBytes){let pageBytes=Buffer2.byteLength(JSON.stringify(envelope),"utf8");for(let i=0;i<envelope.updates.length&&pageBytes>maxBytes;i++){const update=envelope.updates[i];const blanked=blankReplayedMcpAppHtml(update);if(blanked===void 0)continue;pageBytes+=Buffer2.byteLength(JSON.stringify(blanked),"utf8")-Buffer2.byteLength(JSON.stringify(update),"utf8");envelope.updates[i]=blanked}}__name(degradeReplayEnvelopeAppHtml,"degradeReplayEnvelopeAppHtml");function replayContext(sessionId,updates,cumulativeUsage,config,limits){let activeRecordId=null;let serializedUpdateBytes=2;return{sessionId,sendUpdate:__name(async update=>{const projectedUpdate=projectAcpToolResultUpdate(update);const updateWithRecordId=(()=>{if(activeRecordId===null)return projectedUpdate;const record=projectedUpdate;const meta=isObjectRecord2(record["_meta"])?record["_meta"]:{};return{...record,_meta:{...meta,"qwen.session.recordId":activeRecordId}}})();let deliveredUpdate=liftSessionUpdateTimestamp(updateWithRecordId);observeAcpToolResultProjection(update,projectedUpdate,sessionId,deliveredUpdate);if(limits){const updateCount=updates.length+1;if(updateCount>limits.maxUpdates){throw new HistoryReplayLimitError(sessionId,"updates",updateCount,limits.maxUpdates)}let updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(deliveredUpdate),"utf8");if(serializedUpdateBytes+updateBytes>limits.maxBytes){for(let i=0;i<updates.length&&serializedUpdateBytes+updateBytes>limits.maxBytes;i++){const blanked=blankReplayedMcpAppHtml(updates[i]);if(blanked===void 0)continue;serializedUpdateBytes-=Buffer2.byteLength(JSON.stringify(updates[i]),"utf8")-Buffer2.byteLength(JSON.stringify(blanked),"utf8");updates[i]=blanked}if(serializedUpdateBytes+updateBytes>limits.maxBytes){const blanked=blankReplayedMcpAppHtml(deliveredUpdate);if(blanked!==void 0){deliveredUpdate=blanked;updateBytes=(updates.length===0?0:1)+Buffer2.byteLength(JSON.stringify(blanked),"utf8")}}}serializedUpdateBytes+=updateBytes;if(serializedUpdateBytes>limits.maxBytes){throw new HistoryReplayLimitError(sessionId,"bytes",serializedUpdateBytes,limits.maxBytes)}}updates.push(deliveredUpdate)},"sendUpdate"),setActiveRecordId:__name(recordId=>{activeRecordId=recordId},"setActiveRecordId"),cumulativeUsage,...config?{config}:{}}}__name(replayContext,"replayContext");async function collectHistoryReplayUpdates({sessionId,config,records,gaps,cumulativeUsage,logger,replayState,goalBootstrap,limits,suppressRestoreAskUserQuestion,finalizeDangling,branchPointsByAssistantUuid}){const updates=[];let replayError;try{const initial=parseTranscriptReplayState(replayState,logger);let skipFinalizeCallIds;if(suppressRestoreAskUserQuestion!==true&&config?.getRestoreAskUserQuestion?.()===true){const replayClient=config.getLlmClient?.();const lastHistoryContent=replayClient?.isInitialized?.()===true?replayClient.getChat?.()?.peekLastHistoryEntry?.()??lastHistoryContentFromRecords(records):lastHistoryContentFromRecords(records);skipFinalizeCallIds=restorableAskUserQuestionCallIds(lastHistoryContent)}await new HistoryReplayer(replayContext(sessionId,updates,cumulativeUsage,config,limits)).replay(records,gaps,{...initial.goalState?{initialGoalState:initial.goalState}:{},...initial.goalCause?{initialGoalCause:initial.goalCause}:{},...goalBootstrap?{goalBootstrap}:{},...skipFinalizeCallIds?{skipFinalizeCallIds}:{},...finalizeDangling===void 0?{}:{finalizeDangling}})}catch(error){if(error instanceof HistoryReplayLimitError)throw error;replayError=error instanceof Error?error.message:String(error);logger?.warn("[historyReplay] History replay failed for session %s (partial updates: %d):",sessionId,updates.length,error)}if(branchPointsByAssistantUuid){stampBranchPoints(updates,branchPointsByAssistantUuid)}return replayError===void 0?{updates}:{updates,replayError}}__name(collectHistoryReplayUpdates,"collectHistoryReplayUpdates");function liftSessionUpdateTimestamp(update){const record=update;const meta=record["_meta"];const timestamp=isObjectRecord2(meta)?meta["timestamp"]:void 0;return typeof timestamp==="number"||typeof timestamp==="string"?{...record,timestamp}:update}__name(liftSessionUpdateTimestamp,"liftSessionUpdateTimestamp");function readTranscriptSourceRecordIds(update){const value=update;const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;const sourceRecordIds=transcript?.["sourceRecordIds"];if(!Array.isArray(sourceRecordIds))return void 0;return sourceRecordIds.filter(id=>typeof id==="string")}__name(readTranscriptSourceRecordIds,"readTranscriptSourceRecordIds");function stampBranchPoints(updates,branchPoints){const lastChunkIndexByRecordId=new Map;updates.forEach((update,index)=>{if(update.sessionUpdate!=="agent_message_chunk")return;const text=update.content?.text;if(typeof text!=="string"||text.length===0)return;for(const recordId of readTranscriptSourceRecordIds(update)??[]){if(Object.hasOwn(branchPoints,recordId)){lastChunkIndexByRecordId.set(recordId,index)}}});const decoratedIndexes=new Set;for(const[recordId,index]of lastChunkIndexByRecordId){if(decoratedIndexes.has(index))continue;decoratedIndexes.add(index);const value=updates[index];const meta=value["_meta"]&&typeof value["_meta"]==="object"?value["_meta"]:void 0;const transcript=meta?.["qwenTranscript"]&&typeof meta["qwenTranscript"]==="object"?meta["qwenTranscript"]:void 0;value["_meta"]={...meta,qwenTranscript:{...transcript,branchRecordId:branchPoints[recordId]}}}}__name(stampBranchPoints,"stampBranchPoints");async function replayTranscriptRecordPage({sessionId,page,config,encodeCursor,logger,finalizeDangling=true}){const state=parseTranscriptReplayState(page.replay,logger);const updates=[];const replayer=new HistoryReplayer(replayContext(sessionId,updates,state.cumulativeUsage,config));let replayState;let replayError;try{const replayPageState=await replayer.replayPage(page.records,{pendingToolCalls:page.direction==="backward"?[]:state.pendingToolCalls,finalizeDangling:finalizeDangling&&(page.direction==="backward"||!page.hasMore),gaps:page.gaps,includeTiming:true,...state.goalState?{goalState:state.goalState}:{},...state.goalCause?{goalCause:state.goalCause}:{}});replayState=replayPageState.replay}catch(error){logger?.warn("[historyReplay] Paged history replay failed for session %s (partial updates: %d):",sessionId,updates.length,error);replayState=replayer.getReplayState();replayError="Replay conversion failed for this page"}if(page.branchPointsByAssistantUuid){stampBranchPoints(updates,page.branchPointsByAssistantUuid)}const nextCursor=page.nextCursorState&&replayError===void 0?encodeCursor({...page.nextCursorState,...page.direction==="backward"?{}:{replay:replayState}}):void 0;return{updates,...nextCursor?{nextCursor}:{},hasMore:replayError===void 0&&page.hasMore,startTime:page.startTime,lastUpdated:page.lastUpdated,...replayError?{partial:true,replayError}:{}}}__name(replayTranscriptRecordPage,"replayTranscriptRecordPage");export{createWorkspaceMemoryExtractionErrorLogger,extractRememberErrorCode,workspaceMemoryFailureCode,shouldSuppressRememberErrorDetails,workspaceMemoryFailureDiagnostics,MAX_REMEMBER_CONTENT_BYTES,formatWorkspaceMemoryForgetSummary,formatWorkspaceMemoryDreamSummary,isValidServerName,GENERATION_MAX_PROMPT_BYTES,GENERATION_TIMEOUT_MS,executeGeneration,projectAcpToolResultUpdate,HistoryReplayLimitError,createReplayCumulativeUsage,copyCumulativeUsage,degradeReplayEnvelopeAppHtml,collectHistoryReplayUpdates,replayTranscriptRecordPage};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|