@hostclubeos/miraos 0.0.8-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-YR2SA5XW.js → MaxSizedBox-6CGCRBRO.js} +1 -1
- package/chunks/{StandaloneSessionPicker-VEXSGLU4.js → StandaloneSessionPicker-7VQOS4TU.js} +1 -1
- package/chunks/{acp-subagent-executor-ATOLWCVC.js → acp-subagent-executor-BFQRCU7R.js} +1 -1
- package/chunks/{acpAgent-DN46FTZ2.js → acpAgent-PCXQRPNU.js} +3 -3
- package/chunks/{advisor-6MI5JQGC.js → advisor-WDZ5N5ZP.js} +1 -1
- package/chunks/{agent-6HPQ4XCT.js → agent-I7Q3IPSS.js} +1 -1
- package/chunks/{agent-headless-KXAJBOPG.js → agent-headless-6LOYWI5T.js} +1 -1
- package/chunks/{agent-host-client-NOZRE2ZR.js → agent-host-client-PZZKCNQF.js} +1 -1
- package/chunks/{agent-host-connections-6FOSHEWD.js → agent-host-connections-TWWSRTKJ.js} +1 -1
- package/chunks/{autofix-pr-IMJA2KZF.js → autofix-pr-RQPGPQ4D.js} +1 -1
- package/chunks/{batch-L5VJ4XGP.js → batch-UJD5TSBN.js} +1 -1
- package/chunks/{bridge-CCRTJSIM.js → bridge-4TYLRPXZ.js} +1 -1
- package/chunks/{channel-settings-store-SB7BP6XT.js → channel-settings-store-RENJMOQ5.js} +1 -1
- package/chunks/{chunk-UC455ZS7.js → chunk-24PHAWM3.js} +1 -1
- package/chunks/{chunk-CNGBG3X5.js → chunk-26JPBN6V.js} +1 -1
- package/chunks/{chunk-W4M6JXZB.js → chunk-2MQH3J4U.js} +1 -1
- package/chunks/{chunk-GS4FZF6I.js → chunk-2RXOWQSQ.js} +1 -1
- package/chunks/{chunk-LRXYXGMT.js → chunk-323HUW2T.js} +1 -1
- package/chunks/{chunk-7DJYSBNJ.js → chunk-3BHXE7CB.js} +1 -1
- package/chunks/{chunk-7Q6RNE77.js → chunk-3GYAEXAA.js} +1 -1
- package/chunks/{chunk-VOIC5ZW2.js → chunk-3YBZW4HP.js} +1 -1
- package/chunks/{chunk-JRIVHFCG.js → chunk-4RJ2RRGZ.js} +1 -1
- package/chunks/{chunk-3NA5O4QO.js → chunk-5DIW4X4P.js} +1 -1
- package/chunks/{chunk-YELFN6AG.js → chunk-5GB6JNJX.js} +1 -1
- package/chunks/{chunk-6TNX3S5H.js → chunk-5HSNCG73.js} +2 -2
- package/chunks/{chunk-FC5IAX56.js → chunk-6HDMM7TJ.js} +1 -1
- package/chunks/{chunk-CJLKKIUW.js → chunk-6STNGEYC.js} +1 -1
- package/chunks/{chunk-ZJOVJLIH.js → chunk-7EFWNFJJ.js} +1 -1
- package/chunks/{chunk-SMO4PEHK.js → chunk-7EWIKIJI.js} +1 -1
- package/chunks/{chunk-S5NTCBEI.js → chunk-7TB6VG72.js} +1 -1
- package/chunks/{chunk-6AAVML2M.js → chunk-7TLL4JLR.js} +1 -1
- package/chunks/{chunk-IWIGJDPL.js → chunk-AOMXZNMX.js} +1 -1
- package/chunks/{chunk-5YULNQF3.js → chunk-AUM57JI2.js} +1 -1
- package/chunks/{chunk-ZQZK267X.js → chunk-AW5UCOZO.js} +1 -1
- package/chunks/{chunk-D4WMUCSK.js → chunk-C6HVNDQT.js} +2 -2
- package/chunks/{chunk-2DPE27WB.js → chunk-CC6E5CQV.js} +1 -1
- package/chunks/{chunk-SK5C26Y6.js → chunk-CLKUQP27.js} +1 -1
- package/chunks/{chunk-ARILWFTZ.js → chunk-DFMQQM4M.js} +1 -1
- package/chunks/{chunk-IJIQDCNJ.js → chunk-DP7LJTG2.js} +5 -5
- package/chunks/{chunk-7EEWU6XO.js → chunk-DQT5VL7G.js} +1 -1
- package/chunks/{chunk-AHV4IMUX.js → chunk-E4QOAV5O.js} +1 -1
- package/chunks/{chunk-G3COGFSZ.js → chunk-E4REGDEZ.js} +1 -1
- package/chunks/{chunk-MOXZO5PM.js → chunk-EAG7VZJJ.js} +1 -1
- package/chunks/{chunk-GQ24VFGQ.js → chunk-EFO6J22W.js} +1 -1
- package/chunks/{chunk-IJH5HZTB.js → chunk-EMR4QK2F.js} +1 -1
- package/chunks/{chunk-YFXKRGHT.js → chunk-EYECE2PH.js} +1 -1
- package/chunks/{chunk-7HO5DQ6V.js → chunk-EZDXHUHB.js} +1 -1
- package/chunks/{chunk-66N3SLXJ.js → chunk-FJFTKA4H.js} +1 -1
- package/chunks/{chunk-DNCXESHL.js → chunk-FSLDNLNU.js} +1 -1
- package/chunks/{chunk-K3RWL2YH.js → chunk-FSRXTX3N.js} +1 -1
- package/chunks/{chunk-4RRQ7CPF.js → chunk-FWSXFRIQ.js} +1 -1
- package/chunks/{chunk-M3IQE5G4.js → chunk-G4ATLMDH.js} +1 -1
- package/chunks/{chunk-WUZ53TKN.js → chunk-GAS3HKRX.js} +1 -1
- package/chunks/{chunk-LTXZHHNK.js → chunk-GFFL2LR2.js} +1 -1
- package/chunks/{chunk-IK5TB2CB.js → chunk-GYFIY7TD.js} +1 -1
- package/chunks/{chunk-XJKDC7OE.js → chunk-GYXRI4P5.js} +1 -1
- package/chunks/{chunk-4C5BOFDC.js → chunk-H3U7DXIU.js} +1 -1
- package/chunks/{chunk-5AJKMBPM.js → chunk-HEDVPRMD.js} +1 -1
- package/chunks/{chunk-32DLSPV5.js → chunk-HI3644FQ.js} +1 -1
- package/chunks/{chunk-CLLQQMTU.js → chunk-HTHYLMBO.js} +1 -1
- package/chunks/{chunk-VAFRD2H4.js → chunk-IW7RPDV2.js} +1 -1
- package/chunks/{chunk-5BWVS5D3.js → chunk-IXQI4K6O.js} +1 -1
- package/chunks/{chunk-BWLMXGA2.js → chunk-IYH3IZL4.js} +1 -1
- package/chunks/{chunk-XGPGIMZK.js → chunk-J52J35K4.js} +1 -1
- package/chunks/{chunk-BWFZEDYG.js → chunk-J7L5IHLG.js} +1 -1
- package/chunks/{chunk-6STDVRH5.js → chunk-JHS5B4N7.js} +2 -2
- package/chunks/{chunk-EHM4KL2U.js → chunk-JRSO5ZGU.js} +1 -1
- package/chunks/{chunk-NYGJ53Y7.js → chunk-JS6VAGRQ.js} +1 -1
- package/chunks/{chunk-QCSGHQ2P.js → chunk-KAFPULGU.js} +1 -1
- package/chunks/{chunk-CNZS2RPX.js → chunk-LDP47G5M.js} +1 -1
- package/chunks/{chunk-GM6YF6IS.js → chunk-LMZZWPKA.js} +1 -1
- package/chunks/{chunk-5SX4UPMN.js → chunk-LNCELICB.js} +1 -1
- package/chunks/{chunk-K2PGOAJP.js → chunk-LY2DRNTZ.js} +1 -1
- package/chunks/{chunk-KZZ5ZQHX.js → chunk-MMGGGYSJ.js} +1 -1
- package/chunks/{chunk-SVNSF5ZH.js → chunk-MTBU2ZIM.js} +1 -1
- package/chunks/{chunk-MV7LX23I.js → chunk-N27KICJQ.js} +1 -1
- package/chunks/{chunk-OPFBBIAQ.js → chunk-NHYFTK4O.js} +1 -1
- package/chunks/{chunk-NUDHRTIM.js → chunk-NRDHXSEE.js} +1 -1
- package/chunks/{chunk-QZNCYZ7H.js → chunk-NV5VVTYQ.js} +1 -1
- package/chunks/{chunk-7GU7HKIT.js → chunk-OEDMFKZL.js} +1 -1
- package/chunks/{chunk-V3ASW57P.js → chunk-OQAVMR6K.js} +1 -1
- package/chunks/{chunk-GBEQD55S.js → chunk-OY3Y6EMV.js} +1 -1
- package/chunks/{chunk-G7D42XGP.js → chunk-OZL4ZMGQ.js} +2 -2
- package/chunks/{chunk-PGKVSOWW.js → chunk-PKSPKVFH.js} +1 -1
- package/chunks/{chunk-OXG4BLFF.js → chunk-PNFKCYZT.js} +1 -1
- package/chunks/{chunk-JT5EN5MI.js → chunk-PTWHFVGG.js} +2 -2
- package/chunks/{chunk-3VKLOQ2P.js → chunk-QJ6ZTZFC.js} +1 -1
- package/chunks/{chunk-WZAUO3LV.js → chunk-QRGWB7IX.js} +1 -1
- package/chunks/{chunk-JCWNB45W.js → chunk-QRP2GXQD.js} +1 -1
- package/chunks/{chunk-CEVKKM22.js → chunk-RES5ET63.js} +1 -1
- package/chunks/{chunk-HCKF74X7.js → chunk-ROSJCTWB.js} +1 -1
- package/chunks/{chunk-WJXADORN.js → chunk-RR3NFNWL.js} +1 -1
- package/chunks/{chunk-HCCONFJY.js → chunk-RYQDRFLW.js} +1 -1
- package/chunks/{chunk-WSXRO2YB.js → chunk-S7CWSAUQ.js} +1 -1
- package/chunks/{chunk-MXFS555I.js → chunk-SAJKF4WS.js} +1 -1
- package/chunks/chunk-SINRWOVD.js +36 -0
- package/chunks/{chunk-DNXQKR5E.js → chunk-SJNQ6I23.js} +1 -1
- package/chunks/{chunk-DTRSC73M.js → chunk-T2GM4S4G.js} +3 -3
- package/chunks/{chunk-C3ZJUOTJ.js → chunk-TCQJO42E.js} +1 -1
- package/chunks/{chunk-G4OSEVOV.js → chunk-TIIDF23U.js} +2 -2
- package/chunks/{chunk-NNYAXFFN.js → chunk-TKH5R7RZ.js} +1 -1
- package/chunks/{chunk-JHGMLUAL.js → chunk-TSRTZD3X.js} +1 -1
- package/chunks/{chunk-GXNGLDUN.js → chunk-UXSXKLRH.js} +1 -1
- package/chunks/{chunk-MCY3IS2E.js → chunk-UYI5AMPI.js} +1 -1
- package/chunks/{chunk-7L4MR4QM.js → chunk-VO6SPDH4.js} +1 -1
- package/chunks/{chunk-SPCIIUIG.js → chunk-VRIHYTDI.js} +1 -1
- package/chunks/{chunk-Q4NEZZ6L.js → chunk-VT47A26Q.js} +1 -1
- package/chunks/{chunk-E743PFSX.js → chunk-VZOZUCZX.js} +1 -1
- package/chunks/{chunk-WW43VZ6O.js → chunk-WLEGTKGA.js} +1 -1
- package/chunks/{chunk-77GGGTWS.js → chunk-XHCJN4A2.js} +1 -1
- package/chunks/{chunk-UZAFPEVN.js → chunk-XTRZ5PHG.js} +1 -1
- package/chunks/{chunk-DTNW2CM3.js → chunk-Y4GZOZWD.js} +1 -1
- package/chunks/{chunk-YOBM4ZFW.js → chunk-YUCAGV52.js} +2 -2
- package/chunks/{chunk-WOMJLK3E.js → chunk-YWQM4TSO.js} +1 -1
- package/chunks/{chunk-WN6Z3J27.js → chunk-YYTOHY4V.js} +1 -1
- package/chunks/{chunk-VOCM2M4K.js → chunk-Z25W2S5N.js} +1 -1
- package/chunks/{chunk-QWNTORRT.js → chunk-Z6GECBAJ.js} +1 -1
- package/chunks/{chunk-XNP5JXCS.js → chunk-ZJU4B4WX.js} +1 -1
- package/chunks/{chunk-MCHMWRNO.js → chunk-ZSHDQPAO.js} +1 -1
- package/chunks/{chunk-POMEWCFJ.js → chunk-ZUWLTGSR.js} +6 -6
- package/chunks/{codex-subagent-executor-TPO62HU5.js → codex-subagent-executor-2V4NB7IR.js} +1 -1
- package/chunks/{config-utils-6GWIYBUK.js → config-utils-5B2LYCON.js} +1 -1
- package/chunks/{contextCommand-WWVGDTOL.js → contextCommand-UPQGRXWK.js} +1 -1
- package/chunks/{core-runtime-ASQR33TV.js → core-runtime-DPMH2BXK.js} +1 -1
- package/chunks/{create-sub-session-XY2FXSPE.js → create-sub-session-EJVB3FE5.js} +1 -1
- package/chunks/{cron-create-HY3TLNV2.js → cron-create-V2A7PMQC.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-ILW3NJJC.js → daemon-git-worktree-guard-YEIMR2X7.js} +1 -1
- package/chunks/{daemon-status-provider-JVOGEKWY.js → daemon-status-provider-6BRB5TG3.js} +1 -1
- package/chunks/{daemon-trust-policy-XXRBG4JE.js → daemon-trust-policy-BEXVFO4M.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-UL73ADOZ.js → daemon-trust-policy-monitor-BVS6LXBX.js} +1 -1
- package/chunks/{deferred-core-runtime-PT747R7S.js → deferred-core-runtime-NTKFHL5J.js} +1 -1
- package/chunks/{edit-4PJ3NPFA.js → edit-LRG3TMHP.js} +1 -1
- package/chunks/{enterPlanMode-KQ62QN7S.js → enterPlanMode-KOUSHJHR.js} +1 -1
- package/chunks/{environment-H4HADXGA.js → environment-54CM3OXE.js} +1 -1
- package/chunks/{errors-OSD4ZZGR.js → errors-D6XR3NH4.js} +1 -1
- package/chunks/{execution-tool-PHHGLKWC.js → execution-tool-7RZ2JLEK.js} +1 -1
- package/chunks/{execution-worker-MH3CV66T.js → execution-worker-LXQ7WAFG.js} +1 -1
- package/chunks/{exitPlanMode-OU5YP4XN.js → exitPlanMode-4FGFA2QC.js} +1 -1
- package/chunks/{fast-path-WKOMHBWN.js → fast-path-4B7OKPYK.js} +1 -1
- package/chunks/{glob-FYCOEQPM.js → glob-N2D7SY23.js} +1 -1
- package/chunks/{goal-tools-T27GSDNM.js → goal-tools-7RNSDRFO.js} +1 -1
- package/chunks/{handleAutoUpdate-XXCPJLKO.js → handleAutoUpdate-PKKJQAKG.js} +1 -1
- package/chunks/{i18n-3B2PRJM2.js → i18n-F3OAHCLJ.js} +1 -1
- package/chunks/{initializer-HSFVDRTR.js → initializer-OL3DDWR7.js} +1 -1
- package/chunks/{installationInfo-SJJ2DYZ6.js → installationInfo-D2L743RV.js} +1 -1
- package/chunks/{interactive-mod-session-BWY2JRSQ.js → interactive-mod-session-2GXRCQKR.js} +1 -1
- package/chunks/{list-TGCI3MBM.js → list-PU7ZXBY5.js} +1 -1
- package/chunks/{llm-FYR73GKD.js → llm-V42HGUVH.js} +4 -4
- package/chunks/{loadedSettingsAdapter-DUDCINQL.js → loadedSettingsAdapter-KAEVWWRX.js} +1 -1
- package/chunks/{local-7PEOBJKE.js → local-KM5F5RAB.js} +1 -1
- package/chunks/{local-execution-environment-Q4OOA7BL.js → local-execution-environment-OEO2KW3M.js} +1 -1
- package/chunks/{loggingContentGenerator-VVESQOIQ.js → loggingContentGenerator-DQLXSDZR.js} +1 -1
- package/chunks/{loop-wakeup-M2XLAAKZ.js → loop-wakeup-CJICM24Y.js} +1 -1
- package/chunks/{manage-memory-FRVWHM2C.js → manage-memory-7CV6LF4C.js} +1 -1
- package/chunks/{managed-execution-engine-AVIM6AQU.js → managed-execution-engine-JEAIQ7L4.js} +1 -1
- package/chunks/{managed-local-serve-GIXHGFIU.js → managed-local-serve-KA37YWRW.js} +1 -1
- package/chunks/{managed-npm-update-3QSXGSHW.js → managed-npm-update-TSUUH3NN.js} +1 -1
- package/chunks/{managed-runtime-attestation-worker-ML4TCRAW.js → managed-runtime-attestation-worker-PUZ2ECM5.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-JWJFGLBM.js → managed-runtime-bootstrap-SERIRKPD.js} +1 -1
- package/chunks/{managed-runtime-session-worker-4ISKROGZ.js → managed-runtime-session-worker-UOXK63YX.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-C44V2CPM.js → managed-runtime-ssh-worker-VKZYIX6R.js} +1 -1
- package/chunks/{managed-session-authority-UJ3FSKMD.js → managed-session-authority-5FYS3G3M.js} +1 -1
- package/chunks/{mcp-BWCLHHZ6.js → mcp-TRPV3K74.js} +1 -1
- package/chunks/{memory-5XQ2JVNS.js → memory-5CMNRPM2.js} +1 -1
- package/chunks/{model-call-collection-DXK2SIDR.js → model-call-collection-S4JKVFUO.js} +1 -1
- package/chunks/{model-configuration-6OLZS4C3.js → model-configuration-NEIDLKWQ.js} +1 -1
- package/chunks/{modelConfigUtils-5S5PC2RR.js → modelConfigUtils-LZLQOZKJ.js} +1 -1
- package/chunks/{monitor-6GKCWWUI.js → monitor-5MNKK5AO.js} +1 -1
- package/chunks/{nonInteractiveCli-ROHAB2H7.js → nonInteractiveCli-DDTGU2ER.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-OWCCSC5Y.js → nonInteractiveToolExecutor-N7PCYCKO.js} +1 -1
- package/chunks/{notebook-edit-WNRQ3QJZ.js → notebook-edit-7HIBTFFW.js} +1 -1
- package/chunks/{omni-DJ5RGNKA.js → omni-MX7BMOL5.js} +1 -1
- package/chunks/{openaiContentGenerator-237NVB63.js → openaiContentGenerator-NOIIZNRX.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-J33TCZKQ.js → openaiResponsesContentGenerator-5JJ6G7RS.js} +1 -1
- package/chunks/{pidfile-F7IYTFLX.js → pidfile-OHAGZOTV.js} +1 -1
- package/chunks/{processUtils-C6CSXITS.js → processUtils-TCDNCYVB.js} +1 -1
- package/chunks/{prompt-terminal-ledger-ZGYWPFJF.js → prompt-terminal-ledger-4ZUOCMOS.js} +1 -1
- package/chunks/{reactive-degrade-QKXPZQ3W.js → reactive-degrade-C7CGUJNP.js} +1 -1
- package/chunks/{read-file-GSNUMHRE.js → read-file-L4ZF6VDG.js} +1 -1
- package/chunks/{resumeHistoryUtils-4GUCHQGU.js → resumeHistoryUtils-WK3I4OIL.js} +1 -1
- package/chunks/{review-M2QGZFIO.js → review-F6JGI2LP.js} +1 -1
- package/chunks/{ripGrep-X4JTJZC6.js → ripGrep-L6M2GPCM.js} +1 -1
- package/chunks/{run-qwen-serve-4WW37RL2.js → run-qwen-serve-D5HB55SC.js} +1 -1
- package/chunks/{runtime-EFHJ6REE.js → runtime-CH3RAOQL.js} +1 -1
- package/chunks/{sandboxConfig-5XMIRDS4.js → sandboxConfig-EADWCO37.js} +1 -1
- package/chunks/{scheduled-tasks-ZCYM5YQJ.js → scheduled-tasks-PBKD4BHY.js} +1 -1
- package/chunks/{scheduler-5UAKCD5Z.js → scheduler-U5K3523K.js} +1 -1
- package/chunks/{search-memory-KKPYK33Q.js → search-memory-Y2IPKBDP.js} +1 -1
- package/chunks/{send-message-KOZRSWXO.js → send-message-JJQG2S6D.js} +1 -1
- package/chunks/{serve-5HSHEBMT.js → serve-2ZYS47MO.js} +1 -1
- package/chunks/{server-MC6KHP3G.js → server-5GMO4IHU.js} +3 -3
- package/chunks/{session-Z5HFG4IQ.js → session-LLOOVSHK.js} +1 -1
- package/chunks/{session-attachments-root-K2E5ETD4.js → session-attachments-root-XCLXH2XO.js} +1 -1
- package/chunks/{session-execution-engine-selector-NZA6CAJB.js → session-execution-engine-selector-5QPWJZSF.js} +1 -1
- package/chunks/{session-pr-refresh-OYJ56U3L.js → session-pr-refresh-MDBOAN3R.js} +1 -1
- package/chunks/{sessionService-BC56MX3G.js → sessionService-VKAHCTCC.js} +1 -1
- package/chunks/{settings-OHB77GXH.js → settings-ULEB2IYZ.js} +1 -1
- package/chunks/{shell-VKSH7JVL.js → shell-RBEKIYKU.js} +1 -1
- package/chunks/{skill-HQ4C2C3X.js → skill-GEVOEFMZ.js} +1 -1
- package/chunks/{skill-settings-6WPQFE3V.js → skill-settings-4IMGLYJW.js} +1 -1
- package/chunks/{spawnChannel-MXKVLS24.js → spawnChannel-B7L5PWQ6.js} +1 -1
- package/chunks/{standalone-update-NZP3OAZZ.js → standalone-update-SYQM6NOC.js} +1 -1
- package/chunks/{start-opentui-ui-25YQQD3O.js → start-opentui-ui-N427PLF4.js} +2 -2
- package/chunks/{startInteractiveUI-DWQJNIIV.js → startInteractiveUI-AS6GZKJJ.js} +1 -1
- package/chunks/{team-create-RSD7IADX.js → team-create-MN6FHUHU.js} +1 -1
- package/chunks/{team-plan-approval-XAOKZ6BR.js → team-plan-approval-OUYBIT7H.js} +1 -1
- package/chunks/{terminal-image-renderer-P5AGEOYS.js → terminal-image-renderer-MXZDUEOS.js} +1 -1
- package/chunks/{theme-manager-YBKJYPVQ.js → theme-manager-QOYSKWFK.js} +1 -1
- package/chunks/{tool-call-HJCSPR6N.js → tool-call-Q5NLEQFD.js} +1 -1
- package/chunks/{tool-result-media-SPWVV3OS.js → tool-result-media-NZJZTOBQ.js} +1 -1
- package/chunks/{tool-search-YWCOODLL.js → tool-search-D6Y45RNQ.js} +1 -1
- package/chunks/{total-session-admission-HKACVEI2.js → total-session-admission-36W7MDHP.js} +1 -1
- package/chunks/{trustedFolders-BXLZULWO.js → trustedFolders-XW5VH6HK.js} +1 -1
- package/chunks/{update-relaunch-CBJVLG6S.js → update-relaunch-KQPR2HAP.js} +1 -1
- package/chunks/{updateCheck-2J6RY3L3.js → updateCheck-SRW67WAX.js} +1 -1
- package/chunks/{upload-config-EN5XYA3V.js → upload-config-BTJNYMRX.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-LF7VIUER.js → useAutoAcceptIndicator-N3RRUBSL.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-63TR5JOG.js → validateNonInterActiveAuth-SWNH4FY4.js} +1 -1
- package/chunks/{version-F22SKNME.js → version-6R6LSGXO.js} +1 -1
- package/chunks/{web-fetch-ULH7TOLR.js → web-fetch-Y7LBAU3R.js} +1 -1
- package/chunks/{web-search-C3ORWAWR.js → web-search-IB4NYYUH.js} +1 -1
- package/chunks/{workflow-4ATPGZ5N.js → workflow-TR4YIPJO.js} +1 -1
- package/chunks/{workflow-ancestor-trust-AJ27EBZD.js → workflow-ancestor-trust-AHDUBOR7.js} +1 -1
- package/chunks/{workspace-agents-VLAJGYJF.js → workspace-agents-MY2NFL6A.js} +1 -1
- package/chunks/{workspace-providers-status-TFAXNJ6L.js → workspace-providers-status-DNCCKFVE.js} +1 -1
- package/chunks/{workspace-recovery-worker-GKYYJPXV.js → workspace-recovery-worker-22VK4T4R.js} +1 -1
- package/chunks/{workspace-registration-store-ANR3STGQ.js → workspace-registration-store-64TGRRGC.js} +1 -1
- package/chunks/{workspace-registry-OVHNLVBM.js → workspace-registry-E6LFL5GL.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-IEN2G7JP.js → workspace-runtime-coordinator-UHJHBIQT.js} +1 -1
- package/chunks/{workspace-service-NISFZTBE.js → workspace-service-OVEYIQOC.js} +1 -1
- package/chunks/{workspace-skills-status-QRF5ZXMT.js → workspace-skills-status-3NKXA5SK.js} +1 -1
- package/chunks/{workspace-trust-reconciler-X3XMX2GJ.js → workspace-trust-reconciler-JF7YHR52.js} +1 -1
- package/chunks/{write-file-SF42KZAH.js → write-file-FSTHYKKZ.js} +1 -1
- package/chunks/{zoom-image-4UMB6G3P.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-OHOG4HSN.js +0 -31
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{SessionNotFoundError}from"./chunk-CVMEBFLL.js";import{SessionIdCaseConflictError,SessionService,readSessionTranscriptSnapshot}from"./chunk-
|
|
3
|
+
import{SessionNotFoundError}from"./chunk-CVMEBFLL.js";import{SessionIdCaseConflictError,SessionService,readSessionTranscriptSnapshot}from"./chunk-ZUWLTGSR.js";import{SessionExecutionEngineError}from"./chunk-I7KO7V6B.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionExecutionEngineSelector(options){return async selection=>{const{managed}=options;if(selection.operation==="spawn"){if(!managed||isDeferredCreation(selection))return"legacy";const compatibility2=await checkCompatibility(managed,selection);return compatibility2.status==="compatible"?"managed":"legacy"}const{sessionId,workspaceCwd}=selection.request;const service=new SessionService(workspaceCwd,{runtimeBaseDir:options.runtimeBaseDir});const persistedSessionId=await resolvePersistedSessionId(service,sessionId);const snapshot=persistedSessionId===void 0?void 0:await readSessionTranscriptSnapshot(service.getSessionTranscriptPath(persistedSessionId),persistedSessionId,false);if(!snapshot)throw new SessionNotFoundError(sessionId);const owner=snapshot.executionEngine;if(owner.status!=="verified"){throw new SessionExecutionEngineError(sessionId,owner.reason)}if(owner.engine==="legacy")return"legacy";const compatibility=managed?await checkCompatibility(managed,selection):{status:"unknown",reason:"no Managed engine is available"};if(compatibility.status==="compatible")return"managed";throw new SessionExecutionEngineError(sessionId,`belongs to managed, which cannot run here: ${compatibility.reason}`)}}__name(createSessionExecutionEngineSelector,"createSessionExecutionEngineSelector");function createPairedExecutionEngines(options){return{legacy:options.legacy,managed:options.managed?.factory??managedEngineUnavailable,select:createSessionExecutionEngineSelector(options)}}__name(createPairedExecutionEngines,"createPairedExecutionEngines");var managedEngineUnavailable=__name(async()=>{throw new Error("No Managed execution engine is available in this host.")},"managedEngineUnavailable");function isDeferredCreation(selection){const{request}=selection;return selection.daemonOwnedStandalone||request.parentSessionId!==void 0||request.worktree!==void 0||request.branch!==void 0||request.sourceType!==void 0&&(request.sourceType!=="default"||request.sourceId!==void 0)}__name(isDeferredCreation,"isDeferredCreation");async function checkCompatibility(managed,selection){try{return await managed.evaluate(selection)}catch{return{status:"unknown",reason:"the compatibility check failed"}}}__name(checkCompatibility,"checkCompatibility");async function resolvePersistedSessionId(service,sessionId){try{return await service.findSessionIdIgnoringCase(sessionId)}catch(error){if(error instanceof SessionIdCaseConflictError&&error.reason==="case_conflict"&&error.candidateSessionId===sessionId){return sessionId}throw error}}__name(resolvePersistedSessionId,"resolvePersistedSessionId");export{createSessionExecutionEngineSelector,createPairedExecutionEngines};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Qwen Team
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{retryContext}from"./chunk-IDHSLPPU.js";import{MODEL_GENERATION_CONFIG_FIELDS,PROVIDER_SOURCED_FIELDS,REASONING_EFFORT_TIERS,clampReasoningEffort,defaultModalities,getGptReasoningCapabilities,normalize,parseModelReasoningCapabilities,tokenLimit}from"./chunk-EV2CXPMN.js";import{AuthType}from"./chunk-EW6HVTD5.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 DEFAULT_TIMEOUT=12e4;var DISABLED_REQUEST_TIMEOUT_MS=2147483647;function resolveRequestTimeout(timeout){if(timeout===void 0||timeout===null){return DEFAULT_TIMEOUT}return timeout<=0?DISABLED_REQUEST_TIMEOUT_MS:timeout}__name(resolveRequestTimeout,"resolveRequestTimeout");var DEFAULT_STREAM_IDLE_TIMEOUT_MS=24e4;var QWEN_STREAM_IDLE_TIMEOUT_MS_ENV="QWEN_STREAM_IDLE_TIMEOUT_MS";var MAX_STREAM_GUARD_TIMEOUT_MS=2147483647;var DEFAULT_STREAM_MAX_LIFETIME_MS=9e5;var QWEN_STREAM_MAX_LIFETIME_MS_ENV="QWEN_STREAM_MAX_LIFETIME_MS";var DEFAULT_MAX_RETRIES=3;var DEFAULT_OPENAI_BASE_URL="https://api.openai.com/v1";var DEFAULT_DASHSCOPE_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1";function getDashscopeProxyBaseUrl(){return process.env["DASHSCOPE_PROXY_BASE_URL"]}__name(getDashscopeProxyBaseUrl,"getDashscopeProxyBaseUrl");function normalizeOpenAiWireBaseUrl(baseUrl){return(baseUrl||DEFAULT_OPENAI_BASE_URL).replace(/\/v1\/?$/,"").replace(/\/$/,"")}__name(normalizeOpenAiWireBaseUrl,"normalizeOpenAiWireBaseUrl");init_esbuild_shims();function getSystemPromptModel(generation,model=generation.model??""){if(generation.authType==="anthropic"||generation.authType==="openai-responses"){return generation.model??model}if(generation.authType==="qwen-subscription"){const override=generation.extra_body?.["model"];return!retryContext.getStore()?.singleAttempt&&typeof override==="string"?override:model}return getRequestModel(generation,model)}__name(getSystemPromptModel,"getSystemPromptModel");function getRequestModel(generation,model=generation.model??""){if(retryContext.getStore()?.singleAttempt||generation.authType!==void 0&&generation.authType!=="openai"&&generation.authType!=="qwen-oauth")return model;const override={...generation.samplingParams,...generation.extra_body}["model"];return typeof override==="string"?override:model}__name(getRequestModel,"getRequestModel");init_esbuild_shims();function isImageGenerationCapable(model){return model.supportsImageGeneration===true||model.imageOnly===true}__name(isImageGenerationCapable,"isImageGenerationCapable");init_esbuild_shims();var RUNTIME_SNAPSHOT_PREFIX="$runtime|";function buildRuntimeSnapshotId(authType,modelId){return`${RUNTIME_SNAPSHOT_PREFIX}${authType}|${modelId}`}__name(buildRuntimeSnapshotId,"buildRuntimeSnapshotId");function stripRuntimeSnapshotPrefix(modelId){let id=modelId;while(id.startsWith(RUNTIME_SNAPSHOT_PREFIX)){const stripped=id.split("|").slice(2).join("|");if(!stripped)break;id=stripped}return id}__name(stripRuntimeSnapshotPrefix,"stripRuntimeSnapshotPrefix");init_esbuild_shims();import process2 from"node:process";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("MODEL_REGISTRY");function validateAuthTypeKey(key){if(Object.values(AuthType).includes(key)){return key}return void 0}__name(validateAuthTypeKey,"validateAuthTypeKey");function resolveProviderProtocol(providerId,providerProtocol){const explicit=providerProtocol&&Object.hasOwn(providerProtocol,providerId)?providerProtocol[providerId]:void 0;if(explicit!==void 0){return validateAuthTypeKey(explicit)}return validateAuthTypeKey(providerId)}__name(resolveProviderProtocol,"resolveProviderProtocol");function resolveModelProtocol(providerId,model,providerProtocol){const protocol=resolveProviderProtocol(providerId,providerProtocol);if(!protocol||model.wireApi===void 0)return protocol;if(model.wireApi!=="chat-completions"&&model.wireApi!=="responses"){throw new Error(`Invalid wireApi "${model.wireApi}" for provider "${providerId}". Expected "chat-completions" or "responses".`)}if(protocol!=="openai"&&protocol!=="openai-responses"){throw new Error(`Provider "${providerId}" uses protocol "${protocol}"; wireApi is only supported for OpenAI-compatible models.`)}return model.wireApi==="responses"?"openai-responses":"openai"}__name(resolveModelProtocol,"resolveModelProtocol");function tryResolveModelProtocol(providerId,model,providerProtocol){try{return resolveModelProtocol(providerId,model,providerProtocol)}catch{return void 0}}__name(tryResolveModelProtocol,"tryResolveModelProtocol");function validateModelProvidersConfig(modelProviders,providerProtocol){for(const providerId of new Set([...Object.keys(modelProviders??{}),...Object.keys(providerProtocol??{})])){resolveProviderProtocol(providerId,providerProtocol);const models=modelProviders?.[providerId];if(!Array.isArray(models))continue;for(const model of models){resolveModelProtocol(providerId,model,providerProtocol)}}}__name(validateModelProvidersConfig,"validateModelProvidersConfig");function resolveModelSelectionAuthType(authType,modelId,modelProviders,providerProtocol,baseUrl){if(!modelId||authType!=="openai"&&authType!=="openai-responses"){return authType}const candidates=[];for(const[providerId,models]of Object.entries(modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const protocol=resolveModelProtocol(providerId,model,providerProtocol);if(model.id===modelId&&(protocol===authType||(model.wireApi!==void 0||resolveProviderProtocol(providerId,providerProtocol)==="openai-responses")&&(protocol==="openai"||protocol==="openai-responses"))){candidates.push({model,authType:protocol})}}}const preferred=__name(entries=>entries.find(entry=>entry.authType===authType)??entries[0],"preferred");const exact=baseUrl===void 0?void 0:preferred(candidates.filter(entry=>(entry.model.baseUrl||null)===(baseUrl||null)));return(exact??preferred(candidates))?.authType??authType}__name(resolveModelSelectionAuthType,"resolveModelSelectionAuthType");function shouldUseCanonicalModalities(modelId){return/^minimax-m3/i.test(modelId.trim().toLowerCase())}__name(shouldUseCanonicalModalities,"shouldUseCanonicalModalities");function modelRegistryKey(id,baseUrl){return baseUrl?`${id}\0${baseUrl}`:id}__name(modelRegistryKey,"modelRegistryKey");var ModelRegistry=class _ModelRegistry{static{__name(this,"ModelRegistry")}modelsByAuthType;providerProtocolConfig;modelProvidersConfig;getDefaultBaseUrl(authType){switch(authType){case"openai":return DEFAULT_OPENAI_BASE_URL;default:return""}}constructor(modelProvidersConfig,providerProtocolConfig){validateModelProvidersConfig(modelProvidersConfig,providerProtocolConfig);this.modelsByAuthType=new Map;this.providerProtocolConfig=providerProtocolConfig??{};this.modelProvidersConfig=modelProvidersConfig;this.registerProvidersConfig(modelProvidersConfig)}registerProvidersConfig(modelProvidersConfig){if(!modelProvidersConfig)return;for(const[providerId,models]of Object.entries(modelProvidersConfig)){const protocol=resolveProviderProtocol(providerId,this.providerProtocolConfig);if(!protocol){const knownProtocols=Object.values(AuthType).filter(value=>value!=="openai-responses").join(", ");const mapped=Object.hasOwn(this.providerProtocolConfig,providerId)?this.providerProtocolConfig[providerId]:void 0;const message=mapped!==void 0?`Provider "${providerId}" maps to "${mapped}" via providerProtocol, which is not a known protocol (${knownProtocols}); skipping.`:`Provider "${providerId}" in modelProviders is not a built-in protocol (${knownProtocols}) and has no providerProtocol mapping; skipping. Add providerProtocol["${providerId}"] to route it to an SDK protocol.`;debugLogger.warn(message);continue}if(protocol==="qwen-oauth"||protocol==="qwen-subscription"){if(Array.isArray(models)){for(const model of models){resolveModelProtocol(providerId,model,this.providerProtocolConfig)}}continue}this.registerAuthTypeModels(protocol,models,providerId)}}registerAuthTypeModels(authType,models,providerId){if(!Array.isArray(models)){debugLogger.warn(`modelProviders for provider "${providerId??authType}" is not an array; skipping. Expected ModelConfig[]; legacy { protocol, models } entries are normally rewritten by the v5->v4 settings migration.`);return}const providerLabel=providerId&&providerId!==authType?` (provider "${providerId}")`:"";for(const config of models){const modelAuthType=resolveModelProtocol(providerId??authType,config,providerId?this.providerProtocolConfig:void 0);const modelMap=this.modelsByAuthType.get(modelAuthType)??new Map;const key=modelRegistryKey(config.id,config.baseUrl);if(modelMap.has(key)){debugLogger.warn(`Duplicate model id "${config.id}"${config.baseUrl?` with baseUrl "${config.baseUrl}"`:""} for protocol "${modelAuthType}"${providerLabel}. Using the first registered config.`);continue}const resolved=this.resolveModelConfig(config,modelAuthType);modelMap.set(key,resolved);this.modelsByAuthType.set(modelAuthType,modelMap)}}getModelsForAuthType(authType){const models=this.modelsByAuthType.get(authType);if(!models)return[];return Array.from(models.values()).filter(model=>!model.realtimeOnly).map(model=>({id:model.id,label:model.name,description:model.description,capabilities:model.capabilities,authType:model.authType,isVision:model.capabilities?.vision??false,contextWindowSize:model.generationConfig.contextWindowSize??tokenLimit(model.id),modalities:model.generationConfig.modalities,baseUrl:model.baseUrl,...model.registryBaseUrl!==void 0?{registryBaseUrl:model.registryBaseUrl}:{},envKey:model.envKey,fastOnly:model.fastOnly,voiceOnly:model.voiceOnly,visionOnly:model.visionOnly,supportsImageGeneration:model.supportsImageGeneration,imageOnly:model.imageOnly}))}getModel(authType,modelId,baseUrl){const models=this.modelsByAuthType.get(authType);if(!models)return void 0;if(baseUrl!==void 0){const exact=models.get(modelRegistryKey(modelId,baseUrl??void 0));if(exact)return exact;if(baseUrl===null)return void 0;const plain2=models.get(modelId);return plain2?.baseUrl===baseUrl?plain2:void 0}const plain=models.get(modelId);if(plain)return plain;for(const model of models.values()){if(model.id===modelId)return model}return void 0}hasModel(authType,modelId,baseUrl){return this.getModel(authType,modelId,baseUrl)!==void 0}getDefaultModelForAuthType(authType){const models=this.modelsByAuthType.get(authType);if(!models||models.size===0)return void 0;return Array.from(models.values()).find(model=>!model.imageOnly&&!model.voiceOnly&&!model.realtimeOnly)}resolveModelConfig(config,authType){this.validateModelConfig(config,authType);const generationConfig={...config.generationConfig??{}};if(generationConfig.modalities===void 0||shouldUseCanonicalModalities(config.id)){generationConfig.modalities=defaultModalities(config.id)}return{...config,authType,name:config.name||config.id,baseUrl:config.baseUrl||this.getDefaultBaseUrl(authType),...config.baseUrl?{registryBaseUrl:config.baseUrl}:{},generationConfig,capabilities:config.capabilities||{}}}validateModelConfig(config,authType){if(!config.id){throw new Error(`Model config in authType '${authType}' missing required field: id`)}const selectorOnlyCount=[config.fastOnly,config.voiceOnly,config.visionOnly,config.imageOnly,config.realtimeOnly].filter(Boolean).length;if(selectorOnlyCount>1){debugLogger.warn(`Model "${config.id}" in authType "${authType}" has multiple selector-only flags. It will be unreachable in at least one model selector.`)}}reloadModels(modelProvidersConfig,providerProtocolConfig){const reloaded=new _ModelRegistry(modelProvidersConfig,providerProtocolConfig??this.providerProtocolConfig);this.modelsByAuthType=reloaded.modelsByAuthType;this.providerProtocolConfig=reloaded.providerProtocolConfig;this.modelProvidersConfig=reloaded.modelProvidersConfig}getModelProvidersConfig(){return this.modelProvidersConfig}getProviderProtocolConfig(){return this.providerProtocolConfig}};var debugLogger2=createDebugLogger("ModelsConfig");var ModelsConfig=class _ModelsConfig{static{__name(this,"ModelsConfig")}modelRegistry;currentAuthType;currentRegistryBaseUrl;_generationConfig;generationConfigSources;strictModelProviderSelection=false;hasManualCredentials=false;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(value){if(value===null||typeof value!=="object"){return value}if(Array.isArray(value)){return value.map(v=>_ModelsConfig.deepClone(v))}const out={};for(const key of Object.keys(value)){out[key]=_ModelsConfig.deepClone(value[key])}return out}constructor(options={}){this.modelRegistry=new ModelRegistry(options.modelProvidersConfig,options.providerProtocolConfig);this.onModelChange=options.onModelChange;this._generationConfig={...options.generationConfig||{}};this.generationConfigSources=options.generationConfigSources||{};this.authTypeWasExplicitlyProvided=options.initialAuthType!==void 0;const initialModelId=this._generationConfig.model;this.currentAuthType=options.initialAuthType?resolveModelSelectionAuthType(options.initialAuthType,this.generationConfigSources["model"]?.kind==="default"?void 0:initialModelId,options.modelProvidersConfig,options.providerProtocolConfig,options.initialRegistryBaseUrl):void 0;if(this.currentAuthType&&initialModelId){const initialModel=this.modelRegistry.getModel(this.currentAuthType,initialModelId,options.initialRegistryBaseUrl);if(initialModel){this.currentRegistryBaseUrl=initialModel.registryBaseUrl??null}}}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:_ModelsConfig.deepClone(this._generationConfig),generationConfigSources:_ModelsConfig.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId,currentRegistryBaseUrl:this.currentRegistryBaseUrl}}rollbackToStateSnapshot(snapshot){this.currentAuthType=snapshot.currentAuthType;this._generationConfig=snapshot.generationConfig;this.generationConfigSources=snapshot.generationConfigSources;this.strictModelProviderSelection=snapshot.strictModelProviderSelection;this.hasManualCredentials=snapshot.hasManualCredentials;this.activeRuntimeModelSnapshotId=snapshot.activeRuntimeModelSnapshotId;this.currentRegistryBaseUrl=snapshot.currentRegistryBaseUrl}getModel(){return this._generationConfig.model||""}getCurrentAuthType(){return this.currentAuthType}clearAuth(){this.currentAuthType=void 0;this._generationConfig={};this.generationConfigSources={};this.currentRegistryBaseUrl=void 0;this.activeRuntimeModelSnapshotId=void 0;this.hasManualCredentials=false;this.strictModelProviderSelection=false}getCurrentRegistryBaseUrl(){return this.currentRegistryBaseUrl}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(authType){return this.modelRegistry.getModelsForAuthType(authType)}getAllConfiguredModels(authTypes){const inputAuthTypes=authTypes&&authTypes.length>0?authTypes:Object.values(AuthType);const seen=new Set;const orderedAuthTypes=[];for(const authType of inputAuthTypes){if(!seen.has(authType)){seen.add(authType);orderedAuthTypes.push(authType)}}const runtimeOption=this.getRuntimeModelOption();const allModels=[];for(const authType of orderedAuthTypes){if(runtimeOption&&runtimeOption.authType===authType){allModels.push(runtimeOption)}allModels.push(...this.modelRegistry.getModelsForAuthType(authType))}return allModels}hasModel(authType,modelId){return this.modelRegistry.hasModel(authType,modelId)}getResolvedModel(authType,modelId,baseUrl){return this.modelRegistry.getModel(authType,modelId,baseUrl)}getModelDisplayName(modelId){if(!this.currentAuthType)return modelId;const resolved=(this.currentRegistryBaseUrl!==void 0?this.modelRegistry.getModel(this.currentAuthType,modelId,this.currentRegistryBaseUrl):void 0)??this.modelRegistry.getModel(this.currentAuthType,modelId);return resolved?.name??modelId}async setModel(newModel,metadata){if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,newModel)){await this.switchModel(this.currentAuthType,newModel);return}const siblingWire=this.currentAuthType==="openai"?"openai-responses":this.currentAuthType==="openai-responses"?"openai":void 0;if(siblingWire&&this.modelRegistry.hasModel(siblingWire,newModel)){await this.switchModel(siblingWire,newModel);return}const rollbackSnapshot=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=false;this.currentRegistryBaseUrl=void 0;this._generationConfig.model=newModel;this.generationConfigSources["model"]={kind:"programmatic",detail:metadata?.reason||"setModel"};this.applyRawModelDerivedDefaults(newModel);if(this.onModelChange&&this.currentAuthType){await this.onModelChange(this.currentAuthType,true)}}catch(error){this.rollbackToStateSnapshot(rollbackSnapshot);throw error}}applyRawModelDerivedDefaults(modelId){if(this.shouldUpdateModelDerivedDefault("modalities")){this._generationConfig.modalities=defaultModalities(modelId);this.generationConfigSources["modalities"]={kind:"computed",detail:"auto-detected from model"}}if(this.shouldUpdateModelDerivedDefault("contextWindowSize")){this._generationConfig.contextWindowSize=tokenLimit(modelId,"input");this.generationConfigSources["contextWindowSize"]={kind:"computed",detail:"auto-detected from model"}}}shouldUpdateModelDerivedDefault(field){const source=this.generationConfigSources[field];return source===void 0||source.kind==="computed"||source.kind==="default"||source.kind==="modelProviders"||source.kind==="programmatic"||source.kind==="unknown"}async switchModel(authType,modelId,options){const runtimeModelSnapshotId=this.extractRuntimeModelSnapshotId(modelId);if(runtimeModelSnapshotId){await this.switchToRuntimeModel(runtimeModelSnapshotId,options?.initializeIfNeeded);return}const rollbackSnapshot=this.createStateSnapshotForRollback();try{const isAuthTypeChange=authType!==this.currentAuthType;this.currentAuthType=authType;const model=this.modelRegistry.getModel(authType,modelId,options?.baseUrl);if(!model){throw new Error(`Model '${modelId}' not found for authType '${authType}'`)}if(model.imageOnly||model.voiceOnly||model.realtimeOnly){throw new Error(`${model.imageOnly?"Image":model.voiceOnly?"Voice":"Realtime"}-only model '${modelId}' cannot be used as the primary model`)}const previousModelId=rollbackSnapshot.generationConfig.model||"";const previousAuthType=rollbackSnapshot.currentAuthType;const previousModel=previousAuthType&&previousModelId?this.modelRegistry.getModel(previousAuthType,previousModelId,rollbackSnapshot.currentRegistryBaseUrl)??this.modelRegistry.getModel(previousAuthType,previousModelId):void 0;const sharesOpenAICredentials=(authType==="openai"||authType==="openai-responses")&&(previousAuthType==="openai"||previousAuthType==="openai-responses");const sameEndpoint=__name((a,b)=>a===b||isAuthTypeChange&&sharesOpenAICredentials&&normalizeOpenAiWireBaseUrl(a)===normalizeOpenAiWireBaseUrl(b),"sameEndpoint");const canReusePreviousApiKey=(!isAuthTypeChange||sharesOpenAICredentials&&sameEndpoint(rollbackSnapshot.generationConfig.baseUrl,model.baseUrl))&&!!rollbackSnapshot.generationConfig.apiKey&&!!model.envKey&&previousModel!==void 0&&previousModel.envKey===model.envKey&&sameEndpoint(previousModel.baseUrl,model.baseUrl);const previousApiKey=canReusePreviousApiKey?rollbackSnapshot.generationConfig.apiKey:void 0;const previousApiKeySource=canReusePreviousApiKey?rollbackSnapshot.generationConfigSources["apiKey"]:void 0;this.applyResolvedModelDefaults(model);if(!this._generationConfig.apiKey&&previousApiKey){this._generationConfig.apiKey=previousApiKey;if(previousApiKeySource){this.generationConfigSources["apiKey"]=_ModelsConfig.deepClone(previousApiKeySource)}}this.activeRuntimeModelSnapshotId=void 0;const requiresRefresh=isAuthTypeChange?true:this.checkRequiresRefresh(previousModelId);if(this.onModelChange){await this.onModelChange(authType,requiresRefresh,options?.initializeIfNeeded)}}catch(error){this.rollbackToStateSnapshot(rollbackSnapshot);throw error}}buildRuntimeModelSnapshotId(authType,modelId){return buildRuntimeSnapshotId(authType,modelId)}extractRuntimeModelSnapshotId(modelId){if(modelId.startsWith(RUNTIME_SNAPSHOT_PREFIX)){if(this.runtimeModelSnapshots.has(modelId)){return modelId}return void 0}if(this.runtimeModelSnapshots.has(modelId)){return modelId}return void 0}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(settingsGenerationConfig){if(!settingsGenerationConfig){return}for(const field of MODEL_GENERATION_CONFIG_FIELDS){if(!(field in this._generationConfig)&&field in settingsGenerationConfig){this._generationConfig[field]=settingsGenerationConfig[field];this.generationConfigSources[field]={kind:"settings",detail:`model.generationConfig.${field}`}}}}updateCredentials(credentials,settingsGenerationConfig){if(credentials.apiKey||credentials.baseUrl||credentials.model){this.hasManualCredentials=true;this.currentRegistryBaseUrl=void 0;this.clearProviderSourcedConfig()}if(credentials.apiKey){this._generationConfig.apiKey=credentials.apiKey;this.generationConfigSources["apiKey"]={kind:"programmatic",detail:"updateCredentials"}}if(credentials.baseUrl){this._generationConfig.baseUrl=credentials.baseUrl;this.generationConfigSources["baseUrl"]={kind:"programmatic",detail:"updateCredentials"}}if(credentials.model){this._generationConfig.model=credentials.model;this.generationConfigSources["model"]={kind:"programmatic",detail:"updateCredentials"}}this.strictModelProviderSelection=false;this._generationConfig.apiKeyEnvKey=void 0;if(settingsGenerationConfig){this.mergeSettingsGenerationConfig(settingsGenerationConfig)}this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){const currentAuthType=this.currentAuthType;const{model,apiKey,baseUrl}=this._generationConfig;if(!model||!currentAuthType||!apiKey||!baseUrl){return}if(this.modelRegistry.hasModel(currentAuthType,model,baseUrl)){return}if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){const snapshot=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);snapshot.apiKey=apiKey;snapshot.baseUrl=baseUrl;snapshot.modelId=model;const newSnapshotId=this.buildRuntimeModelSnapshotId(snapshot.authType,snapshot.modelId);if(newSnapshotId!==snapshot.id){this.runtimeModelSnapshots.delete(snapshot.id);snapshot.id=newSnapshotId;this.runtimeModelSnapshots.set(newSnapshotId,snapshot);this.activeRuntimeModelSnapshotId=newSnapshotId}snapshot.createdAt=Date.now()}else{this.detectAndCaptureRuntimeModel()}}clearProviderSourcedConfig(){for(const field of PROVIDER_SOURCED_FIELDS){const source=this.generationConfigSources[field];if(source?.kind==="modelProviders"){delete this._generationConfig[field];delete this.generationConfigSources[field]}}}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=false}applyResolvedModelDefaults(model){this.strictModelProviderSelection=true;this.currentRegistryBaseUrl=model.registryBaseUrl??null;this.hasManualCredentials=false;this._generationConfig.model=model.id;this.generationConfigSources["model"]={kind:"modelProviders",authType:model.authType,modelId:model.id,detail:"model.id"};this._generationConfig.apiKey=void 0;this._generationConfig.apiKeyEnvKey=void 0;if(model.envKey!==void 0){const apiKey=process2.env[model.envKey];if(apiKey){this._generationConfig.apiKey=apiKey;this.generationConfigSources["apiKey"]={kind:"env",envKey:model.envKey,via:{kind:"modelProviders",authType:model.authType,modelId:model.id,detail:"envKey"}}}else{debugLogger2.debug(`No API key found for model "${model.id}": process.env["${model.envKey}"] is ${apiKey===""?"empty string":"not set"}. Run /auth or set ${model.envKey} in your environment.`)}this._generationConfig.apiKeyEnvKey=model.envKey;this.generationConfigSources["apiKeyEnvKey"]={kind:"modelProviders",authType:model.authType,modelId:model.id,detail:"envKey"}}this._generationConfig.baseUrl=model.baseUrl;this.generationConfigSources["baseUrl"]={kind:"modelProviders",authType:model.authType,modelId:model.id,detail:"baseUrl"};const gc=model.generationConfig;for(const field of MODEL_GENERATION_CONFIG_FIELDS){this._generationConfig[field]=gc[field];this.generationConfigSources[field]={kind:"modelProviders",authType:model.authType,modelId:model.id,detail:`generationConfig.${field}`}}if(gc.contextWindowSize===void 0){this._generationConfig.contextWindowSize=tokenLimit(model.id,"input");this.generationConfigSources["contextWindowSize"]={kind:"computed",detail:"auto-detected from model"}}if(gc.modalities===void 0){this._generationConfig.modalities=defaultModalities(model.id);this.generationConfigSources["modalities"]={kind:"computed",detail:"auto-detected from model"}}}checkRequiresRefresh(previousModelId){const authType=this.currentAuthType;if(!authType){return true}const currentModel=this.modelRegistry.getModel(authType,this._generationConfig.model||"",this._generationConfig.baseUrl||void 0);const previousModel=this.modelRegistry.getModel(authType,previousModelId);if(!previousModel||!currentModel){return true}const criticalFieldsChanged=previousModel.envKey!==currentModel.envKey||previousModel.baseUrl!==currentModel.baseUrl;if(criticalFieldsChanged){return true}return false}syncAfterAuthRefresh(authType,modelId,providerBaseUrlOverride){const previousAuthType=this.currentAuthType;const providerBaseUrl=providerBaseUrlOverride??(previousAuthType===authType&&this.currentRegistryBaseUrl!==void 0?this.currentRegistryBaseUrl:this.generationConfigSources["baseUrl"]?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0);const wasRegistered=(authType==="openai"||authType==="openai-responses")&&previousAuthType===authType&&this.currentRegistryBaseUrl!==void 0&&modelId===this._generationConfig.model;const resolved=modelId?this.modelRegistry.getModel(authType,modelId,providerBaseUrl)??this.modelRegistry.getModel(authType,modelId):void 0;if(wasRegistered&&!resolved){throw new Error(`Model '${modelId}' is no longer configured for authType '${authType}'. Select an available model.`)}if(resolved?.imageOnly||resolved?.voiceOnly||resolved?.realtimeOnly){throw new Error(`${resolved.imageOnly?"Image":resolved.voiceOnly?"Voice":"Realtime"}-only model '${modelId}' cannot be used as the primary model`)}this.strictModelProviderSelection=false;this.currentAuthType=authType;if(resolved){const hasBeenApplied=this.generationConfigSources["baseUrl"]?.kind==="modelProviders";const isProviderChanged=hasBeenApplied&&(this._generationConfig.apiKeyEnvKey!==resolved.envKey||this._generationConfig.baseUrl!==resolved.baseUrl);const isUnchanged=previousAuthType===authType&&this._generationConfig.model===modelId&&!isProviderChanged;const savedApiKey=isUnchanged?this._generationConfig.apiKey:void 0;const savedApiKeySource=isUnchanged?this.generationConfigSources["apiKey"]?{...this.generationConfigSources["apiKey"]}:void 0:void 0;const baseUrlSource2=this.generationConfigSources["baseUrl"];const shouldPreserveResolvedBaseUrl=isUnchanged&&!!this._generationConfig.baseUrl&&(baseUrlSource2?.kind==="cli"||baseUrlSource2?.kind==="env"||baseUrlSource2?.kind==="settings");const savedBaseUrl=shouldPreserveResolvedBaseUrl?this._generationConfig.baseUrl:void 0;const savedBaseUrlSource=shouldPreserveResolvedBaseUrl?baseUrlSource2?{...baseUrlSource2}:void 0:void 0;this.applyResolvedModelDefaults(resolved);if(isUnchanged&&!this._generationConfig.apiKey&&savedApiKey){this._generationConfig.apiKey=savedApiKey;if(savedApiKeySource){this.generationConfigSources["apiKey"]=savedApiKeySource}}if(savedBaseUrl){this._generationConfig.baseUrl=savedBaseUrl;if(savedBaseUrlSource){this.generationConfigSources["baseUrl"]=savedBaseUrlSource}}this.strictModelProviderSelection=true;this.activeRuntimeModelSnapshotId=void 0;return}const apiKeySource=this.generationConfigSources["apiKey"];const baseUrlSource=this.generationConfigSources["baseUrl"];const hasExistingCredentials=this._generationConfig.apiKey&&apiKeySource?.kind!=="modelProviders"||this._generationConfig.baseUrl&&baseUrlSource?.kind!=="modelProviders";const isAuthTypeChange=previousAuthType!==authType;const shouldPreserveCredentials=!isAuthTypeChange&&(modelId===void 0||!this.modelRegistry.hasModel(authType,modelId))&&(this.hasManualCredentials||hasExistingCredentials);if(shouldPreserveCredentials){this.currentRegistryBaseUrl=void 0;if(modelId){this._generationConfig.model=modelId;if(!this.generationConfigSources["model"]){this.generationConfigSources["model"]={kind:"programmatic",detail:"auth refresh (preserved credentials)"}}}return}const defaultModel=this.modelRegistry.getDefaultModelForAuthType(authType);if(defaultModel){this.applyResolvedModelDefaults(defaultModel);this.activeRuntimeModelSnapshotId=void 0;return}if(modelId){this.currentRegistryBaseUrl=void 0;this._generationConfig.model=modelId;if(!this.generationConfigSources["model"]){this.generationConfigSources["model"]={kind:"programmatic",detail:"auth refresh (no default model)"}}}}setOnModelChange(callback){this.onModelChange=callback}detectAndCaptureRuntimeModel(){const{model:currentModel,apiKey,baseUrl,apiKeyEnvKey,...generationConfig}=this._generationConfig;const currentAuthType=this.currentAuthType;if(!currentModel||!currentAuthType){return void 0}if(this.modelRegistry.hasModel(currentAuthType,currentModel,baseUrl)){this.clearRuntimeModelSnapshotForAuthType(currentAuthType);return void 0}const hasValidCredentials=this._generationConfig.apiKey&&this._generationConfig.baseUrl;if(!hasValidCredentials){return void 0}const snapshotId=this.buildRuntimeModelSnapshotId(currentAuthType,currentModel);const snapshot={id:snapshotId,authType:currentAuthType,modelId:currentModel,apiKey,baseUrl,apiKeyEnvKey,generationConfig,sources:{...this.generationConfigSources},createdAt:Date.now()};this.runtimeModelSnapshots.set(snapshotId,snapshot);this.activeRuntimeModelSnapshotId=snapshotId;this.currentRegistryBaseUrl=void 0;this.cleanupOldRuntimeModelSnapshots();return snapshotId}getActiveRuntimeModelSnapshot(){if(!this.activeRuntimeModelSnapshotId){return void 0}return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(snapshotId,initializeIfNeeded){const runtimeModelSnapshot=this.runtimeModelSnapshots.get(snapshotId);if(!runtimeModelSnapshot){throw new Error(`Runtime model snapshot '${snapshotId}' not found`)}const rollbackSnapshot=this.createStateSnapshotForRollback();try{const isAuthTypeChange=runtimeModelSnapshot.authType!==this.currentAuthType;this.currentAuthType=runtimeModelSnapshot.authType;this.activeRuntimeModelSnapshotId=snapshotId;this.currentRegistryBaseUrl=void 0;this.strictModelProviderSelection=false;this.hasManualCredentials=true;this._generationConfig.model=runtimeModelSnapshot.modelId;this.generationConfigSources["model"]={kind:"programmatic",detail:"runtimeModelSwitch"};if(runtimeModelSnapshot.apiKey){this._generationConfig.apiKey=runtimeModelSnapshot.apiKey;this.generationConfigSources["apiKey"]=runtimeModelSnapshot.sources["apiKey"]||{kind:"programmatic",detail:"runtimeModelSwitch"}}if(runtimeModelSnapshot.baseUrl){this._generationConfig.baseUrl=runtimeModelSnapshot.baseUrl;this.generationConfigSources["baseUrl"]=runtimeModelSnapshot.sources["baseUrl"]||{kind:"programmatic",detail:"runtimeModelSwitch"}}if(runtimeModelSnapshot.apiKeyEnvKey){this._generationConfig.apiKeyEnvKey=runtimeModelSnapshot.apiKeyEnvKey}if(runtimeModelSnapshot.generationConfig){Object.assign(this._generationConfig,runtimeModelSnapshot.generationConfig)}const requiresRefresh=isAuthTypeChange;if(this.onModelChange){await this.onModelChange(runtimeModelSnapshot.authType,requiresRefresh,initializeIfNeeded)}}catch(error){this.rollbackToStateSnapshot(rollbackSnapshot);throw error}}getRuntimeModelOption(){const snapshot=this.getActiveRuntimeModelSnapshot();if(!snapshot){return void 0}return{id:snapshot.modelId,label:snapshot.modelId,authType:snapshot.authType,isVision:false,contextWindowSize:snapshot.generationConfig?.contextWindowSize,isRuntimeModel:true,runtimeSnapshotId:snapshot.id}}clearRuntimeModelSnapshotForAuthType(authType){for(const[id,snapshot]of this.runtimeModelSnapshots.entries()){if(snapshot.authType===authType){this.runtimeModelSnapshots.delete(id);if(this.activeRuntimeModelSnapshotId===id){this.activeRuntimeModelSnapshotId=void 0}}}}cleanupOldRuntimeModelSnapshots(){const snapshotsByAuthType=new Map;for(const snapshot of this.runtimeModelSnapshots.values()){const existing=snapshotsByAuthType.get(snapshot.authType);if(!existing||snapshot.createdAt>existing.createdAt){snapshotsByAuthType.set(snapshot.authType,snapshot)}}this.runtimeModelSnapshots.clear();for(const snapshot of snapshotsByAuthType.values()){this.runtimeModelSnapshots.set(snapshot.id,snapshot)}if(this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){this.activeRuntimeModelSnapshotId=void 0}}reloadModelProvidersConfig(modelProvidersConfig,providerProtocolConfig){this.modelRegistry.reloadModels(modelProvidersConfig,providerProtocolConfig)}getModelProvidersConfig(){return this.modelRegistry.getModelProvidersConfig()}getProviderProtocolConfig(){return this.modelRegistry.getProviderProtocolConfig()}};init_esbuild_shims();import{isDeepStrictEqual}from"node:util";init_esbuild_shims();import{createHash}from"node:crypto";init_esbuild_shims();var SERVICE_MODEL_ID=/(?:^|[-_/])(tts|asr|stt|realtime|audio|voice|embed|embedding|rerank)(?:$|[-_/])/i;function isServiceModelId(id){return SERVICE_MODEL_ID.test(id)}__name(isServiceModelId,"isServiceModelId");function resolveEnvKey(config,inputs){const protocol=inputs.protocol??config.protocol;const key=typeof config.envKey==="function"?config.envKey(protocol,inputs.baseUrl):config.envKey;return config.id==="custom-openai-compatible"&&inputs.advancedConfig?.purpose?`${key}_${inputs.advancedConfig.purpose.toUpperCase()}`:key}__name(resolveEnvKey,"resolveEnvKey");function resolveModelNamePrefix(config,baseUrl){return typeof config.modelNamePrefix==="function"?config.modelNamePrefix(baseUrl):config.modelNamePrefix}__name(resolveModelNamePrefix,"resolveModelNamePrefix");function resolveOwnsModel(config){if(config.ownsModel)return config.ownsModel;if(typeof config.envKey!=="string"||typeof config.modelNamePrefix!=="string"){return void 0}const envKey=config.envKey;const prefix=config.modelNamePrefix;if(!prefix)return model=>model.envKey===envKey;const namePrefix=`[${prefix}] `;return model=>model.envKey===envKey&&typeof model.name==="string"&&model.name.startsWith(namePrefix)}__name(resolveOwnsModel,"resolveOwnsModel");function buildGenerationConfig(spec,protocol){const parts={};let hasAny=false;if(spec.enableThinking){if(protocol==="openai-responses"){parts.reasoning={effort:"medium"}}else{parts.extra_body={enable_thinking:true}}hasAny=true}if(spec.thinkingMandatory){parts.thinkingMandatory=true;hasAny=true}if(spec.contextWindowSize){parts.contextWindowSize=spec.contextWindowSize;hasAny=true}if(spec.modalities&&Object.values(spec.modalities).some(Boolean)){parts.modalities=spec.modalities;hasAny=true}return hasAny?parts:void 0}__name(buildGenerationConfig,"buildGenerationConfig");function buildAdvancedGenerationConfig(advCfg,protocol){const cfg={};let hasAny=false;if(advCfg?.enableThinking){if(protocol==="openai-responses"){cfg.reasoning={effort:"medium"}}else{cfg.extra_body={enable_thinking:true}}hasAny=true}if(advCfg?.multimodal&&Object.values(advCfg.multimodal).some(Boolean)){cfg.modalities=advCfg.multimodal;hasAny=true}if(advCfg?.contextWindowSize&&advCfg.contextWindowSize>0){cfg.contextWindowSize=advCfg.contextWindowSize;hasAny=true}if(advCfg?.maxTokens&&advCfg.maxTokens>0){cfg.samplingParams={max_tokens:advCfg.maxTokens};hasAny=true}return hasAny?cfg:void 0}__name(buildAdvancedGenerationConfig,"buildAdvancedGenerationConfig");function specToModelConfig(spec,prefix,baseUrl,envKey,protocol){const genConfig=buildGenerationConfig(spec,protocol);return{id:spec.id,name:prefix?`[${prefix}] ${spec.id}`:spec.id,...spec.description?{description:spec.description}:{},...spec.capabilities?{capabilities:spec.capabilities}:{},baseUrl,envKey,...spec.supportsImageGeneration?{supportsImageGeneration:true}:{},...spec.imageOnly?{imageOnly:true}:{},...genConfig?{generationConfig:genConfig}:{}}}__name(specToModelConfig,"specToModelConfig");function applyProviderCustomHeaders(models,config){if(!config.customHeaders)return models;return models.map(model=>{const existing=model.generationConfig??{};return{...model,generationConfig:{...existing,customHeaders:{...config.customHeaders,...existing.customHeaders}}}})}__name(applyProviderCustomHeaders,"applyProviderCustomHeaders");function buildModelConfigs(config,inputs){const envKey=resolveEnvKey(config,inputs);const prefix=resolveModelNamePrefix(config,inputs.baseUrl);const protocol=resolveModelProtocol(inputs.protocol??config.protocol,inputs);let models;if(config.models&&!config.modelsEditable){models=config.models.map(spec=>specToModelConfig(spec,prefix,inputs.baseUrl,envKey,protocol))}else if(config.models&&config.modelsEditable){const specMap=new Map(config.models.map(s=>[s.id.toLowerCase(),s]));models=inputs.modelIds.map(id=>{const spec=specMap.get(id.toLowerCase());if(spec){return specToModelConfig({...spec,id},prefix,inputs.baseUrl,envKey,protocol)}const genConfig=buildAdvancedGenerationConfig(inputs.advancedConfig,protocol);return{id,name:prefix?`[${prefix}] ${id}`:id,baseUrl:inputs.baseUrl,envKey,...genConfig?{generationConfig:genConfig}:{}}})}else{const advCfg=inputs.advancedConfig;const displayName=__name(id=>prefix?`[${prefix}] ${id}`:id,"displayName");models=inputs.modelIds.map(id=>{const genConfig=buildAdvancedGenerationConfig(advCfg,protocol);return{id,name:displayName(id),baseUrl:inputs.baseUrl,envKey,...advCfg?.purpose==="image"?{supportsImageGeneration:true,imageOnly:true}:advCfg?.purpose==="voice"?{voiceOnly:true}:{},...genConfig?{generationConfig:genConfig}:{}}})}return applyProviderCustomHeaders(models,config)}__name(buildModelConfigs,"buildModelConfigs");function resolveMetadataKey(config){if(!config.models)return void 0;if(config.id.includes(".")){throw new Error(`Provider id must not contain '.' (would corrupt providerMetadata.${config.id} dotted writes): ${config.id}`)}return config.id}__name(resolveMetadataKey,"resolveMetadataKey");var PROVIDER_METADATA_NS="providerMetadata";function resolveProviderState(config,baseUrl,models){const key=resolveMetadataKey(config);if(key){return{[`${PROVIDER_METADATA_NS}.${key}`]:{version:computeModelListVersion(models),baseUrl}}}return void 0}__name(resolveProviderState,"resolveProviderState");function retireProviderState(config){const key=resolveMetadataKey(config);return key?{[`${PROVIDER_METADATA_NS}.${key}`]:{version:void 0}}:void 0}__name(retireProviderState,"retireProviderState");function buildInstallPlan(config,inputs,existingModels=[],selection){const inputProtocol=inputs.protocol??config.protocol;const protocol=resolveModelProtocol(inputProtocol,inputs);const isOpenAI=protocol==="openai"||protocol==="openai-responses";const savedProtocol=isOpenAI?"openai":protocol;const wireApi=inputs.wireApi??(inputProtocol==="openai-responses"?"responses":void 0);if(inputProtocol==="openai-responses"){inputs={...inputs,protocol:savedProtocol,wireApi}}let envKey=resolveEnvKey(config,inputs);const providerOwns=resolveOwnsModel(config);const builtModels=inputs.prebuiltModels??buildModelConfigs(config,inputs);const preserveSavedApis=isOpenAI&&!config.protocolOptions&&wireApi===void 0;let models=wireApi?builtModels.map(model=>model.wireApi===void 0?{...model,wireApi}:model):builtModels;if(preserveSavedApis&&existingModels.length){const responsesModels=inputs.prebuiltModels??buildModelConfigs(config,{...inputs,wireApi:"responses"});models=builtModels.flatMap((model,index)=>{if(model.wireApi!==void 0)return[model];const saved=existingModels.filter(entry=>providerOwns?.(entry)&&entry.id===model.id&&entry.baseUrl===model.baseUrl&&tryResolveModelProtocol(savedProtocol,entry)!==void 0);if(!saved.length)return[model];const seen=new Set;return saved.flatMap(entry=>{const route=resolveModelProtocol(savedProtocol,entry);if(seen.has(route))return[];seen.add(route);return[{...route==="openai-responses"?responsesModels[index]:model,...entry.wireApi!==void 0?{wireApi:entry.wireApi}:{}}]})})}const providerState=resolveProviderState(config,inputs.baseUrl,models);if(config.id==="custom-openai-compatible"&&existingModels?.some(entry=>providerOwns?.(entry)&&(entry.imageOnly||entry.voiceOnly||entry.realtimeOnly)&&models.some(model=>model.id===entry.id)&&typeof entry.baseUrl==="string"&&entry.baseUrl!==inputs.baseUrl&&resolveEnvKey(config,{...inputs,baseUrl:entry.baseUrl})===envKey)){throw new ProviderInstallError("A service model already uses this credential endpoint. Reconnect using its exact saved base URL.","modelPurpose",protocol)}if(existingModels?.length&&!inputs.advancedConfig?.purpose){models=models.map(model=>{const existing=existingModels.find(entry=>(providerOwns?.(entry)||config.mergeModelsByIdentity)&&entry.id===model.id&&entry.baseUrl===model.baseUrl&&tryResolveModelProtocol(savedProtocol,entry)===resolveModelProtocol(savedProtocol,model));if(!existing)return model;const preservedGeneration={...existing.generationConfig};const advanced=inputs.advancedConfig;if(!config.models&&advanced){if(advanced.replaceExisting){delete preservedGeneration.contextWindowSize;if(preservedGeneration.samplingParams){preservedGeneration.samplingParams={...preservedGeneration.samplingParams};delete preservedGeneration.samplingParams.max_tokens;if(!Object.keys(preservedGeneration.samplingParams).length)delete preservedGeneration.samplingParams}}if(advanced.replaceExisting||advanced.multimodal!==void 0)delete preservedGeneration.modalities;if(advanced.replaceExisting||advanced.enableThinking!==void 0){if(preservedGeneration.extra_body){preservedGeneration.extra_body={...preservedGeneration.extra_body};delete preservedGeneration.extra_body["enable_thinking"];if(!Object.keys(preservedGeneration.extra_body).length)delete preservedGeneration.extra_body}if(protocol==="openai-responses")delete preservedGeneration.reasoning}}const generationConfig=Object.keys(preservedGeneration).length||model.generationConfig?{...preservedGeneration,...model.generationConfig,...preservedGeneration.extra_body||model.generationConfig?.extra_body?{extra_body:{...preservedGeneration.extra_body,...model.generationConfig?.extra_body}}:{},...preservedGeneration.contextWindowSize!==void 0&&inputs.advancedConfig?.contextWindowSize===void 0?{contextWindowSize:preservedGeneration.contextWindowSize}:{},...preservedGeneration.samplingParams||model.generationConfig?.samplingParams?{samplingParams:{...preservedGeneration.samplingParams,...model.generationConfig?.samplingParams}}:{},...preservedGeneration.customHeaders||model.generationConfig?.customHeaders?{customHeaders:{...preservedGeneration.customHeaders,...model.generationConfig?.customHeaders}}:{}}:void 0;return{...existing,...model,name:existing?.name??model.name,generationConfig,...existing?.supportsImageGeneration?{supportsImageGeneration:true}:{},...existing?.imageOnly?{imageOnly:true}:{},...existing?.voiceOnly?{voiceOnly:true}:{},...existing?.realtimeOnly?{realtimeOnly:true}:{},...existing.envKey?{envKey:existing.envKey}:{}}})}if(inputs.apiKey&&inputs.baseUrl){const hostOf=__name(url=>{try{return url?new URL(url).host:void 0}catch{return void 0}},"hostOf");const setupHost=hostOf(inputs.baseUrl);if(setupHost){let changed=false;const routed=models.map(model=>{if(!model.imageOnly&&!model.voiceOnly&&!model.realtimeOnly&&hostOf(model.baseUrl)===setupHost&&model.envKey!==envKey){changed=true;return{...model,envKey}}return model});if(changed)models=routed}}if(models.length>0){const conversation=models.filter(model=>!model.imageOnly&&!model.voiceOnly&&!model.realtimeOnly);const credentialModels=conversation.length?conversation:models;const keys=new Set(credentialModels.map(model=>model.envKey));if(keys.size>1&&inputs.apiKey){throw new Error("Reconnect models with different credential references separately to preserve their independent API keys.")}if(credentialModels[0]?.envKey)envKey=credentialModels[0].envKey}const ownsModel=config.mergeModelsByIdentity?void 0:resolveOwnsModel(config);for(const model of models){const modelProtocol=resolveModelProtocol(savedProtocol,model);if(model.voiceOnly&&modelProtocol!=="openai"){throw new ProviderInstallError("Voice transcription requires the OpenAI Chat Completions API.","modelPurpose",protocol)}}const selectedModels=preserveSavedApis&&selection?.id?models.filter(model=>!model.imageOnly&&!model.voiceOnly&&!model.realtimeOnly&&model.id===selection.id&&(!selection.baseUrl||model.baseUrl===selection.baseUrl)):[];const firstModel=selectedModels.find(model=>resolveModelProtocol(savedProtocol,model)===selection?.authType&&!isServiceModelId(model.id))??selectedModels.find(model=>resolveModelProtocol(savedProtocol,model)===selection?.authType)??selectedModels.find(model=>!isServiceModelId(model.id))??selectedModels[0]??models.find(model=>!model.imageOnly&&!model.voiceOnly&&!model.realtimeOnly&&!isServiceModelId(model.id))??models.find(model=>!model.imageOnly&&!model.voiceOnly&&!model.realtimeOnly);if(models.length===0){throw new Error(`No models configured for provider "${config.id}". Check model list or provider configuration.`)}const firstModelId=firstModel?.id;const modelSelection=firstModelId===void 0?void 0:{modelId:firstModelId,...firstModel?.baseUrl?{baseUrl:firstModel.baseUrl}:{}};return{providerId:config.id,authType:firstModel?resolveModelProtocol(savedProtocol,firstModel):savedProtocol,env:{[envKey]:inputs.apiKey},...modelSelection?{modelSelection}:{},modelProviders:[{authType:savedProtocol,models,mergeStrategy:"prepend-and-remove-owned",...ownsModel?{ownsModel}:{}}],providerState:models.every(model=>model.wireApi===void 0)&&protocol===config.protocol?providerState:retireProviderState(config)}}__name(buildInstallPlan,"buildInstallPlan");function computeModelListVersion(models){return createHash("sha256").update(JSON.stringify(models)).digest("hex")}__name(computeModelListVersion,"computeModelListVersion");var DEFAULT_BASE_URLS={["openai"]:"https://api.openai.com/v1",["openai-responses"]:"https://api.openai.com",["anthropic"]:"https://api.anthropic.com/v1",["gemini"]:"https://generativelanguage.googleapis.com"};function getDefaultBaseUrlForProtocol(protocol){if(protocol===void 0)return"";return DEFAULT_BASE_URLS[protocol]??""}__name(getDefaultBaseUrlForProtocol,"getDefaultBaseUrlForProtocol");function resolveBaseUrl(config,selectedBaseUrl){if(typeof config.baseUrl==="string"){return config.baseUrl}if(Array.isArray(config.baseUrl)){const normalizedSelectedBaseUrl=normalizeBaseUrlForMatching(selectedBaseUrl);const match=config.baseUrl.find(opt=>normalizeBaseUrlForMatching(opt.url)===normalizedSelectedBaseUrl);if(match)return match.url;return config.baseUrl[0]?.url??selectedBaseUrl??""}return selectedBaseUrl??""}__name(resolveBaseUrl,"resolveBaseUrl");function normalizeBaseUrlForMatching(baseUrl){if(baseUrl===void 0)return"";let end=baseUrl.length;while(end>0&&baseUrl.charCodeAt(end-1)===47){end--}return end===baseUrl.length?baseUrl:baseUrl.slice(0,end)}__name(normalizeBaseUrlForMatching,"normalizeBaseUrlForMatching");function getDefaultModelIds(config){return config.models?.map(s=>s.id)??[]}__name(getDefaultModelIds,"getDefaultModelIds");function isProviderModelConfig(value){return typeof value==="object"&&value!==null&&typeof value.id==="string"}__name(isProviderModelConfig,"isProviderModelConfig");function getModelsForProviderProtocol(modelProviders,protocol,providerProtocol){const canonicalProtocol=protocol==="openai-responses"?"openai":protocol;const result=[];for(const[providerId,raw]of Object.entries(modelProviders??{})){if(!Array.isArray(raw))continue;for(const model of raw){if(!isProviderModelConfig(model))continue;const effective=tryResolveModelProtocol(providerId,model,providerProtocol);if(effective!==canonicalProtocol&&!(canonicalProtocol==="openai"&&effective==="openai-responses"))continue;result.push(effective==="openai-responses"?{...model,wireApi:"responses"}:canonicalProtocol==="openai"&&providerId!==canonicalProtocol?{...model,wireApi:"chat-completions"}:model)}}return result}__name(getModelsForProviderProtocol,"getModelsForProviderProtocol");function findExistingProviderModels(config,modelProviders,mapping,selection){const ownsModel=resolveOwnsModel(config);if(!ownsModel||!modelProviders)return void 0;const protocols=config.protocolOptions?.length?config.protocolOptions:[config.protocol];for(const providerProtocol of protocols){const models=getModelsForProviderProtocol(modelProviders,providerProtocol,mapping).filter(ownsModel);if(!models.length)continue;const selectedModels=selection?.id?models.filter(model=>model.id===selection.id&&(!selection.baseUrl||model.baseUrl===selection.baseUrl)):[];const selected=selectedModels.find(model=>resolveModelProtocol(providerProtocol,model)===selection?.authType)??selectedModels[0]??models[0];const protocol=resolveModelProtocol(providerProtocol,selected);return{protocol,models:models.filter(model=>resolveModelProtocol(providerProtocol,model)===protocol)}}return void 0}__name(findExistingProviderModels,"findExistingProviderModels");function shouldShowStep(config,step,protocol=config.protocol){switch(step){case"protocol":return Array.isArray(config.protocolOptions)&&config.protocolOptions.length>1;case"wireApi":return Boolean(config.protocolOptions?.length)&&(protocol==="openai"||protocol==="openai-responses");case"baseUrl":return config.baseUrl===void 0||Array.isArray(config.baseUrl);case"apiKey":return true;case"models":return!config.models||config.modelsEditable===true;case"advancedConfig":return config.showAdvancedConfig===true;default:return false}}__name(shouldShowStep,"shouldShowStep");function providerMatchesCredentials(config,baseUrl,envKey){let configEnvKey;if(typeof config.envKey==="string"){configEnvKey=config.envKey}else if(typeof config.envKey==="function"&&baseUrl){const protocols=config.protocolOptions?.length?config.protocolOptions:[config.protocol];for(const proto of protocols){try{const derived=config.envKey(proto,baseUrl);if(derived===envKey||config.id==="custom-openai-compatible"&&(envKey===`${derived}_IMAGE`||envKey===`${derived}_VOICE`)){configEnvKey=envKey;break}}catch(err){let safeHost;try{safeHost=new URL(baseUrl).hostname}catch{safeHost="[invalid]"}console.warn(`[providerMatchesCredentials] envKey(${proto}, ${safeHost}) threw (${err instanceof Error?err.constructor.name:typeof err}); skipping this protocol`)}}}if(configEnvKey!==envKey){return false}if(typeof config.baseUrl==="string"){return config.baseUrl===baseUrl}if(Array.isArray(config.baseUrl)){return config.baseUrl.some(opt=>opt.url===baseUrl)}if(config.baseUrl===void 0&&configEnvKey!==void 0){return Boolean(baseUrl)}return false}__name(providerMatchesCredentials,"providerMatchesCredentials");function buildProviderTemplate(config,baseUrl){const resolved=resolveBaseUrl(config,baseUrl);return buildModelConfigs(config,{baseUrl:resolved,apiKey:"",modelIds:getDefaultModelIds(config)})}__name(buildProviderTemplate,"buildProviderTemplate");var DENY_ENV_KEYS=new Set(["NODE_OPTIONS","NODE_PATH","LD_PRELOAD","LD_LIBRARY_PATH","DYLD_INSERT_LIBRARIES","DYLD_LIBRARY_PATH","PATH","HOME","TMPDIR","TMP","TEMP"]);function isSameModelIdentity(a,b){return a.id===b.id&&(a.baseUrl??"")===(b.baseUrl??"")}__name(isSameModelIdentity,"isSameModelIdentity");function applyModelProvidersPatch(existingModelProviders,patch,mapping){if(patch.authType==="openai"&&resolveProviderProtocol(patch.authType,mapping)==="openai-responses"){patch={...patch,models:patch.models.map(model=>({...model,wireApi:model.wireApi??"chat-completions"}))}}const existingModels=existingModelProviders[patch.authType]??[];let updatedModels=patch.models;if(patch.mergeStrategy==="append"){updatedModels=[...existingModels,...patch.models]}else{const ownsModel=patch.ownsModel;const preservedModels=existingModels.filter(model=>{if(ownsModel){return!ownsModel(model)||!patch.models.some(newModel=>resolveModelProtocol(patch.authType,newModel)===tryResolveModelProtocol(patch.authType,model,mapping))}return!patch.models.some(newModel=>isSameModelIdentity(newModel,model)&&resolveModelProtocol(patch.authType,newModel)===tryResolveModelProtocol(patch.authType,model,mapping))});updatedModels=patch.mergeStrategy==="replace-owned"?[...preservedModels,...patch.models]:[...patch.models,...preservedModels]}return{...existingModelProviders,[patch.authType]:updatedModels}}__name(applyModelProvidersPatch,"applyModelProvidersPatch");var ProviderInstallError=class extends Error{static{__name(this,"ProviderInstallError")}step;authType;constructor(message,step,authType,options){super(message,options);this.name="ProviderInstallError";this.step=step;this.authType=authType}};async function applyProviderInstallPlan(plan,options){const{settings,reloadModelProviders,syncAuthState,refreshAuth,doRefreshAuth=true}=options;const selectedAuthType=settings.getValue("security.auth.selectedType");const mapping=settings.getValue("providerProtocol");const serviceOnly=(plan.modelProviders??[]).flatMap(patch=>patch.models);const preserveSelection=serviceOnly.length>0&&serviceOnly.every(model=>model.imageOnly||model.voiceOnly||model.realtimeOnly);const previousEnvValues=new Map;const previousRuntimeProviders={...settings.getModelProviders()};const writeContext=settings.getModelProvidersForWrite?.();const writeMapping=writeContext?writeContext.providerProtocol:mapping;for(const[providerId,models]of Object.entries(writeContext?.modelProviders??{})){if(!Array.isArray(models))continue;if(providerId!=="openai-responses"&&resolveProviderProtocol(providerId,writeMapping)!=="openai-responses")continue;const overwritten=models.filter(existing=>plan.modelProviders?.some(patch=>patch.authType==="openai"&&patch.models.some(model=>isSameModelIdentity(existing,model)&&tryResolveModelProtocol(providerId,existing,writeMapping)===resolveModelProtocol(patch.authType,model))));if(overwritten.length&&(writeContext?.shadowedProviders.includes(providerId)||overwritten.some(model=>tryResolveModelProtocol(providerId,model,writeMapping)!==tryResolveModelProtocol(providerId,model,mapping)))){throw new ProviderInstallError("A higher-precedence settings scope overrides this released provider declaration. Reconfigure it in the owning scope without that override.","modelProviders",plan.authType)}}for(const patch of plan.modelProviders??[]){const existingModels=getModelsForProviderProtocol(previousRuntimeProviders,patch.authType,mapping);const ownBucketModels=previousRuntimeProviders[patch.authType]??[];const changesRole=existingModels.some(existing=>patch.models.some(model=>(isSameModelIdentity(existing,model)||existing.id===model.id&&patch.ownsModel?.(existing)&&(preserveSelection||patch.mergeStrategy!=="append"))&&(Boolean(existing.imageOnly)!==Boolean(model.imageOnly)||Boolean(existing.voiceOnly)!==Boolean(model.voiceOnly)||Boolean(existing.realtimeOnly)!==Boolean(model.realtimeOnly)||isImageGenerationCapable(existing)&&!isImageGenerationCapable(model))));const removesConversation=preserveSelection&&ownBucketModels.some(existing=>!existing.imageOnly&&!existing.voiceOnly&&!existing.realtimeOnly&&(patch.ownsModel?.(existing)??patch.models.some(model=>isSameModelIdentity(existing,model))));const removesService=!preserveSelection&&patch.mergeStrategy!=="append"&&ownBucketModels.some(existing=>(existing.imageOnly||existing.voiceOnly||existing.realtimeOnly)&&patch.ownsModel?.(existing)&&!patch.models.some(model=>model.id===existing.id));if(changesRole||removesConversation||removesService){throw new ProviderInstallError(removesConversation?"This install would remove existing conversation models. Include them in the provider selection, or add the service model with Custom Provider.":removesService?"This install would remove existing service models. Include them in the provider selection, or add the conversation model with Custom Provider.":"This install would replace a model configured for another purpose. Use a different model ID or endpoint.","modelPurpose",plan.authType)}}const voiceIds=new Set([...Object.values(previousRuntimeProviders).flatMap(models=>Array.isArray(models)?models:[]),...serviceOnly].filter(model=>model?.voiceOnly).map(model=>model.id));const selectedVoice=settings.getValue("voiceModel");if(typeof selectedVoice==="string"&&selectedVoice)voiceIds.add(selectedVoice);const changedVoiceIds=[...voiceIds].filter(id=>plan.modelProviders?.some(patch=>patch.models.some(model=>model.id===id)));if(changedVoiceIds.length){let prospective=previousRuntimeProviders;for(const patch of plan.modelProviders??[]){prospective=applyModelProvidersPatch(prospective,patch,mapping)}const configured=new ModelsConfig({modelProvidersConfig:Object.fromEntries(Object.entries(prospective).map(([providerId,models])=>[providerId,Array.isArray(models)?models.filter(model=>tryResolveModelProtocol(providerId,model,mapping)!==void 0):models])),providerProtocolConfig:mapping}).getAllConfiguredModels();if(changedVoiceIds.some(id=>configured.filter(entry=>entry.id===id).length>1)){throw new ProviderInstallError("A voice model with this ID is already configured at another endpoint. Edit that model or use a different model ID.","modelPurpose",plan.authType)}}const previousModelId=settings.getValue("model.name");const previousBaseUrl=settings.getValue("model.baseUrl");let currentStep="init";try{currentStep="backup";settings.backup?.();currentStep="env";const shadowedEnvKeys=[];for(const[key,value]of Object.entries(plan.env??{})){if(DENY_ENV_KEYS.has(key.toUpperCase())){throw new Error(`Install plan must not set reserved environment variable: ${key}`)}const previous=process.env[key];if(previous!==void 0&&previous!==""&&previous!==value){shadowedEnvKeys.push(key)}previousEnvValues.set(key,previous);settings.setValue(`env.${key}`,value);process.env[key]=value}if(shadowedEnvKeys.length>0){console.error(`[auth] Warning: ${shadowedEnvKeys.join(", ")} ${shadowedEnvKeys.length===1?"is":"are"} also set in your shell environment or .env file. The shell/file value will take priority on restart. To ensure your new key is used, update or remove the variable from your shell profile or .env file.`)}currentStep="modelProviders";let updatedModelProviders={...previousRuntimeProviders};for(const patch of plan.modelProviders??[]){updatedModelProviders=applyModelProvidersPatch(updatedModelProviders,preserveSelection?{...patch,mergeStrategy:"replace-owned",ownsModel:__name(existing=>(patch.ownsModel?.(existing)??false)||patch.models.some(model=>isSameModelIdentity(existing,model)),"ownsModel")}:patch,mapping);settings.setValue(`modelProviders.${patch.authType}`,updatedModelProviders[patch.authType]??[]);if(patch.authType!=="openai")continue;const ownProviders=settings.getModelProvidersForWrite?.().modelProviders??settings.getModelProviders();for(const[providerId,models]of Object.entries(ownProviders)){if(providerId===patch.authType||!Array.isArray(models))continue;if(providerId.includes("."))continue;if(providerId!=="openai-responses"&&resolveProviderProtocol(providerId,writeMapping)!=="openai-responses")continue;const remaining=models.filter(existing=>!patch.models.some(model=>isSameModelIdentity(existing,model)&&tryResolveModelProtocol(providerId,existing,writeMapping)===resolveModelProtocol(patch.authType,model)));if(remaining.length!==models.length)settings.setValue(`modelProviders.${providerId}`,remaining)}}const effectiveProviders=settings.getModelProviders();for(const patch of plan.modelProviders??[]){const effectiveModels=getModelsForProviderProtocol(effectiveProviders,patch.authType,mapping);const expectedModels=getModelsForProviderProtocol({[patch.authType]:patch.models},patch.authType);const ownProviders=settings.getModelProvidersForWrite?.().modelProviders;const installedModels=ownProviders?getModelsForProviderProtocol({[patch.authType]:ownProviders[patch.authType]??[]},patch.authType,mapping):expectedModels;if(expectedModels.some(model=>{const winner=effectiveModels.find(effective=>isSameModelIdentity(model,effective)&&resolveModelProtocol(patch.authType,model)===resolveModelProtocol(patch.authType,effective));const installed=installedModels.find(entry=>isSameModelIdentity(model,entry)&&resolveModelProtocol(patch.authType,model)===resolveModelProtocol(patch.authType,entry));return!winner||!installed||!isDeepStrictEqual(JSON.parse(JSON.stringify({...installed,wireApi:void 0})),JSON.parse(JSON.stringify({...winner,wireApi:void 0})))})){throw new ProviderInstallError("A higher-precedence settings scope overrides the installed models. Update the scope that owns this provider.","modelProviders",plan.authType)}}currentStep="authType";if(!preserveSelection){settings.setValue("security.auth.selectedType",plan.authType)}currentStep="legacyCredentials";if(plan.legacyCredentials?.apiKey!=null){settings.setValue("security.auth.apiKey",plan.legacyCredentials.apiKey)}if(plan.legacyCredentials?.baseUrl!=null){settings.setValue("security.auth.baseUrl",plan.legacyCredentials.baseUrl)}currentStep="modelSelection";let effectiveModelSelection=preserveSelection?void 0:plan.modelSelection;let routeResyncSelection;if(effectiveModelSelection?.modelId){const currentModelId=settings.getValue("model.name");const currentBaseUrl=settings.getValue("model.baseUrl");const planOffersCurrentModel=typeof currentModelId==="string"&¤tModelId.length>0&&(plan.modelProviders??[]).some(patch=>patch.models.some(model=>resolveModelProtocol(patch.authType,model)===plan.authType&&(currentBaseUrl===""||currentBaseUrl===void 0?model.id===currentModelId:isSameModelIdentity({id:currentModelId,baseUrl:currentBaseUrl},model))));if(planOffersCurrentModel){effectiveModelSelection=void 0;let previousAuthType;if((plan.authType==="openai"||plan.authType==="openai-responses")&&typeof selectedAuthType==="string"){try{previousAuthType=resolveModelSelectionAuthType(selectedAuthType,typeof previousModelId==="string"?previousModelId:void 0,previousRuntimeProviders,settings.getValue("providerProtocol"),typeof previousBaseUrl==="string"?previousBaseUrl:void 0)}catch{previousAuthType=void 0}}if(previousAuthType!==void 0&&previousAuthType!==plan.authType){routeResyncSelection={modelId:currentModelId,...currentBaseUrl?{baseUrl:currentBaseUrl}:{}}}}}if(effectiveModelSelection?.modelId){settings.setValue("model.name",effectiveModelSelection.modelId);if(effectiveModelSelection.baseUrl){settings.setValue("model.baseUrl",effectiveModelSelection.baseUrl)}else{settings.setValue("model.baseUrl","")}}currentStep="providerState";for(const[key,entries]of Object.entries(plan.providerState??{})){for(const[field,value]of Object.entries(entries)){settings.setValue(`${key}.${field}`,value)}}currentStep="persist";settings.persist();currentStep="reloadModelProviders";updatedModelProviders=settings.getModelProviders();reloadModelProviders?.(updatedModelProviders);const syncSelection=effectiveModelSelection?.modelId?effectiveModelSelection:routeResyncSelection;if(syncSelection){currentStep="syncAuthState";syncAuthState?.(plan.authType,syncSelection.modelId,syncSelection.baseUrl)}if(!preserveSelection&&doRefreshAuth&&refreshAuth){currentStep="refreshAuth";await refreshAuth(plan.authType)}currentStep="cleanupBackup";settings.cleanupBackup?.();return{updatedModelProviders}}catch(error){try{settings.restore?.()}catch(restoreErr){console.error("[applyProviderInstallPlan] settings.restore failed during rollback:",restoreErr)}try{for(const[key,prev]of previousEnvValues){if(prev===void 0){delete process.env[key]}else{process.env[key]=prev}}}catch(envErr){console.error("[applyProviderInstallPlan] env rollback failed:",envErr)}try{reloadModelProviders?.(previousRuntimeProviders)}catch(reloadErr){console.error("[applyProviderInstallPlan] reloadModelProviders failed during rollback:",reloadErr)}const errMsg=error instanceof Error?error.message:String(error);throw new ProviderInstallError(errMsg,currentStep,plan.authType,{cause:error instanceof Error?error:void 0})}}__name(applyProviderInstallPlan,"applyProviderInstallPlan");init_esbuild_shims();init_esbuild_shims();var HOSTCLUBE_ENV_KEY="HOSTCLUBE_API_KEY";var HOSTCLUBE_BASE_URL="https://ia.hostclube.com/v1";var hostclubeProvider={id:"hostclube",label:"HostClube",description:"Conecte com sua chave HostClube \u2014 os modelos da sua conta s\xE3o carregados automaticamente.",protocol:"openai",baseUrl:HOSTCLUBE_BASE_URL,envKey:HOSTCLUBE_ENV_KEY,models:[],modelsEditable:true,supportsModelDiscovery:true,modelNamePrefix:"HostClube",apiKeyPlaceholder:"sk-...",ownsModel:__name(model=>{if(model.envKey===HOSTCLUBE_ENV_KEY)return true;try{const host=new URL(model.baseUrl??"").hostname;return host==="ia.hostclube.com"||host.endsWith(".hostclube.com")}catch{return false}},"ownsModel"),documentationUrl:"https://hostclube.com",uiGroup:"third-party"};init_esbuild_shims();init_esbuild_shims();var QWENCLOUD_ENV_KEY="QWENCLOUD_API_KEY";var QWENCLOUD_CHINA_BASE_URL="https://maas.qianwenaiapi.com/compatible-mode/v1";var QWENCLOUD_GLOBAL_BASE_URL="https://maas.qwencloudapi.com/compatible-mode/v1";var QWENCLOUD_CHINA_API_KEY_URL="https://platform.qianwenai.com/docs/developer-guides/administration/api-keys";var QWENCLOUD_GLOBAL_API_KEY_URL="https://docs.qwencloud.com/developer-guides/administration/api-keys";var QWENCLOUD_MODELS=[{id:"qwen3.8-max",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","medium","xhigh"],defaultEffort:"xhigh",disableField:"reasoning_effort"}},modalities:{image:true,video:true}},{id:"qwen3.7-plus",contextWindowSize:1e6,enableThinking:true,capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},modalities:{image:true,video:true}},{id:"qwen3.8-flash",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","medium","xhigh"],defaultEffort:"xhigh",disableField:"reasoning_effort"}},modalities:{image:true,video:true}},{id:"deepseek-v4-pro-0813",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}}},{id:"deepseek-v4.1-flash",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}},modalities:{image:true}},{id:"kimi-k3",thinkingMandatory:true,contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"max",canDisable:false,disableField:"reasoning_effort"}},modalities:{image:true}},{id:"glm-5.3",contextWindowSize:1e6,enableThinking:true}];var qwencloudStandardProvider={id:"qwencloud-standard",label:"Standard API Key",description:"Pay-as-you-go \xB7 Connect with an existing platform API key",protocol:"openai",baseUrl:[{id:"cn-qianwenai",label:"China \u2014 \u5343\u95EEAI\u5E73\u53F0",url:QWENCLOUD_CHINA_BASE_URL,documentationUrl:QWENCLOUD_CHINA_API_KEY_URL,apiKeyUrl:QWENCLOUD_CHINA_API_KEY_URL},{id:"intl-qwencloud",label:"International \u2014 QwenCloud",url:QWENCLOUD_GLOBAL_BASE_URL,documentationUrl:QWENCLOUD_GLOBAL_API_KEY_URL,apiKeyUrl:QWENCLOUD_GLOBAL_API_KEY_URL}],envKey:QWENCLOUD_ENV_KEY,models:QWENCLOUD_MODELS,modelsEditable:true,supportsModelDiscovery:true,modelNamePrefix:"QwenCloud Standard",apiKeyPlaceholder:"sk-...",validateApiKey:__name(key=>key.startsWith("sk-")&&!key.startsWith("sk-sp-")?null:'Invalid API key. Pay-as-you-go keys start with "sk-" or "sk-ws-". Token Plan keys ("sk-sp-") need the Token Plan entry instead.',"validateApiKey"),webSearch:{backend:"dashscope"},ownsModel:__name(model=>model.envKey===QWENCLOUD_ENV_KEY&&typeof model.baseUrl==="string"&&(model.baseUrl===QWENCLOUD_CHINA_BASE_URL||model.baseUrl===QWENCLOUD_GLOBAL_BASE_URL),"ownsModel"),uiGroup:"qwencloud",uiLabels:{flowTitle:"QwenCloud",baseUrlStepTitle:"Platform"}};var QWENCLOUD_TOKEN_PLAN_ENV_KEY="QWENCLOUD_TOKEN_PLAN_API_KEY";var QWENCLOUD_TOKEN_PLAN_CHINA_BASE_URL="https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1";var QWENCLOUD_TOKEN_PLAN_GLOBAL_BASE_URL="https://token-plan.maas.qwencloudapi.com/compatible-mode/v1";var QWENCLOUD_TOKEN_PLAN_CHINA_DOC_URL="https://platform.qianwenai.com/docs/token-plan/overview";var QWENCLOUD_TOKEN_PLAN_GLOBAL_DOC_URL="https://docs.qwencloud.com/token-plan/overview";var QWENCLOUD_TOKEN_PLAN_MODELS=QWENCLOUD_MODELS.filter(model=>model.id!=="kimi-k3");var qwencloudTokenPlanProvider={id:"qwencloud-token-plan",label:"Token Plan",description:"Subscription with a monthly Credit quota \xB7 Dedicated endpoint (Personal and Team editions)",protocol:"openai",baseUrl:[{id:"cn-qianwenai",label:"China \u2014 \u5343\u95EEAI\u5E73\u53F0",url:QWENCLOUD_TOKEN_PLAN_CHINA_BASE_URL,documentationUrl:QWENCLOUD_TOKEN_PLAN_CHINA_DOC_URL,apiKeyUrl:QWENCLOUD_TOKEN_PLAN_CHINA_DOC_URL},{id:"intl-qwencloud",label:"International \u2014 QwenCloud",url:QWENCLOUD_TOKEN_PLAN_GLOBAL_BASE_URL,documentationUrl:QWENCLOUD_TOKEN_PLAN_GLOBAL_DOC_URL,apiKeyUrl:QWENCLOUD_TOKEN_PLAN_GLOBAL_DOC_URL}],envKey:QWENCLOUD_TOKEN_PLAN_ENV_KEY,models:QWENCLOUD_TOKEN_PLAN_MODELS,modelsEditable:true,supportsModelDiscovery:true,modelNamePrefix:__name(baseUrl=>baseUrl===QWENCLOUD_TOKEN_PLAN_GLOBAL_BASE_URL?"QwenCloud Token Plan for Global/Intl":"QwenCloud Token Plan","modelNamePrefix"),apiKeyPlaceholder:"sk-sp-...",validateApiKey:__name(key=>key.startsWith("sk-sp-")?null:'Invalid API key. Token Plan API keys start with "sk-sp-". Generate one from the Token Plan console, or use the Standard API Key entry for a pay-as-you-go key.',"validateApiKey"),ownsModel:__name(model=>model.envKey===QWENCLOUD_TOKEN_PLAN_ENV_KEY&&typeof model.baseUrl==="string"&&(model.baseUrl===QWENCLOUD_TOKEN_PLAN_CHINA_BASE_URL||model.baseUrl===QWENCLOUD_TOKEN_PLAN_GLOBAL_BASE_URL),"ownsModel"),webSearch:{backend:"dashscope"},uiGroup:"qwencloud",uiLabels:{flowTitle:"QwenCloud",baseUrlStepTitle:"Platform"}};init_esbuild_shims();var CODING_PLAN_ENV_KEY="BAILIAN_CODING_PLAN_API_KEY";var CODING_PLAN_CHINA_BASE_URL="https://coding.dashscope.aliyuncs.com/v1";var CODING_PLAN_GLOBAL_BASE_URL="https://coding-intl.dashscope.aliyuncs.com/v1";var MODELSTUDIO_MODELS=[{id:"qwen3.5-plus",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true,modalities:{image:true,video:true}},{id:"qwen3.6-plus",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},description:"Currently available to Pro subscribers only.",contextWindowSize:1e6,enableThinking:true,modalities:{image:true,video:true}},{id:"qwen3.7-plus",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true},{id:"glm-5",contextWindowSize:202752,enableThinking:true},{id:"kimi-k2.5",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:262144,enableThinking:true,modalities:{image:true,video:true}},{id:"MiniMax-M2.5",contextWindowSize:196608,enableThinking:true},{id:"qwen3-coder-plus",contextWindowSize:1e6},{id:"qwen3-coder-next",contextWindowSize:262144},{id:"qwen3-max-2026-01-23",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:262144,enableThinking:true},{id:"glm-4.7",contextWindowSize:202752,enableThinking:true}];var codingPlanProvider={id:"coding-plan",label:"Coding Plan",description:"For individual developers \xB7 Weekly quota included",protocol:"openai",baseUrl:[{id:"aliyun",label:"China (Beijing)",url:CODING_PLAN_CHINA_BASE_URL,documentationUrl:"https://help.aliyun.com/zh/model-studio/coding-plan"},{id:"alibabacloud",label:"Singapore (International)",url:CODING_PLAN_GLOBAL_BASE_URL,documentationUrl:"https://www.alibabacloud.com/help/en/model-studio/coding-plan"}],envKey:CODING_PLAN_ENV_KEY,models:MODELSTUDIO_MODELS,modelsEditable:true,supportsModelDiscovery:true,modelNamePrefix:__name(baseUrl=>baseUrl===CODING_PLAN_GLOBAL_BASE_URL?"ModelStudio Coding Plan for Global/Intl":"ModelStudio Coding Plan","modelNamePrefix"),apiKeyPlaceholder:"sk-sp-...",validateApiKey:__name(key=>!key.startsWith("sk-sp-")?'Invalid API key. Coding Plan API keys start with "sk-sp-". Please check.':null,"validateApiKey"),ownsModel:__name(model=>model.envKey===CODING_PLAN_ENV_KEY&&typeof model.baseUrl==="string"&&(model.baseUrl===CODING_PLAN_CHINA_BASE_URL||model.baseUrl===CODING_PLAN_GLOBAL_BASE_URL),"ownsModel"),uiGroup:"alibaba",uiLabels:{flowTitle:"Alibaba ModelStudio",baseUrlStepTitle:"Region"}};init_esbuild_shims();var TOKEN_PLAN_ENV_KEY="BAILIAN_TOKEN_PLAN_API_KEY";var TOKEN_PLAN_CHINA_BASE_URL="https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1";var TOKEN_PLAN_GLOBAL_BASE_URL="https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1";var TOKEN_PLAN_MODELS=[{id:"qwen3.7-plus",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true,modalities:{image:true,video:true}},{id:"qwen3.6-plus",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true,modalities:{image:true,video:true}},{id:"qwen3.7-max",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true},{id:"qwen3.8-max",capabilities:{reasoning:{thinking:true,efforts:["low","medium","high","xhigh","max"],defaultEffort:"xhigh",disableField:"reasoning_effort"}},contextWindowSize:1e6,modalities:{image:true,video:true}},{id:"qwen3.6-flash",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true},{id:"deepseek-v4-pro",capabilities:{reasoning:{thinking:true,efforts:["high","max"],defaultEffort:"high",disableField:"enable_thinking"}},contextWindowSize:1e6},{id:"deepseek-v4-flash-0731",capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}},contextWindowSize:1e6},{id:"deepseek-v4.1-flash",capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}},contextWindowSize:1e6,modalities:{image:true}},{id:"deepseek-v4.1-flash-1017",capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}},contextWindowSize:1e6,modalities:{image:true}},{id:"kimi-k2.7-code",capabilities:{reasoning:{thinking:true,toggleOnly:true,canDisable:false,disableField:"enable_thinking"}},contextWindowSize:262144,enableThinking:true,modalities:{image:true,video:true},thinkingMandatory:true},{id:"kimi-k2.6",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:262144,enableThinking:true},{id:"kimi-k2.5",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:262144,enableThinking:true,modalities:{image:true,video:true}},{id:"glm-5.3",capabilities:{reasoning:{thinking:true,toggleOnly:true,canDisable:false,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true,thinkingMandatory:true},{id:"glm-5.2",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true},{id:"glm-5.1",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:202752,enableThinking:true},{id:"glm-5",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:202752,enableThinking:true},{id:"MiniMax-M2.5",capabilities:{reasoning:{thinking:true,toggleOnly:true,canDisable:false,disableField:"enable_thinking"}},contextWindowSize:196608,enableThinking:true,thinkingMandatory:true},{id:"qwen3.8-flash",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","medium","high","xhigh","max"],defaultEffort:"xhigh",disableField:"reasoning_effort"}},modalities:{image:true,video:true}},{id:"deepseek-v4-pro-0813",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}}}];var tokenPlanProvider={id:"token-plan",label:"Token Plan",description:"Subscription with a monthly Credit quota \xB7 Dedicated endpoint (Personal and Team editions)",protocol:"openai",baseUrl:[{id:"cn-beijing",label:"China (Beijing)",url:TOKEN_PLAN_CHINA_BASE_URL,documentationUrl:"https://bailian.console.aliyun.com/cn-beijing?tab=doc#/doc/?type=model&url=3028856"},{id:"ap-southeast-1",label:"Singapore (International)",url:TOKEN_PLAN_GLOBAL_BASE_URL,documentationUrl:"https://modelstudio.console.alibabacloud.com/ap-southeast-1?tab=doc#/doc/?type=model"}],envKey:TOKEN_PLAN_ENV_KEY,models:TOKEN_PLAN_MODELS,modelsEditable:true,supportsModelDiscovery:true,modelNamePrefix:__name(baseUrl=>baseUrl===TOKEN_PLAN_GLOBAL_BASE_URL?"ModelStudio Token Plan for Global/Intl":"ModelStudio Token Plan","modelNamePrefix"),ownsModel:__name(model=>model.envKey===TOKEN_PLAN_ENV_KEY&&(typeof model.baseUrl==="string"&&(model.baseUrl===TOKEN_PLAN_CHINA_BASE_URL||model.baseUrl===TOKEN_PLAN_GLOBAL_BASE_URL)||typeof model.name==="string"&&model.name.startsWith("[ModelStudio Token Plan]")),"ownsModel"),webSearch:{backend:"dashscope"},uiGroup:"alibaba",uiLabels:{flowTitle:"Alibaba ModelStudio",baseUrlStepTitle:"Region"}};init_esbuild_shims();var alibabaStandardProvider={id:"alibabaStandard",label:"Standard API Key",description:"Connect with an existing ModelStudio API key",protocol:"openai",baseUrl:[{id:"cn-beijing",label:"China (Beijing)",url:"https://dashscope.aliyuncs.com/compatible-mode/v1",documentationUrl:"https://bailian.console.aliyun.com/cn-beijing?tab=api#/api"},{id:"sg-singapore",label:"Singapore",url:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",documentationUrl:"https://modelstudio.console.alibabacloud.com/ap-southeast-1?tab=api#/api/?type=model&url=2712195"},{id:"us-virginia",label:"US (Virginia)",url:"https://dashscope-us.aliyuncs.com/compatible-mode/v1",documentationUrl:"https://modelstudio.console.alibabacloud.com/us-east-1?tab=api#/api/?type=model&url=2712195"},{id:"cn-hongkong",label:"China (Hong Kong)",url:"https://cn-hongkong.dashscope.aliyuncs.com/compatible-mode/v1",documentationUrl:"https://modelstudio.console.alibabacloud.com/cn-hongkong?tab=api#/api/?type=model&url=2712195"}],envKey:"DASHSCOPE_API_KEY",models:[{id:"qwen3.6-plus",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true},{id:"qwen3.7-plus",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true},{id:"qwen3.7-max",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true},{id:"glm-5.3",capabilities:{reasoning:{thinking:true,toggleOnly:true,canDisable:false,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true,thinkingMandatory:true},{id:"glm-5.2",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:1e6,enableThinking:true},{id:"glm-5.1",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},contextWindowSize:202752,enableThinking:true},{id:"deepseek-v4-pro",capabilities:{reasoning:{thinking:true,efforts:["high","max"],defaultEffort:"high",disableField:"enable_thinking"}},contextWindowSize:1e6},{id:"deepseek-v4.1-flash",capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}},contextWindowSize:1e6,modalities:{image:true}},{id:"deepseek-v4.1-flash-1017",capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}},contextWindowSize:1e6,modalities:{image:true}},{id:"qwen3.8-max",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","medium","high","xhigh","max"],defaultEffort:"xhigh",disableField:"reasoning_effort"}},modalities:{image:true,video:true}},{id:"qwen3.8-max-0902",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","medium","high","xhigh","max"],defaultEffort:"xhigh",disableField:"reasoning_effort"}},modalities:{image:true,video:true}},{id:"qwen3.8-flash",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","medium","high","xhigh","max"],defaultEffort:"xhigh",disableField:"reasoning_effort"}},modalities:{image:true,video:true}},{id:"deepseek-v4-pro-0813",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}}},{id:"deepseek-v4-flash-0731",contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"enable_thinking"}}},{id:"kimi-k3",thinkingMandatory:true,contextWindowSize:1e6,capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"max",canDisable:false,disableField:"reasoning_effort"}},modalities:{image:true}},{id:"kimi-k2.7-code",thinkingMandatory:true,enableThinking:true,contextWindowSize:262144,capabilities:{reasoning:{thinking:true,toggleOnly:true,canDisable:false,disableField:"enable_thinking"}},modalities:{image:true,video:true}},{id:"kimi-k2.6",enableThinking:true,contextWindowSize:262144,capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"enable_thinking"}},modalities:{image:true,video:true}}],modelsEditable:true,supportsModelDiscovery:true,modelNamePrefix:"ModelStudio Standard",apiKeyPlaceholder:"sk-...",validateApiKey:__name(key=>key.startsWith("sk-")&&!key.startsWith("sk-sp-")?null:'Invalid API key. Pay-as-you-go keys start with "sk-" or "sk-ws-". Token Plan keys ("sk-sp-") need the Token Plan entry instead.',"validateApiKey"),webSearch:{backend:"dashscope"},uiGroup:"alibaba",uiLabels:{flowTitle:"Alibaba ModelStudio",baseUrlStepTitle:"Region"}};init_esbuild_shims();var OPENROUTER_ENV_KEY="OPENROUTER_API_KEY";var OPENROUTER_BASE_URL="https://openrouter.ai/api/v1";var openRouterProvider={id:"openrouter",label:"OpenRouter",description:"Connect with an OpenRouter API key (get one from openrouter.ai/keys)",protocol:"openai",baseUrl:OPENROUTER_BASE_URL,envKey:OPENROUTER_ENV_KEY,models:[{id:"z-ai/glm-4.5-air:free",contextWindowSize:128e3},{id:"openai/gpt-oss-120b:free",contextWindowSize:131072}],modelsEditable:true,modelNamePrefix:"OpenRouter",ownsModel:__name(model=>{if(model.envKey!==OPENROUTER_ENV_KEY)return false;try{const host=new URL(model.baseUrl??"").hostname;return host==="openrouter.ai"||host.endsWith(".openrouter.ai")}catch{return false}},"ownsModel"),customHeaders:{"HTTP-Referer":"https://github.com/QwenLM/qwen-code.git","X-OpenRouter-Title":"Qwen Code"},documentationUrl:"https://openrouter.ai/docs",uiGroup:"third-party"};init_esbuild_shims();var REQUESTY_ENV_KEY="REQUESTY_API_KEY";var REQUESTY_BASE_URL="https://router.requesty.ai/v1";var requestyProvider={id:"requesty",label:"Requesty",description:"Connect with a Requesty API key (get one from app.requesty.ai/api-keys)",protocol:"openai",baseUrl:REQUESTY_BASE_URL,envKey:REQUESTY_ENV_KEY,models:[{id:"openai/gpt-4o-mini",contextWindowSize:128e3},{id:"openai/gpt-4o",contextWindowSize:128e3}],modelsEditable:true,modelNamePrefix:"Requesty",ownsModel:__name(model=>{if(model.envKey!==REQUESTY_ENV_KEY)return false;try{const host=new URL(model.baseUrl??"").hostname;return host==="router.requesty.ai"||host.endsWith(".requesty.ai")}catch{return false}},"ownsModel"),customHeaders:{"HTTP-Referer":"https://github.com/QwenLM/qwen-code.git","X-Title":"Qwen Code"},documentationUrl:"https://docs.requesty.ai",uiGroup:"third-party"};init_esbuild_shims();var deepseekProvider={id:"deepseek",label:"DeepSeek API Key",description:"Quick setup for DeepSeek (deepseek-flash, deepseek-v4-pro)",protocol:"openai",baseUrl:"https://api.deepseek.com",envKey:"DEEPSEEK_API_KEY",models:[{id:"deepseek-v4-pro",contextWindowSize:1e6,capabilities:{reasoning:{profile:"deepseek-openai",thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"thinking"}}},{id:"deepseek-flash",capabilities:{reasoning:{profile:"deepseek-openai",thinking:true,efforts:["low","high","max"],defaultEffort:"high",disableField:"thinking"}},contextWindowSize:1e6}],modelsEditable:true,modelNamePrefix:"DeepSeek",documentationUrl:"https://api-docs.deepseek.com/zh-cn/",uiGroup:"third-party"};init_esbuild_shims();var GROK_ENV_KEY="XAI_API_KEY";var GROK_BASE_URL="https://api.x.ai/v1";var grokProvider={id:"grok",label:"Grok (xAI) API Key",description:"Quick setup for xAI Grok chat & code models",protocol:"openai",baseUrl:GROK_BASE_URL,envKey:GROK_ENV_KEY,models:[{id:"grok-4.5",contextWindowSize:5e5},{id:"grok-4.3",contextWindowSize:1e6},{id:"grok-4.20-0309-reasoning",contextWindowSize:1e6},{id:"grok-4.20-0309-non-reasoning",contextWindowSize:1e6},{id:"grok-4.20-multi-agent-0309",contextWindowSize:1e6},{id:"grok-build-0.1",contextWindowSize:262144}],modelsEditable:true,modelNamePrefix:"Grok",documentationUrl:"https://docs.x.ai/docs",uiGroup:"third-party"};init_esbuild_shims();var minimaxProvider={id:"minimax",label:"MiniMax API Key",description:"Quick setup for MiniMax models",protocol:"openai",baseUrl:[{id:"international",label:"International",url:"https://api.minimax.io/v1",documentationUrl:"https://www.minimax.io/platform"},{id:"china",label:"China",url:"https://api.minimaxi.com/v1",documentationUrl:"https://platform.minimaxi.com"}],envKey:"MINIMAX_API_KEY",models:[{id:"MiniMax-M3",contextWindowSize:1e6,modalities:{image:true,video:true}},{id:"MiniMax-M2.7",contextWindowSize:204800},{id:"MiniMax-M2.7-highspeed",contextWindowSize:204800},{id:"MiniMax-M2.5",contextWindowSize:196608},{id:"MiniMax-M2.5-highspeed",contextWindowSize:196608},{id:"image-01",imageOnly:true},{id:"image-01-live",imageOnly:true}],modelsEditable:true,modelNamePrefix:"MiniMax",uiGroup:"third-party"};init_esbuild_shims();var zaiProvider={id:"zai",label:"Z.AI API Key",description:"Quick setup for Z.AI models",protocol:"openai",baseUrl:[{id:"standard-api-key",label:"Standard API Key",url:"https://api.z.ai/api/paas/v4",documentationUrl:"https://docs.z.ai/"},{id:"coding-plan",label:"Coding Plan",url:"https://api.z.ai/api/coding/paas/v4",documentationUrl:"https://docs.z.ai/"}],envKey:"ZAI_API_KEY",models:[{id:"GLM-5.2",contextWindowSize:1e6,enableThinking:true},{id:"GLM-5.1",contextWindowSize:204800,enableThinking:true},{id:"GLM-5",contextWindowSize:204800},{id:"GLM-5-Turbo",contextWindowSize:204800}],modelsEditable:true,modelNamePrefix:"Z.AI",uiGroup:"third-party"};init_esbuild_shims();var moonshotProvider={id:"moonshot",label:"Kimi (Moonshot AI) API Key",description:"Quick setup for Kimi models",protocol:"openai",baseUrl:[{id:"international",label:"International",url:"https://api.moonshot.ai/v1",documentationUrl:"https://platform.kimi.ai/docs"},{id:"china",label:"China",url:"https://api.moonshot.cn/v1",documentationUrl:"https://platform.moonshot.cn/docs"}],envKey:"MOONSHOT_API_KEY",models:[{id:"kimi-k3",capabilities:{reasoning:{thinking:true,efforts:["low","high","max"],defaultEffort:"max",canDisable:false,disableField:"reasoning_effort"}},contextWindowSize:1e6,thinkingMandatory:true,modalities:{image:true,video:true}},{id:"kimi-k2.7-code",capabilities:{reasoning:{thinking:true,toggleOnly:true,canDisable:false,disableField:"thinking"}},contextWindowSize:262144,modalities:{image:true,video:true},thinkingMandatory:true},{id:"kimi-k2.7-code-highspeed",capabilities:{reasoning:{thinking:true,toggleOnly:true,canDisable:false,disableField:"thinking"}},contextWindowSize:262144,modalities:{image:true,video:true},thinkingMandatory:true},{id:"kimi-k2.6",capabilities:{reasoning:{thinking:true,toggleOnly:true,disableField:"thinking"}},contextWindowSize:262144,modalities:{image:true,video:true}}],modelsEditable:true,modelNamePrefix:"Kimi",uiGroup:"third-party"};init_esbuild_shims();var idealabProvider={id:"idealab",label:"Idealab API Key",description:"Alibaba internal LLM service (Qwen3.6-Plus-DogFooding, DeepSeek V4, Kimi K2.6)",protocol:"openai",baseUrl:"https://idealab.alibaba-inc.com/api/openai/v1",envKey:"IDEALAB_API_KEY",models:[{id:"Qwen3.6-Plus-DogFooding",contextWindowSize:1e6,enableThinking:true,modalities:{image:true,video:true}},{id:"bailian/deepseek-v4-pro",contextWindowSize:1e6,enableThinking:true},{id:"bailian/deepseek-v4-flash",contextWindowSize:1e6,enableThinking:true},{id:"bailian/kimi-k2.6",contextWindowSize:262144,enableThinking:true}],modelsEditable:true,modelNamePrefix:"Idealab",uiGroup:"third-party"};init_esbuild_shims();var modelscopeProvider={id:"modelscope",label:"ModelScope API Key",description:"Quick setup for ModelScope API Inference",protocol:"openai",baseUrl:"https://api-inference.modelscope.cn/v1",envKey:"MODELSCOPE_API_KEY",models:[{id:"deepseek-ai/DeepSeek-V4-Flash",contextWindowSize:1e6,enableThinking:true},{id:"Qwen/Qwen3.5-397B-A17B",contextWindowSize:1e6,enableThinking:true},{id:"ZhipuAI/GLM-5.1",contextWindowSize:1e6,enableThinking:true}],modelsEditable:true,modelNamePrefix:"ModelScope",documentationUrl:"https://modelscope.cn/docs/model-service/API-Inference/intro",uiGroup:"third-party"};init_esbuild_shims();import{createHash as createHash2}from"node:crypto";var CUSTOM_API_KEY_ENV_PREFIX="QWEN_CUSTOM_API_KEY_";function normalizeEnvSegment(value){const upper=value.trim().toUpperCase();let result="";let prevWasUnderscore=false;for(let i=0;i<upper.length;i++){const code=upper.charCodeAt(i);const isAlphaNum=code>=65&&code<=90||code>=48&&code<=57;if(isAlphaNum){result+=upper[i];prevWasUnderscore=false}else if(!prevWasUnderscore){result+="_";prevWasUnderscore=true}}let start=0;let end=result.length;while(start<end&&result.charCodeAt(start)===95)start++;while(end>start&&result.charCodeAt(end-1)===95)end--;return result.slice(start,end)}__name(normalizeEnvSegment,"normalizeEnvSegment");function stripTrailingSlashes(value){let end=value.length;while(end>0&&value.charCodeAt(end-1)===47)end--;return value.slice(0,end)}__name(stripTrailingSlashes,"stripTrailingSlashes");function generateCustomEnvKey(protocol,baseUrl){const canonicalBaseUrl=stripTrailingSlashes(baseUrl.trim());const suffix=createHash2("sha256").update(`${protocol}\0${canonicalBaseUrl}`).digest("hex").slice(0,12).toUpperCase();return`${CUSTOM_API_KEY_ENV_PREFIX}${normalizeEnvSegment(protocol)}_${normalizeEnvSegment(baseUrl)}_${suffix}`}__name(generateCustomEnvKey,"generateCustomEnvKey");var customProvider={id:"custom-openai-compatible",label:"Custom Provider",description:"Manually connect a local server, proxy, or unsupported provider",protocol:"openai",protocolOptions:["openai","anthropic","gemini"],baseUrl:void 0,envKey:generateCustomEnvKey,models:void 0,supportsModelDiscovery:true,modelNamePrefix:"",showAdvancedConfig:true,ownsModel:__name(model=>typeof model.envKey==="string"&&model.envKey.startsWith(CUSTOM_API_KEY_ENV_PREFIX),"ownsModel"),mergeModelsByIdentity:true,uiGroup:"custom"};var ALL_PROVIDERS=[hostclubeProvider,qwencloudTokenPlanProvider,qwencloudStandardProvider,codingPlanProvider,tokenPlanProvider,alibabaStandardProvider,deepseekProvider,grokProvider,minimaxProvider,zaiProvider,moonshotProvider,idealabProvider,modelscopeProvider,openRouterProvider,requestyProvider,customProvider];var QWENCLOUD_PROVIDERS=ALL_PROVIDERS.filter(p=>p.uiGroup==="qwencloud");var ALIBABA_PROVIDERS=ALL_PROVIDERS.filter(p=>p.uiGroup==="alibaba");var THIRD_PARTY_PROVIDERS=ALL_PROVIDERS.filter(p=>p.uiGroup==="third-party"&&p.id!==hostclubeProvider.id);function findProviderById(id){return ALL_PROVIDERS.find(p=>p.id===id)}__name(findProviderById,"findProviderById");function findProviderByCredentials(baseUrl,envKey){return ALL_PROVIDERS.find(p=>providerMatchesCredentials(p,baseUrl,envKey))}__name(findProviderByCredentials,"findProviderByCredentials");function getAllProviderBaseUrls(){return ALL_PROVIDERS.flatMap(p=>{if(typeof p.baseUrl==="string")return[p.baseUrl];if(Array.isArray(p.baseUrl))return p.baseUrl.map(o=>o.url);return[]})}__name(getAllProviderBaseUrls,"getAllProviderBaseUrls");init_esbuild_shims();var FLASH_MODELS=new Set(["deepseek-flash","deepseek-v4-flash","deepseek-v4.1-flash","deepseek-v4.1-flash-1017"]);var LEGACY_MODELS=new Set(["deepseek-v4-pro","deepseek-v4-pro-0813","deepseek-v4-flash-0731"]);function isDeepSeekV4Model(model){return/^deepseek-v4/i.test(model??"")}__name(isDeepSeekV4Model,"isDeepSeekV4Model");function isNewerFlashAlias(model){const normalized=model?.toLowerCase()??"";return FLASH_MODELS.has(normalized)&&normalized!=="deepseek-v4-flash"||normalized.startsWith("deepseek-v4.1-flash")}__name(isNewerFlashAlias,"isNewerFlashAlias");function hostnameOf(baseUrl){try{return new URL(baseUrl??"").hostname.toLowerCase()}catch{return void 0}}__name(hostnameOf,"hostnameOf");function isDeepSeekOfficialBaseUrl(baseUrl){const hostname=hostnameOf(baseUrl);return hostname!==void 0&&(hostname==="api.deepseek.com"||hostname.endsWith(".api.deepseek.com"))}__name(isDeepSeekOfficialBaseUrl,"isDeepSeekOfficialBaseUrl");function isDeepSeekMaasHostname(hostname){return hostname.endsWith(".maas.aliyuncs.com")||/^(?:dashscope(?:-intl|-us)?|cn-hongkong\.dashscope)\.aliyuncs\.com$/.test(hostname)}__name(isDeepSeekMaasHostname,"isDeepSeekMaasHostname");function isDeepSeekEstablishedHost(baseUrl,model){const hostname=hostnameOf(baseUrl);if(hostname===void 0)return false;const normalized=(model??"").toLowerCase();const known=FLASH_MODELS.has(normalized)||LEGACY_MODELS.has(normalized);if(isDeepSeekOfficialBaseUrl(baseUrl))return known||normalized==="deepseek-v4-flash-vision-exp";if(isDeepSeekMaasHostname(hostname))return known;return/^deepseek-v4\.1-flash(?:-1017)?$/.test(normalized)&&(hostname.endsWith(".alibaba-inc.com")||hostname.endsWith(".aliyun-inc.com")||hostname.endsWith(".alicloudapi.com"))}__name(isDeepSeekEstablishedHost,"isDeepSeekEstablishedHost");function getDeepSeekEndpoint(baseUrl,model){const hostname=hostnameOf(baseUrl);if(hostname===void 0)return void 0;if(isDeepSeekOfficialBaseUrl(baseUrl))return"official";if(isDeepSeekMaasHostname(hostname))return"maas";if(isDeepSeekV4Model(model))return"maas";return void 0}__name(getDeepSeekEndpoint,"getDeepSeekEndpoint");function getBuiltinDeepSeekReasoning(config){const model=config.model?.toLowerCase()??"";const endpoint=getDeepSeekEndpoint(config.baseUrl,model);if(config.authType!=="openai"||!endpoint||!isDeepSeekV4Model(model)&&!FLASH_MODELS.has(model))return void 0;return{profile:"deepseek-openai",thinking:true,efforts:endpoint==="maas"&&(model==="deepseek-v4-pro"||model==="deepseek-v4-flash")?["high","max"]:["low","high","max"],defaultEffort:"high",disableField:endpoint==="official"?"thinking":"enable_thinking",...config.thinkingMandatory?{canDisable:false}:{}}}__name(getBuiltinDeepSeekReasoning,"getBuiltinDeepSeekReasoning");function normalizeDeepSeekReasoningEffort(effort,model,baseUrl){const builtin=getBuiltinDeepSeekReasoning({authType:"openai",model,baseUrl});if(effort==="low")return builtin&&!builtin.toggleOnly&&builtin.efforts.includes("low")?"low":"high";if(effort==="medium")return"high";if(effort==="xhigh")return builtin&&getDeepSeekEndpoint(baseUrl,model)==="official"||isNewerFlashAlias(model)?"high":"max";return effort}__name(normalizeDeepSeekReasoningEffort,"normalizeDeepSeekReasoningEffort");function applyDeepSeekReasoningEffort(request,baseUrl,configuredEffort){const body=request;const model=typeof body["model"]==="string"?body["model"]:void 0;if(getDeepSeekEndpoint(baseUrl,model)!=="official"&&!getBuiltinDeepSeekReasoning({authType:"openai",model,baseUrl}))return request;const reasoning=body["reasoning"];const nestedEffort=reasoning?.["effort"];const effort=nestedEffort??configuredEffort;if(typeof effort!=="string"||!effort)return request;const next={...body};if(typeof next["reasoning_effort"]!=="string"||!next["reasoning_effort"])next["reasoning_effort"]=nestedEffort===void 0?effort:normalizeDeepSeekReasoningEffort(effort,model,baseUrl);const{effort:_effort,...rest}=reasoning??{};if(Object.keys(rest).length>0)next["reasoning"]=rest;else delete next["reasoning"];return next}__name(applyDeepSeekReasoningEffort,"applyDeepSeekReasoningEffort");function getDeepSeekReasoningState(config,resolved){const model=getRequestModel(config);if(!getBuiltinDeepSeekReasoning({...config,model})||!resolved||resolved.profile!==void 0&&resolved.profile!=="deepseek-openai"||resolved.toggleOnly||resolved.profile===void 0&&!isDeepSeekEstablishedHost(config.baseUrl,model))return void 0;const defaultEffort=resolved.defaultEffort;const configured=(config.reasoning||void 0)?.effort;const effort=configured??defaultEffort;const normalized=effort===void 0||resolved.efforts.includes(effort)?effort:normalizeDeepSeekReasoningEffort(effort,model,config.baseUrl);const body=applyDeepSeekReasoningEffort({model:config.model,...config.samplingParams,...config.extra_body},config.baseUrl,normalized===void 0?void 0:clampReasoningEffort(normalized,resolved.efforts));const disabled=resolved.canDisable!==false&&(config.reasoning===false||(resolved.disableField==="thinking"?body["thinking"]?.type==="disabled":body["enable_thinking"]===false)||body["reasoning_effort"]==="none");const wireEffort=config.reasoning!==false&&typeof body["reasoning_effort"]==="string"?body["reasoning_effort"]:defaultEffort;const effective=wireEffort===void 0||resolved.efforts.includes(wireEffort)?wireEffort:normalizeDeepSeekReasoningEffort(wireEffort,model,config.baseUrl);return{enabled:!disabled,effort:resolved.efforts.includes(effective)?effective:defaultEffort}}__name(getDeepSeekReasoningState,"getDeepSeekReasoningState");init_esbuild_shims();var DASHSCOPE_SOURCE_CONFIG_HEADER="X-DashScope-Source-Config";var TOKEN_PLAN_HOST_PREFIX="token-plan.";var SITE_CHANNELS=[["maas.qianwenaiapi.com","qianwenai-inner-agents"],["maas.qwencloudapi.com","qwencloud-inner-agents"]];var SITE_CHANNEL_BY_HOST=new Map(SITE_CHANNELS);var QWENCLOUD_MAAS_HOSTS=SITE_CHANNELS.map(([host])=>host);function buildDashScopeSourceConfig(baseUrl,runtimeChannel){if(!baseUrl)return void 0;let hostname;try{hostname=new URL(baseUrl).hostname.toLowerCase()}catch{return void 0}const isTokenPlan=hostname.startsWith(TOKEN_PLAN_HOST_PREFIX);const channel=SITE_CHANNEL_BY_HOST.get(isTokenPlan?hostname.slice(TOKEN_PLAN_HOST_PREFIX.length):hostname);if(!channel)return void 0;const t1=runtimeChannel==="desktop"?"qwen-code-desktop":"qwen-code-cli";return JSON.stringify({channel,source:"model",tags:isTokenPlan?{t1}:{t1,t2:"payg"}})}__name(buildDashScopeSourceConfig,"buildDashScopeSourceConfig");function withDashScopeSourceConfig(headers,baseUrl,runtimeChannel){const value=buildDashScopeSourceConfig(baseUrl,runtimeChannel);if(!value)return headers;const name=DASHSCOPE_SOURCE_CONFIG_HEADER.toLowerCase();const result=Object.fromEntries(Object.entries(headers).filter(([key])=>key.toLowerCase()!==name));result[DASHSCOPE_SOURCE_CONFIG_HEADER]=value;return result}__name(withDashScopeSourceConfig,"withDashScopeSourceConfig");function withoutDashScopeSourceConfig(headers){if(!headers)return void 0;const name=DASHSCOPE_SOURCE_CONFIG_HEADER.toLowerCase();const kept=Object.entries(headers).filter(([key])=>key.toLowerCase()!==name);return kept.length===Object.keys(headers).length?headers:Object.fromEntries(kept)}__name(withoutDashScopeSourceConfig,"withoutDashScopeSourceConfig");init_esbuild_shims();init_esbuild_shims();function isOpenRouterHostname(contentGeneratorConfig){const baseUrl=contentGeneratorConfig.baseUrl??"";if(!baseUrl)return false;try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="openrouter.ai"||hostname.endsWith(".openrouter.ai")}catch{return false}}__name(isOpenRouterHostname,"isOpenRouterHostname");init_esbuild_shims();var CLAUDE_MODEL_FAMILIES=["opus","sonnet","haiku","fable","mythos"];function parseClaudeModelVersion(model){const match=model.toLowerCase().match(new RegExp(`claude-(${CLAUDE_MODEL_FAMILIES.join("|")})-(\\d+)(?:[-.](\\d{1,2})(?!\\d))?`));if(!match){return null}return{family:match[1],major:Number.parseInt(match[2],10),minor:match[3]?Number.parseInt(match[3],10):0}}__name(parseClaudeModelVersion,"parseClaudeModelVersion");function anthropicSupportedEffortTiers(model){const tiers=["low","medium","high"];const parsed=parseClaudeModelVersion(model);if(!parsed){return tiers}const{family,major,minor}=parsed;const atLeast=__name((maj,min)=>major>maj||major===maj&&minor>=min,"atLeast");if(major>=5||family==="opus"&&atLeast(4,7)){tiers.push("xhigh")}if(major>=5||(family==="opus"||family==="sonnet")&&atLeast(4,6)){tiers.push("max")}return tiers}__name(anthropicSupportedEffortTiers,"anthropicSupportedEffortTiers");var REASONING_PROFILES=["openai-effort","openai-reasoning","deepseek-openai","dashscope-effort","dashscope-thinking","qwen-chat-template","anthropic-manual","anthropic-adaptive","deepseek-anthropic","gemini"];function invalidReasoning(route){throw new Error(`Model "${route.model}" capabilities.reasoning: invalid profile, efforts or defaultEffort`)}__name(invalidReasoning,"invalidReasoning");function validateReasoningDeclaration(route,declaration){if(declaration===void 0)return void 0;if(!declaration||typeof declaration!=="object"||Array.isArray(declaration))return invalidReasoning(route);const input=declaration;if(input.profile===void 0&&("thinking"in input||"disableField"in input))return parseModelReasoningCapabilities(input);if(!Object.keys(input).length||Object.keys(input).some(key=>!["profile","efforts","defaultEffort","thinking","toggleOnly","canDisable","disableField"].includes(key)))return invalidReasoning(route);if(input.profile!==void 0&&!REASONING_PROFILES.includes(input.profile)||input.thinking!==void 0&&input.thinking!==true||input.toggleOnly!==void 0&&typeof input.toggleOnly!=="boolean"||input.canDisable!==void 0&&input.canDisable!==false)return invalidReasoning(route);if(input.efforts!==void 0&&(!Array.isArray(input.efforts)||!input.efforts.length||input.efforts.some(tier=>!REASONING_EFFORT_TIERS.includes(tier))||new Set(input.efforts).size!==input.efforts.length))return invalidReasoning(route);if(input.defaultEffort!==void 0&&(!REASONING_EFFORT_TIERS.includes(input.defaultEffort)||input.efforts&&!input.efforts.includes(input.defaultEffort)))return invalidReasoning(route);return input}__name(validateReasoningDeclaration,"validateReasoningDeclaration");function resolveReasoningCapabilities(route,declaration){try{return validateReasoningCapabilities(route,declaration)}catch{return void 0}}__name(resolveReasoningCapabilities,"resolveReasoningCapabilities");function validateReasoningCapabilities(route,declaration){if(declaration===void 0){if(route.authType==="qwen-subscription"){return{thinking:true,efforts:["low","medium","xhigh"],defaultEffort:"medium",disableField:"enable_thinking"}}return getBuiltinDeepSeekReasoning(route)}const input=validateReasoningDeclaration(route,declaration);if(!input)return void 0;if(input.profile===void 0&&"thinking"in input)return parseModelReasoningCapabilities(input);const model=normalize(route.model);const provider=ALL_PROVIDERS.find(candidate=>typeof candidate.baseUrl==="string"?candidate.baseUrl===route.baseUrl:candidate.baseUrl?.some(option=>option.url===route.baseUrl));const known=(provider?.models?.find(candidate=>candidate.id===route.model)??provider?.models?.find(candidate=>candidate.id===model))?.capabilities?.reasoning;const inherited=parseModelReasoningCapabilities(known);if(!input.profile&&inherited?.toggleOnly){if(input.efforts||input.defaultEffort)return invalidReasoning(route);return parseModelReasoningCapabilities({...inherited,...input})}const gpt=getGptReasoningCapabilities(route.model);const claude=route.authType==="anthropic"?parseClaudeModelVersion(route.model):void 0;if(!inherited&&!gpt&&!claude&&!input.profile)return invalidReasoning(route);const auth=route.authType;let host="";try{host=new URL(route.baseUrl??"").hostname.toLowerCase()}catch{host=""}const dashscope=auth==="qwen-oauth"||/(^|\.)(dashscope(?:-intl|-us)?\.aliyuncs\.com|alibaba-inc\.com|aliyun-inc\.com|alicloudapi\.com)$/.test(host)||QWENCLOUD_MAAS_HOSTS.some(domain=>host===domain||host.endsWith(`.${domain}`))||/^token-plan\..+\.maas\.aliyuncs\.com$/.test(host);const profile=input.profile??(auth==="gemini"||auth==="vertex-ai"?"gemini":auth==="openai-responses"?"openai-reasoning":auth==="openai"&&isOpenRouterHostname(route)?"openai-reasoning":auth==="anthropic"?model.includes("deepseek")?"deepseek-anthropic":claude&&(claude.major>4||claude.major===4&&claude.minor>=6)?"anthropic-adaptive":"anthropic-manual":model.startsWith("qwen")?dashscope?inherited?.disableField==="reasoning_effort"?"dashscope-effort":"dashscope-thinking":"qwen-chat-template":inherited?.disableField==="thinking"?"deepseek-openai":"openai-effort");const protocol=profile==="gemini"?"gemini":profile.startsWith("anthropic-")||profile==="deepseek-anthropic"?"anthropic":"openai";if(auth==="openai-responses"&&profile!=="openai-reasoning"||auth&&protocol!==(auth==="vertex-ai"?"gemini":auth==="qwen-oauth"||auth==="qwen-subscription"||auth==="openai-responses"?"openai":auth))return invalidReasoning(route);const toggleOnly=profile==="dashscope-thinking"||profile==="qwen-chat-template";const disableField=!input.profile&&inherited?.disableField||(toggleOnly?"enable_thinking":profile==="openai-effort"||profile==="dashscope-effort"?"reasoning_effort":"thinking");const inheritedEfforts=inherited&&!inherited.toggleOnly?inherited.efforts:gpt?.efforts??(claude?anthropicSupportedEffortTiers(route.model):void 0);const efforts=input.efforts??inheritedEfforts;const inheritedDefault=inherited&&!inherited.toggleOnly?inherited.defaultEffort:gpt?.defaultEffort;const defaultEffort=input.defaultEffort??(inheritedDefault&&efforts?clampReasoningEffort(inheritedDefault,efforts):void 0);if(toggleOnly&&(input.efforts!==void 0||input.defaultEffort!==void 0)||!toggleOnly&&(!efforts||!defaultEffort)||profile==="gemini"&&efforts?.some(tier=>tier==="xhigh"||tier==="max"))return invalidReasoning(route);const result={...input,thinking:true,profile,toggleOnly,disableField,...toggleOnly?{}:{efforts,defaultEffort},...route.thinkingMandatory||inherited?.canDisable===false||gpt?.thinkingMandatory?{canDisable:false}:{}};const parsed=parseModelReasoningCapabilities(result);if(!parsed)return invalidReasoning(route);return{...parsed,profile,...gpt&&input.defaultEffort===void 0?{defaultEnabled:gpt.defaultEnabled}:{}}}__name(validateReasoningCapabilities,"validateReasoningCapabilities");function captureReasoningSnapshot(models){return Object.freeze(models.map(model=>Object.freeze({id:model.id,authType:model.authType,baseUrl:model.baseUrl,registryBaseUrl:model.registryBaseUrl,reasoning:model.capabilities?.reasoning&&typeof model.capabilities.reasoning==="object"?Object.freeze({...structuredClone(model.capabilities.reasoning),..."efforts"in model.capabilities.reasoning&&Array.isArray(model.capabilities.reasoning.efforts)?{efforts:Object.freeze([...model.capabilities.reasoning.efforts])}:{}}):model.capabilities?.reasoning})))}__name(captureReasoningSnapshot,"captureReasoningSnapshot");function resolveReasoningDeclaration(config,generation,model=generation.model){model=getRequestModel(generation,model);if(generation.reasoningSnapshot){const rows=generation.reasoningSnapshot.filter(row2=>row2.authType===generation.authType&&row2.id===model);const row=generation.reasoningRouteBaseUrl===null&&model===generation.model?rows.find(row2=>row2.registryBaseUrl===void 0):typeof generation.reasoningRouteBaseUrl==="string"&&model===generation.model?rows.find(row2=>row2.registryBaseUrl===generation.reasoningRouteBaseUrl):rows.find(row2=>row2.registryBaseUrl===generation.baseUrl)??rows.find(row2=>row2.registryBaseUrl===void 0&&row2.baseUrl===generation.baseUrl);return row?.reasoning}return generation.authType?config?.getResolvedModelConfig?.(generation.authType,model,generation.baseUrl)?.capabilities?.reasoning:void 0}__name(resolveReasoningDeclaration,"resolveReasoningDeclaration");function resolveReasoningForModel(config,generation,model=generation.model,strict=false){model=getRequestModel(generation,model);const declaration=resolveReasoningDeclaration(config,generation,model);return(strict?validateReasoningCapabilities:resolveReasoningCapabilities)({...generation,model,thinkingMandatory:model===generation.model?generation.thinkingMandatory:void 0},declaration)}__name(resolveReasoningForModel,"resolveReasoningForModel");function getEffectiveReasoning(generation,resolved){if(!resolved)return generation.reasoning;if(generation.reasoning===false&&resolved.canDisable!==false)return false;const selected=generation.reasoning||void 0;if(!selected&&resolved.defaultEnabled===false&&resolved.canDisable!==false)return false;if(resolved.toggleOnly)return selected??(resolved.profile?{}:void 0);const model=getRequestModel(generation);const knownDeepSeek=(resolved.profile==="deepseek-openai"||resolved.profile===void 0&&isDeepSeekEstablishedHost(generation.baseUrl,model))&&getBuiltinDeepSeekReasoning({...generation,model});let effort=selected?.effort??resolved.defaultEffort;if(effort&&knownDeepSeek&&!resolved.efforts.includes(effort))effort=normalizeDeepSeekReasoningEffort(effort,model,generation.baseUrl);return effort?{...selected,effort:(resolved.profile||knownDeepSeek)&&REASONING_EFFORT_TIERS.includes(effort)?clampReasoningEffort(effort,resolved.efforts):effort}:selected}__name(getEffectiveReasoning,"getEffectiveReasoning");init_esbuild_shims();init_esbuild_shims();var debugLogger3=createDebugLogger("OUTBOUND_CORRELATION");var PLACEHOLDERS=[{token:"${session_id}",resolve:__name(config=>config.getSessionId(),"resolve")}];var SESSION_ID_PLACEHOLDER_PATTERN=/\$(?:session_id|QWEN_CODE_SESSION_ID)(?!\w)|\$\{(?:session_id|QWEN_CODE_SESSION_ID)\}/gi;var warnedGateOff=new Set;function warnIfDynamicHeadersDisabled(customHeaders,config){try{const names=Object.entries(customHeaders??{}).filter(([,value])=>typeof value==="string"&&hasDynamicPlaceholder(value)).map(([name])=>name);if(names.length===0)return;if(config.getOutboundAllowDynamicHeaderValues())return;const key=names.slice().sort().join(",");if(warnedGateOff.has(key))return;warnedGateOff.add(key);console.warn(`customHeaders ${names.join(", ")} contain a runtime placeholder, but outboundCorrelation.allowDynamicHeaderValues is not enabled \u2014 the header(s) will not be sent. Set it to true in settings.json to allow the value to be filled in per request.`)}catch{}}__name(warnIfDynamicHeadersDisabled,"warnIfDynamicHeadersDisabled");function hasDynamicPlaceholder(value){return value.search(SESSION_ID_PLACEHOLDER_PATTERN)!==-1}__name(hasDynamicPlaceholder,"hasDynamicPlaceholder");function resolveDynamicHeaderValue(value,config){if(typeof value!=="string")return void 0;if(!hasDynamicPlaceholder(value))return value;try{if(!config.getOutboundAllowDynamicHeaderValues()){debugLogger3.warn(`Dropping a customHeaders value containing a runtime placeholder: outboundCorrelation.allowDynamicHeaderValues is not enabled.`);return void 0}let expanded=value.replace(SESSION_ID_PLACEHOLDER_PATTERN,"${session_id}");for(const{token,resolve}of PLACEHOLDERS){if(!expanded.includes(token))continue;const resolved=resolve(config);if(!resolved)return void 0;expanded=expanded.split(token).join(resolved)}return expanded}catch(error){debugLogger3.warn(`Unable to expand a customHeaders placeholder: ${error instanceof Error?error.message:String(error)}`);return void 0}}__name(resolveDynamicHeaderValue,"resolveDynamicHeaderValue");function applyDynamicHeaderValues(headers,config){const pending=[];headers.forEach((value,key)=>{if(hasDynamicPlaceholder(value))pending.push([key,value])});for(const[key,value]of pending){const resolved=resolveDynamicHeaderValue(value,config);if(resolved===void 0){headers.delete(key)}else{headers.set(key,resolved)}}}__name(applyDynamicHeaderValues,"applyDynamicHeaderValues");var debugLogger4=createDebugLogger("OUTBOUND_CORRELATION");var SESSION_ID_HEADER="session_id";var SESSION_ID_HEADER_HOSTS=["routify.alibaba-inc.com","routify-online.alibaba-inc.com","routify-pub.alibaba-inc.com"];function requestUrl(input){try{if(typeof input==="string")return new URL(input);if(input instanceof URL)return input;return new URL(input.url)}catch{return void 0}}__name(requestUrl,"requestUrl");function buildSessionIdHeaders(config,destination){try{const url=requestUrl(destination);if(url?.protocol!=="https:"||!SESSION_ID_HEADER_HOSTS.includes(url.hostname.toLowerCase())){return{}}const sessionId=config.getSessionId();return sessionId?{[SESSION_ID_HEADER]:sessionId}:{}}catch(error){debugLogger4.warn(`Unable to add ${SESSION_ID_HEADER} to outbound request: ${error instanceof Error?error.message:String(error)}`);return{}}}__name(buildSessionIdHeaders,"buildSessionIdHeaders");function wrapFetchWithSessionId(baseFetch,config,customHeaders){const fetchLike=baseFetch;const expandsHeaders=Object.values(customHeaders??{}).some(value=>typeof value==="string"&&hasDynamicPlaceholder(value));if(expandsHeaders)warnIfDynamicHeadersDisabled(customHeaders,config);const wrapped=__name(async(input,init)=>{const singleAttempt=retryContext.getStore()?.singleAttempt;const requestInit=singleAttempt?{...init,redirect:"error"}:init;const sessionHeaders=buildSessionIdHeaders(config,input);const sessionId=sessionHeaders[SESSION_ID_HEADER];if(!sessionId&&!expandsHeaders)return fetchLike(input,requestInit);const headers=new Headers(input instanceof Request?input.headers:void 0);new Headers(requestInit?.headers).forEach((value,key)=>headers.set(key,value));if(expandsHeaders)applyDynamicHeaderValues(headers,config);if(sessionId)headers.set(SESSION_ID_HEADER,sessionId);return fetchLike(input,{...requestInit,headers})},"wrapped");return wrapped}__name(wrapFetchWithSessionId,"wrapFetchWithSessionId");function buildSessionAwareFetch(runtimeFetch,config,customHeaders){const baseFetch=runtimeFetch??globalThis.fetch;return wrapFetchWithSessionId(baseFetch,config,customHeaders)}__name(buildSessionAwareFetch,"buildSessionAwareFetch");init_esbuild_shims();var ISOLATED_MODEL_REQUEST_FIELDS=new Set(["model","models","messages","input","instructions","prompt","conversation","previous_response_id","tools","tool_choice","parallel_tool_calls","functions","function_call","web_search_options","enable_search","search_options","plugins","n","background","stream","stream_options"]);function filterIsolatedModelOverrides(overrides){if(!overrides||!retryContext.getStore()?.singleAttempt)return overrides;return Object.fromEntries(Object.entries(overrides).filter(([key])=>!ISOLATED_MODEL_REQUEST_FIELDS.has(key)))}__name(filterIsolatedModelOverrides,"filterIsolatedModelOverrides");function ensureReasoningContentOnAssistantMessage(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content==="string"){return message}return{...assistant,reasoning_content:""}}__name(ensureReasoningContentOnAssistantMessage,"ensureReasoningContentOnAssistantMessage");function stripReasoningContent(message){if(!("reasoning_content"in message)){return[message]}const next={...message};const reasoningContent=next["reasoning_content"];delete next["reasoning_content"];if(message.role==="assistant"&&typeof reasoningContent==="string"&&reasoningContent.length>0&&Object.entries(next).every(([key,value])=>key==="role"||key==="name"||value===void 0||value===null||value===""||Array.isArray(value)&&value.length===0)){return[]}return[next]}__name(stripReasoningContent,"stripReasoningContent");export{DISABLED_REQUEST_TIMEOUT_MS,resolveRequestTimeout,DEFAULT_STREAM_IDLE_TIMEOUT_MS,QWEN_STREAM_IDLE_TIMEOUT_MS_ENV,MAX_STREAM_GUARD_TIMEOUT_MS,DEFAULT_STREAM_MAX_LIFETIME_MS,QWEN_STREAM_MAX_LIFETIME_MS_ENV,DEFAULT_MAX_RETRIES,DEFAULT_OPENAI_BASE_URL,DEFAULT_DASHSCOPE_BASE_URL,getDashscopeProxyBaseUrl,normalizeOpenAiWireBaseUrl,isOpenRouterHostname,getSystemPromptModel,getRequestModel,isImageGenerationCapable,RUNTIME_SNAPSHOT_PREFIX,buildRuntimeSnapshotId,stripRuntimeSnapshotPrefix,ModelsConfig,ProviderInstallError,applyProviderInstallPlan,isServiceModelId,resolveOwnsModel,resolveMetadataKey,PROVIDER_METADATA_NS,buildInstallPlan,computeModelListVersion,getDefaultBaseUrlForProtocol,resolveBaseUrl,getDefaultModelIds,getModelsForProviderProtocol,findExistingProviderModels,shouldShowStep,providerMatchesCredentials,buildProviderTemplate,hostclubeProvider,CUSTOM_API_KEY_ENV_PREFIX,customProvider,ALL_PROVIDERS,QWENCLOUD_PROVIDERS,ALIBABA_PROVIDERS,THIRD_PARTY_PROVIDERS,findProviderById,findProviderByCredentials,getAllProviderBaseUrls,isDeepSeekEstablishedHost,getBuiltinDeepSeekReasoning,applyDeepSeekReasoningEffort,getDeepSeekReasoningState,QWENCLOUD_MAAS_HOSTS,withDashScopeSourceConfig,withoutDashScopeSourceConfig,resolveReasoningCapabilities,validateReasoningCapabilities,captureReasoningSnapshot,resolveReasoningDeclaration,resolveReasoningForModel,getEffectiveReasoning,buildSessionAwareFetch,filterIsolatedModelOverrides,ensureReasoningContentOnAssistantMessage,stripReasoningContent,resolveProviderProtocol,resolveModelProtocol,tryResolveModelProtocol,validateModelProvidersConfig,resolveModelSelectionAuthType};
|
|
4
|
+
/**
|
|
5
|
+
* @license
|
|
6
|
+
* Copyright 2026 Qwen Team
|
|
7
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* @license
|
|
11
|
+
* Copyright 2025 Qwen
|
|
12
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* @license
|
|
16
|
+
* Copyright 2025 Qwen Team
|
|
17
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* @license
|
|
21
|
+
* Copyright 2026 MiraOS
|
|
22
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* @license
|
|
26
|
+
* Copyright 2026 HostClube
|
|
27
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
28
|
+
*/
|
|
29
|
+
/**
|
|
30
|
+
* @license
|
|
31
|
+
* Copyright 2026 Qwen Team
|
|
32
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
33
|
+
*
|
|
34
|
+
* Provider registry — imports all provider definitions and assembles the
|
|
35
|
+
* lookup tables used by the UI and CLI commands.
|
|
36
|
+
*/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-VOIC5ZW2.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-UGDAT4C4.js";import{runStartupRecoveryOnce}from"./chunk-YU67VCCO.js";import{isPermittedRedirect,isPrivateHost,resolveNetworkTarget}from"./chunk-IUVB7EIZ.js";import{isOmniDeliveryActive}from"./chunk-OXG4BLFF.js";import{requireEffectiveOmniUploadConfig}from"./chunk-GM6YF6IS.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-2W7KMUTJ.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-RQHIWFQL.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-BSFNCIBS.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-DLFX4M6C.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{detectRuntime,loadUndici}from"./chunk-E5XJBLSO.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-Q6UAOTP3.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{isAbortError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
|
|
3
|
+
import{DashScopeUploader}from"./chunk-RKDS7A4H.js";import{OmniDegradationCache,OmniTransportGuardError,assertWithinByteLimit,assertWithinDurationLimit,assertWithinTokenLimit,effectiveMaxUploadFileBytes,effectiveOmniStorageMaxTotalBytes,estimateRawResourceTokens,runFixedPolicies,runOmniGcOnce}from"./chunk-3YBZW4HP.js";import{MEDIA_DETECTOR_VERSION,MediaMemoryService}from"./chunk-UGDAT4C4.js";import{runStartupRecoveryOnce}from"./chunk-YU67VCCO.js";import{isPermittedRedirect,isPrivateHost,resolveNetworkTarget}from"./chunk-IUVB7EIZ.js";import{isOmniDeliveryActive}from"./chunk-PNFKCYZT.js";import{requireEffectiveOmniUploadConfig}from"./chunk-LMZZWPKA.js";import{DEFAULT_UPLOAD_CACHE_TTL_HOURS,OmniUploadCache}from"./chunk-2W7KMUTJ.js";import{OmniObjectStore,prepareOmniDownloadsDir}from"./chunk-RQHIWFQL.js";import{extensionForMime,hashFileSha256,recognizeMediaFile,sniffMediaType}from"./chunk-BSFNCIBS.js";import{isFfmpegAvailable,isFfprobeAvailable}from"./chunk-DLFX4M6C.js";import{ImageViewError,boundImageBuffer,sniffBoundableImageMime}from"./chunk-Z6AR5XE5.js";import{detectRuntime,loadUndici}from"./chunk-E5XJBLSO.js";import{TOOL_RESULT_MEDIA_REMEDY,clampInlineMediaPart,getMaxInlineMediaBytes}from"./chunk-Q6UAOTP3.js";import{OMNI_DISCLOSURE_TEXT_PREFIX,OMNI_OMISSION_TEXT_PREFIX,OMNI_RESOURCE_HANDLE_TEXT_PREFIX,OMNI_RESOURCE_PATH_TEXT_PREFIX,OMNI_TRANSCRIPT_TEXT_PREFIX,formatDisclosureText,formatOmissionText,formatResourceHandleText,formatTranscriptText,harnessPathAnnotationPart,isHarnessAnnotationPart,parseResourceHandleText,parseResourcePathText,splitAnnotationBody,unescapeAnnotationName}from"./chunk-SW54YEPK.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{isAbortError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import path4 from"node:path";import fs4 from"node:fs/promises";init_esbuild_shims();function buildSessionConditionNamespace(config,reservedOutputTokens){const session={reservedOutputTokens};const windowSize=config.getContentGeneratorConfig?.()?.contextWindowSize;const contextWindowTokens=typeof windowSize==="number"&&Number.isFinite(windowSize)&&windowSize>0?windowSize:void 0;if(contextWindowTokens!==void 0){session.contextWindowTokens=contextWindowTokens}let promptTokenCount;try{const count=config.getGeminiClient?.()?.getChat?.()?.getLastPromptTokenCount();if(typeof count==="number"&&Number.isFinite(count)&&count>=0){promptTokenCount=count}}catch{}if(promptTokenCount!==void 0){session.promptTokenCount=promptTokenCount}if(contextWindowTokens!==void 0&&promptTokenCount!==void 0){session.availableContextTokens=Math.max(0,contextWindowTokens-promptTokenCount-reservedOutputTokens)}return session}__name(buildSessionConditionNamespace,"buildSessionConditionNamespace");init_esbuild_shims();import{randomBytes}from"node:crypto";import{once}from"node:events";import{createWriteStream}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";var debugLogger=createDebugLogger("omni:download");var OmniDownloadError=class extends Error{static{__name(this,"OmniDownloadError")}constructor(message,options){super(message,options);this.name="OmniDownloadError"}};var RESOLVE_TIMEOUT_MS=3e4;var HEADER_TIMEOUT_MS=3e4;var IDLE_TIMEOUT_MS=6e4;var MAX_REDIRECTS=5;function parseHttpUrlRef(pathName){if(!/^https?:\/\//i.test(pathName))return null;try{return new URL(pathName)}catch{return null}}__name(parseHttpUrlRef,"parseHttpUrlRef");function scrubPathsFromMessage(message){return message.replace(/(?:[A-Za-z]:)?(?:[\\/][^\s'"`\\/]+){2,}[\\/]?/g,match=>path.basename(match))}__name(scrubPathsFromMessage,"scrubPathsFromMessage");function formatCauseChain(err){const parts=[];let cause=err instanceof Error?err.cause:void 0;for(let depth=0;cause!=null&&depth<4;depth++){const code=cause.code;const message=cause instanceof Error?cause.message:typeof cause==="string"?cause:void 0;if(typeof code==="string"&&message&&!message.includes(code)){parts.push(`${code}: ${message}`)}else if(message){parts.push(message)}else if(typeof code==="string"){parts.push(code)}cause=cause instanceof Error?cause.cause:void 0}return parts.length>0?scrubPathsFromMessage(parts.join("; ")):void 0}__name(formatCauseChain,"formatCauseChain");function detectConfiguredProxy(undici){for(const key of["https_proxy","HTTPS_PROXY","http_proxy","HTTP_PROXY","all_proxy","ALL_PROXY"]){if(process.env[key])return true}try{return undici.getGlobalDispatcher()instanceof undici.EnvHttpProxyAgent}catch{return false}}__name(detectConfiguredProxy,"detectConfiguredProxy");async function downloadMediaUrl(params){const{url,downloadsDir,maxBytes,signal,resolveTimeoutMs=RESOLVE_TIMEOUT_MS,headerTimeoutMs=HEADER_TIMEOUT_MS,idleTimeoutMs=IDLE_TIMEOUT_MS}=params;const resolveTarget=params.resolveTarget??(target=>resolveNetworkTarget(target,"public",signal));if(isPrivateHost(url)){throw new OmniDownloadError(`URL host is not publicly routable (refused for safety): ${new URL(url).hostname}`)}let parsed;try{parsed=new URL(url)}catch{throw new OmniDownloadError("URL media ref is not a valid URL (refused).")}if(parsed.protocol!=="https:"){throw new OmniDownloadError(`URL media must be https (refused for safety): ${parsed.protocol}//${parsed.hostname}`)}if(parsed.username||parsed.password){throw new OmniDownloadError(`URL media must not embed credentials (refused for safety): ${parsed.hostname}`)}const runtime=detectRuntime();if(runtime!=="node"){throw new OmniDownloadError(`URL media requires the Node runtime to verify the connection target (refused for safety on ${runtime}): use a local file path instead of a URL, or run under Node.`)}const undici=await loadUndici();const proxied=params.detectProxy?params.detectProxy():detectConfiguredProxy(undici);if(proxied){throw new OmniDownloadError(`URL media fetching is not supported behind a proxy yet (refused): the connection pinning that enforces SSRF protection cannot be applied through a proxy. Download the file manually and use a local path instead.`)}try{await prepareOmniDownloadsDir(downloadsDir)}catch(err){throw new OmniDownloadError(`Could not prepare the downloads directory for URL media: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}const partPath=path.join(downloadsDir,`${randomBytes(8).toString("hex")}.part`);let currentUrl=url;let dispatcher;try{for(let redirects=0;;redirects++){let target;const resolveAbort=new AbortController;const resolveTimer=setTimeout(()=>resolveAbort.abort(new Error("resolve timeout")),resolveTimeoutMs);try{const pending=resolveTarget(currentUrl);pending.catch(()=>{});target=await Promise.race([pending,new Promise((_,reject)=>{resolveAbort.signal.addEventListener("abort",()=>reject(resolveAbort.signal.reason),{once:true})})])}catch(err){if(signal?.aborted)throw err;if(resolveAbort.signal.aborted){throw new OmniDownloadError(`Download timed out resolving ${new URL(currentUrl).hostname} (${resolveTimeoutMs/1e3}s)`)}const text=err instanceof Error?err.message:String(err);const reason=/blocked address/i.test(text)?"resolved to a non-public address":/did not resolve/i.test(text)?"did not resolve":"could not be verified";throw new OmniDownloadError(`URL host ${reason} (refused for safety): ${new URL(currentUrl).hostname}`,{cause:err})}finally{clearTimeout(resolveTimer)}if(!target.lookup){throw new OmniDownloadError(`URL host cannot be safely bound to a verified address (refused for safety): ${new URL(currentUrl).hostname}`)}const fetchFn=params.fetchFn??undici.fetch;const previousDispatcher=dispatcher;dispatcher=new undici.Agent({connect:{lookup:target.lookup}});await previousDispatcher?.close().catch(()=>{});const headerAbort=new AbortController;const headerTimer=setTimeout(()=>headerAbort.abort(new Error("header timeout")),headerTimeoutMs);const combined=AbortSignal.any(signal?[signal,headerAbort.signal]:[headerAbort.signal]);let res;try{res=await fetchFn(currentUrl,{redirect:"manual",signal:combined,dispatcher})}catch(err){if(signal?.aborted)throw err;if(headerAbort.signal.aborted){throw new OmniDownloadError(`Download timed out waiting for response headers from ${new URL(currentUrl).hostname} (${headerTimeoutMs/1e3}s)`)}const detail=err instanceof Error?scrubPathsFromMessage(err.message):String(err);const causeDetail=formatCauseChain(err);throw new OmniDownloadError(`Download request failed for ${new URL(currentUrl).hostname}: ${detail}${causeDetail?` (${causeDetail})`:""}`,{cause:err})}finally{clearTimeout(headerTimer)}if(res.status>=300&&res.status<400){await res.body?.cancel().catch(()=>{});const location=res.headers.get("location");if(!location||redirects>=MAX_REDIRECTS){throw new OmniDownloadError(`Too many or invalid redirects downloading from ${new URL(currentUrl).hostname}`)}let redirectUrl;try{redirectUrl=new URL(location,currentUrl).toString()}catch{throw new OmniDownloadError(`Redirect with a malformed Location header from ${new URL(currentUrl).hostname}`)}if(!isPermittedRedirect(currentUrl,redirectUrl)){throw new OmniDownloadError(`Cross-origin redirect refused: ${new URL(currentUrl).hostname} \u2192 ${new URL(redirectUrl).hostname}`)}currentUrl=redirectUrl;continue}if(!res.ok){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download failed: HTTP ${res.status} from ${new URL(currentUrl).hostname}`)}const contentLength=Number(res.headers.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>maxBytes){await res.body?.cancel().catch(()=>{});throw new OmniDownloadError(`Download exceeds the omni media limit: Content-Length ${contentLength} > ${maxBytes} bytes.`)}if(!res.body){throw new OmniDownloadError("Download response had no body.")}let written=0;const idleAbort=new AbortController;let idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);const streamSignal=AbortSignal.any(signal?[signal,idleAbort.signal]:[idleAbort.signal]);try{const source=Readable.fromWeb(res.body,{signal:streamSignal});const counter=__name(async function*(src){for await(const chunk of src){clearTimeout(idleTimer);idleTimer=setTimeout(()=>idleAbort.abort(new Error("idle timeout")),idleTimeoutMs);written+=chunk.length;if(written>maxBytes){throw new OmniDownloadError(`Download exceeds the omni media limit: >${maxBytes} bytes received.`)}yield chunk}},"counter");const destination=createWriteStream(partPath,{mode:384});await once(destination,"open");await pipeline(source,counter,destination)}catch(err){if(signal?.aborted)throw err;if(err instanceof OmniDownloadError)throw err;if(idleAbort.signal.aborted){throw new OmniDownloadError(`Download stalled from ${new URL(currentUrl).hostname}: no data for ${idleTimeoutMs/1e3}s`)}throw new OmniDownloadError(`Download interrupted from ${new URL(currentUrl).hostname}: ${err instanceof Error?scrubPathsFromMessage(err.message):String(err)}`,{cause:err})}finally{clearTimeout(idleTimer)}debugLogger.debug(`downloaded ${written} bytes from ${new URL(currentUrl).hostname}`);return{partPath}}}catch(err){await fs.rm(partPath,{force:true});throw err}finally{await dispatcher?.close().catch(()=>{})}}__name(downloadMediaUrl,"downloadMediaUrl");init_esbuild_shims();import{randomBytes as randomBytes2}from"node:crypto";import fs2 from"node:fs/promises";import path2 from"node:path";var debugLogger2=createDebugLogger("omni:tool-result");var MAX_UPLOADS_PER_TOOL_RESULT=8;var MAX_UPLOAD_BYTES_PER_TOOL_RESULT=128*1024*1024;async function boundDeclinedInlinePart(part,bytes,signal){const inline=part.inlineData;if(!inline?.data)return part;const inlineByteCeiling=getMaxInlineMediaBytes();let boundedPart=part;if(sniffBoundableImageMime(bytes.subarray(0,12))){try{const view=await boundImageBuffer(bytes,`tool-result media (${inline.mimeType??"unknown"})`,signal,inlineByteCeiling);if(view){boundedPart={inlineData:{...inline,data:view.bytes.toString("base64"),mimeType:view.mimeType}}}}catch(error){if(!(error instanceof ImageViewError)){throw error}debugLogger2.debug(`tool-result media kept inline could not be bounded: ${error.message}`)}}return clampInlineMediaPart(boundedPart,inlineByteCeiling,TOOL_RESULT_MEDIA_REMEDY)}__name(boundDeclinedInlinePart,"boundDeclinedInlinePart");async function processToolResultOmniMedia(responseParts,config,signal){if(!isOmniDeliveryActive(config))return responseParts;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};let changed=false;let uploadsRemaining=MAX_UPLOADS_PER_TOOL_RESULT;let uploadBytesRemaining=MAX_UPLOAD_BYTES_PER_TOOL_RESULT;const keepInline=__name(async(part,bytes)=>{const kept=await boundDeclinedInlinePart(part,bytes,signal);if(kept!==part)changed=true;return[kept]},"keepInline");const convertPart=__name(async part=>{const inline=part.inlineData;if(!inline?.data||!inline.mimeType)return[part];const top=inline.mimeType.split("/")[0];if(top!=="image"&&top!=="audio"&&top!=="video")return[part];const bytes=Buffer.from(inline.data,"base64");const sniffed=sniffMediaType(bytes.subarray(0,4096));if(!sniffed)return keepInline(part,bytes);if(!modalities[sniffed.modality]){return keepInline(part,bytes)}if(uploadsRemaining<=0||bytes.length>uploadBytesRemaining){debugLogger2.debug(`tool-result media budget exhausted; keeping part inline (${bytes.length} bytes)`);return keepInline(part,bytes)}const store=new OmniObjectStore(config.storage.getQwenDir());let tempPath;const displayName=inline.displayName??`tool-media.${top}`;try{const stagingDir=await prepareOmniDownloadsDir(path2.join(store.getOmniRootDir(),"downloads"));tempPath=path2.join(stagingDir,`${randomBytes2(8).toString("hex")}.part`);await fs2.writeFile(tempPath,bytes,{mode:384});const delivery=await processMediaForOmniDelivery(tempPath,config,{expectedModality:sniffed.modality,signal,displayName,origin:"tool"});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);uploadsRemaining-=delivery.additionalMedia?.filter(e=>!e.omission).length??0;const handleParts=delivery.resourceId?[{text:formatResourceHandleText(displayName,delivery.resourceId)}]:[];if(delivery.omission){changed=true;return[...handleParts,{text:formatOmissionText(displayName,delivery.omission.reason)},...additionalParts,...transcriptParts]}if(!delivery.fileUri&&transcriptParts.length>0){changed=true;return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},...additionalParts,...transcriptParts]:[...handleParts,...additionalParts,...transcriptParts]}changed=true;uploadsRemaining--;uploadBytesRemaining-=bytes.length;const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};return delivery.disclosure?[...handleParts,{text:formatDisclosureText(displayName,delivery.disclosure)},fileDataPart,...additionalParts,...transcriptParts]:[...handleParts,fileDataPart,...additionalParts,...transcriptParts]}catch(err){if(signal.aborted)throw err;if(err instanceof OmniTransportGuardError){changed=true;return[...err.sessionResourceId?[{text:formatResourceHandleText(displayName,err.sessionResourceId)}]:[],{text:`[Tool media part withheld by the omni transport guard: ${err.message}]`}]}debugLogger2.debug(`tool-result media upload failed, keeping inline: ${err instanceof Error?err.message:String(err)}`);return keepInline(part,bytes)}finally{if(tempPath!==void 0){await fs2.rm(tempPath,{force:true}).catch(()=>{})}}},"convertPart");const result=[];for(const part of responseParts){const nested=part.functionResponse?.parts;if(Array.isArray(nested)&&nested.length>0){const convertedNested=[];let nestedChanged=false;for(const nestedPart of nested){const converted=await convertPart(nestedPart);if(converted.length!==1||converted[0]!==nestedPart){nestedChanged=true}convertedNested.push(...converted)}if(nestedChanged){result.push({...part,functionResponse:{...part.functionResponse,parts:convertedNested}});changed=true}else{result.push(part)}continue}result.push(...await convertPart(part))}return changed?result:responseParts}__name(processToolResultOmniMedia,"processToolResultOmniMedia");init_esbuild_shims();import fs3 from"node:fs/promises";import path3 from"node:path";var debugLogger3=createDebugLogger("omni:export");function textOfPart(part){if(typeof part==="string")return part;if(typeof part==="object"&&part!==null&&"text"in part){const text=part.text;return typeof text==="string"?text:void 0}return void 0}__name(textOfPart,"textOfPart");function functionResponseOfPart(part){if(typeof part!=="object"||part===null)return void 0;const response=part.functionResponse;if(typeof response!=="object"||response===null)return void 0;const{id,parts}=response;return{id,...Array.isArray(parts)?{parts}:{}}}__name(functionResponseOfPart,"functionResponseOfPart");function isThoughtPart(part){return typeof part==="object"&&part!==null&&part.thought===true}__name(isThoughtPart,"isThoughtPart");function functionCallOfPart(part){if(typeof part!=="object"||part===null)return void 0;const fc=part.functionCall;if(typeof fc!=="object"||fc===null)return void 0;const{id,name,args}=fc;if(typeof name!=="string")return void 0;const cleanArgs=typeof args==="object"&&args!==null?{...args}:void 0;return{...typeof id==="string"?{callId:id}:{},name,...cleanArgs?{args:cleanArgs}:{}}}__name(functionCallOfPart,"functionCallOfPart");function stripSystemReminders(text){return text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"")}__name(stripSystemReminders,"stripSystemReminders");function mediaFor(turn,name){let media=turn.media.get(name);if(!media){media={name,disclosures:[],transcripts:[]};turn.media.set(name,media)}return media}__name(mediaFor,"mediaFor");function consumeAnnotationPart(turn,text,isHarnessAnnotation){if(text.startsWith(OMNI_RESOURCE_HANDLE_TEXT_PREFIX)){const resourceId=parseResourceHandleText(text);if(resourceId){const body=text.slice(OMNI_RESOURCE_HANDLE_TEXT_PREFIX.length);const name=unescapeAnnotationName(body.slice(0,body.length-resourceId.length-1));mediaFor(turn,name).resourceId=resourceId;return true}return false}if(text.startsWith(OMNI_RESOURCE_PATH_TEXT_PREFIX)){if(!isHarnessAnnotation)return false;const filePath=parseResourcePathText(text);if(filePath){mediaFor(turn,filePath.split(/[\\/]/).pop()??filePath);return true}return false}for(const[prefix,apply]of[[OMNI_DISCLOSURE_TEXT_PREFIX,(m,payload)=>{m.disclosures.push(payload)}],[OMNI_OMISSION_TEXT_PREFIX,(m,payload)=>{m.omitted=payload}],[OMNI_TRANSCRIPT_TEXT_PREFIX,(m,payload)=>{m.transcripts.push(payload)}]]){if(!text.startsWith(prefix))continue;const split=splitAnnotationBody(text.slice(prefix.length));if(!split)return false;apply(mediaFor(turn,split.name),split.payload);return true}return false}__name(consumeAnnotationPart,"consumeAnnotationPart");function consumeRecordParts(turn,record,collectProse){const parts=(record.message?.parts??[]).flatMap(part=>[part,...functionResponseOfPart(part)?.parts??[]]);for(const part of parts){const raw=textOfPart(part);if(raw===void 0)continue;const withoutReminders=stripSystemReminders(raw);const forAnnotation=withoutReminders.replace(/^\s+/,"");if(consumeAnnotationPart(turn,forAnnotation,isHarnessAnnotationPart(part)))continue;const prose=withoutReminders.trim();if(!prose)continue;if(collectProse)turn.requestTexts.push(prose)}}__name(consumeRecordParts,"consumeRecordParts");function finishTurn(turn,sessionId){return{kind:"turn",sessionId,turnIndex:turn.turnIndex,...turn.timestamp!==void 0?{timestamp:turn.timestamp}:{},request:{text:turn.requestTexts.join("\n"),media:[...turn.media.values()],...turn.recall!==void 0?{recall:turn.recall}:{}},response:{text:turn.responseTexts.join("\n"),toolCalls:turn.toolCalls}}}__name(finishTurn,"finishTurn");function activeChainRecords(records){const byUuid=new Map;for(const record of records){if(typeof record.uuid==="string")byUuid.set(record.uuid,record)}if(byUuid.size===0)return records;let leaf;for(let i=records.length-1;i>=0;i--){if(typeof records[i].uuid==="string"){leaf=records[i];break}}if(!leaf)return records;const active=new Set;let current=leaf;while(current?.uuid&&!active.has(current.uuid)){active.add(current.uuid);current=typeof current.parentUuid==="string"?byUuid.get(current.parentUuid):void 0}return records.filter(r=>typeof r.uuid!=="string"||active.has(r.uuid))}__name(activeChainRecords,"activeChainRecords");function buildTurnRecords(transcriptLines){const turns=[];let sessionId="";let current;for(const record of activeChainRecords(transcriptLines)){if(typeof record.sessionId==="string"&&sessionId===""){sessionId=record.sessionId}if(record.type==="user"&&record.subtype===void 0){if(current)turns.push(finishTurn(current,sessionId));current={turnIndex:turns.length,...record.timestamp!==void 0?{timestamp:record.timestamp}:{},requestTexts:[],media:new Map,responseTexts:[],toolCalls:[]};consumeRecordParts(current,record,true);continue}if(!current)continue;if(record.type==="system"&&record.subtype==="omni_recall"){current.recall=record.systemPayload;continue}if(record.type==="tool_result"){consumeRecordParts(current,record,false);continue}if(record.type==="assistant"){for(const part of record.message?.parts??[]){if(isThoughtPart(part))continue;const text=textOfPart(part);if(text!==void 0&&text.trim()){current.responseTexts.push(text);continue}const call=functionCallOfPart(part);if(call)current.toolCalls.push(call)}}}if(current)turns.push(finishTurn(current,sessionId));return turns}__name(buildTurnRecords,"buildTurnRecords");async function readSnapshotRaw(omniRootDir){const filePath=path3.join(omniRootDir,"memory.json");let raw;try{raw=await fs3.readFile(filePath,"utf8")}catch{return void 0}try{const parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||[parsed.files,parsed.versions,parsed.executions,parsed.entries].some(c=>typeof c!=="object"||c===null||Array.isArray(c))){throw new Error("unexpected snapshot shape")}return parsed}catch(err){debugLogger3.debug(`trajectory export: memory unreadable, exporting transcript only: ${err instanceof Error?err.message:err}`);return void 0}}__name(readSnapshotRaw,"readSnapshotRaw");function buildMemoryRecords(snapshot){const files=[];const executions=[];for(const version of Object.values(snapshot.versions)){try{const file=snapshot.files[version.fileId];if(!file)continue;files.push({kind:"file",fileId:version.fileId,fileVersionId:version.fileVersionId,rootFileId:file.rootFileId,sha256:version.sha256,mediaType:version.mediaType,origin:file.origin,sizeBytes:version.sizeBytes,mimeType:version.mimeType,source:version.source,...version.producedByExecutionId!==void 0?{producedByExecutionId:version.producedByExecutionId}:{},...version.parentVersionId!==void 0?{parentVersionId:version.parentVersionId}:{},createdAt:version.createdAt})}catch{}}for(const execution of Object.values(snapshot.executions)){try{const outputs=execution.outputRefs.flatMap(entryId=>{const entry=snapshot.entries[entryId];if(!entry)return[];return[{kind:entry.kind,...entry.role!==void 0?{role:entry.role}:{},...entry.artifactRef?.managedId?.startsWith("sha256/")?{sha256:entry.artifactRef.managedId.slice("sha256/".length)}:{},...entry.artifactRef?.mimeType!==void 0?{mimeType:entry.artifactRef.mimeType}:{},...entry.artifactRef?.sizeBytes!==void 0?{sizeBytes:entry.artifactRef.sizeBytes}:{},...entry.disclosure!==void 0?{disclosure:entry.disclosure}:{}}]});executions.push({kind:"execution",executionId:execution.executionId,invocationId:execution.invocationId,executionOrigin:execution.executionOrigin,toolName:execution.toolName,...execution.toolVersion!==void 0?{toolVersion:execution.toolVersion}:{},finalArguments:execution.finalArguments,omniConfigHash:execution.omniConfigHash,sourceVersionId:execution.sourceVersionId,rootFileId:execution.rootFileId,startedAt:execution.startedAt,completedAt:execution.completedAt,...execution.reusedExecutionId!==void 0?{reusedExecutionId:execution.reusedExecutionId}:{},outputs})}catch{}}return{files,executions}}__name(buildMemoryRecords,"buildMemoryRecords");function filterToSession(memory,turns,transcriptLines){const callIds=new Set;for(const record of activeChainRecords(transcriptLines)){if(record.type!=="tool_result")continue;for(const part of record.message?.parts??[]){const id=functionResponseOfPart(part)?.id;if(typeof id==="string")callIds.add(id)}}const mediaNames=new Set;for(const turn of turns){for(const call of turn.response.toolCalls){if(call.callId)callIds.add(call.callId)}for(const media of turn.request.media)mediaNames.add(media.name)}const filesByVersion=new Map(memory.files.map(f=>[f.fileVersionId,f]));const versionsByFile=new Map;for(const f of memory.files){const list=versionsByFile.get(f.fileId)??[];list.push(f);versionsByFile.set(f.fileId,list)}const includedFiles=new Set;const includedExecutions=new Set;const includeFile=__name(fileId=>{if(!fileId||includedFiles.has(fileId))return false;if(!versionsByFile.has(fileId))return false;includedFiles.add(fileId);return true},"includeFile");for(const f of memory.files){if(mediaNames.has(f.source.locator))includeFile(f.fileId)}for(const e of memory.executions){if(callIds.has(e.invocationId))includedExecutions.add(e.executionId)}let changed=true;while(changed){changed=false;for(const e of memory.executions){const sourceFile=filesByVersion.get(e.sourceVersionId)?.fileId;if(!includedExecutions.has(e.executionId)){if(sourceFile&&includedFiles.has(sourceFile)){includedExecutions.add(e.executionId);changed=true}else{continue}}if(includeFile(sourceFile))changed=true}for(const f of memory.files){if(includedFiles.has(f.fileId))continue;if(f.producedByExecutionId!==void 0&&includedExecutions.has(f.producedByExecutionId)){includeFile(f.fileId);changed=true}}}return{files:memory.files.filter(f=>includedFiles.has(f.fileId)),executions:memory.executions.filter(e=>includedExecutions.has(e.executionId))}}__name(filterToSession,"filterToSession");async function exportOmniTrajectory(options){const raw=await fs3.readFile(options.transcriptPath,"utf8");const transcriptLines=[];for(const line of raw.split("\n")){if(!line.trim())continue;try{transcriptLines.push(JSON.parse(line))}catch{}}const turns=buildTurnRecords(transcriptLines);const records=[...turns];const snapshot=await readSnapshotRaw(options.omniRootDir);const memoryRecords=snapshot?filterToSession(buildMemoryRecords(snapshot),turns,transcriptLines):{files:[],executions:[]};records.push(...memoryRecords.files.sort((a,b)=>a.fileVersionId.localeCompare(b.fileVersionId)),...memoryRecords.executions.sort((a,b)=>a.executionId.localeCompare(b.executionId)));return records}__name(exportOmniTrajectory,"exportOmniTrajectory");function serializeOmniTrajectory(records){return records.map(r=>JSON.stringify(r)).join("\n")+"\n"}__name(serializeOmniTrajectory,"serializeOmniTrajectory");async function writeOmniTrajectoryJsonl(options){const outPath=path3.resolve(options.outPath);if(outPath===path3.resolve(options.transcriptPath)){throw new Error("trajectory outPath must differ from the transcript path")}const records=await exportOmniTrajectory(options);await fs3.mkdir(path3.dirname(outPath),{recursive:true});await fs3.writeFile(outPath,serializeOmniTrajectory(records),"utf8");return{records:records.length}}__name(writeOmniTrajectoryJsonl,"writeOmniTrajectoryJsonl");var debugLogger4=createDebugLogger("omni");function sanitizeErrorMessage(err,knownPaths=[]){let msg=err instanceof Error?err.message:String(err);for(const known of knownPaths){if(!known)continue;msg=msg.split(known).join(path4.basename(known));const segments=known.split(/[\\/]+/).filter(Boolean);if(/^[A-Za-z]:$/.test(segments[0]??""))segments.shift();if(segments.length>=2){const spelled=segments.map(segment=>segment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");msg=msg.replace(new RegExp(`(?:[A-Za-z]:)?[\\\\/]*${spelled}`,"g"),()=>path4.basename(known))}}return msg.replace(/(?:\/[^/\s'"]+)+\/([^/\s'"]+)/g,"$1").replace(/(?:[A-Za-z]:)?(?:\\[^\\\s'"]+)+\\([^\\\s'"]+)/g,"$1")}__name(sanitizeErrorMessage,"sanitizeErrorMessage");function buildAdditionalMediaParts(displayName,additionalMedia){const parts=[];for(const extra of additionalMedia??[]){if(extra.disclosure){parts.push({text:formatDisclosureText(displayName,extra.disclosure)})}if(extra.omission){parts.push({text:formatOmissionText(displayName,extra.omission.reason)})}else{parts.push({fileData:{fileUri:extra.fileUri,mimeType:extra.mimeType,displayName}})}}return parts}__name(buildAdditionalMediaParts,"buildAdditionalMediaParts");function buildTranscriptParts(displayName,transcripts){const parts=[];for(const t of transcripts??[]){if(t.disclosure){parts.push({text:formatDisclosureText(displayName,t.disclosure)})}parts.push({text:formatTranscriptText(displayName,t.text)})}return parts}__name(buildTranscriptParts,"buildTranscriptParts");var OmniDeliveryError=class extends Error{static{__name(this,"OmniDeliveryError")}constructor(message,options){super(message,options);this.name="OmniDeliveryError"}};function evaluateTransportLimits(config,recognized,displayName){try{assertWithinByteLimit(config,recognized.sizeBytes,displayName);assertWithinDurationLimit(config,recognized,displayName);return{estimate:assertWithinTokenLimit(config,recognized,displayName)}}catch(err){if(err instanceof OmniTransportGuardError){return{estimate:estimateRawResourceTokens(recognized),violation:err.message}}throw err}}__name(evaluateTransportLimits,"evaluateTransportLimits");async function processMediaForOmniDelivery(filePath,config,options){const{expectedModality,signal}=options??{};const displayName=options?.displayName??path4.basename(filePath);const[ffmpeg,ffprobe]=await Promise.all([isFfmpegAvailable(),isFfprobeAvailable()]);if(!ffmpeg||!ffprobe){throw new OmniDeliveryError("ffmpeg/ffprobe not available; omni media delivery requires both on PATH.")}await fs4.stat(filePath).catch(err=>{throw new OmniDeliveryError(`Cannot stat media file ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})});let recognized;try{recognized=await recognizeMediaFile(filePath,{expectedModality,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Media recognition failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath])}`,{cause:err})}const store=new OmniObjectStore(config.storage.getQwenDir());const uploadConfig=requireEffectiveOmniUploadConfig(config);const cacheScope=createHash("sha256").update(`${uploadConfig.baseUrl}|${uploadConfig.apiKey}`).digest("hex").slice(0,16);const configuredTtl=config.getOmniUploadUrlTtlHours?.();const uploadCache=new OmniUploadCache(store.getOmniRootDir(),configuredTtl===void 0?DEFAULT_UPLOAD_CACHE_TTL_HOURS:configuredTtl,cacheScope);await runStartupRecoveryOnce(store,uploadCache,{quarantineRetentionDays:config.getOmniQuarantineRetentionDays?.(),quarantineMaxBytes:config.getOmniQuarantineMaxBytes?.(),degradationCache:new OmniDegradationCache(store.getOmniRootDir())});const processingConfig=config.getOmniProcessingConfig?.();const conditionContext=processingConfig?{session:buildSessionConditionNamespace(config,processingConfig.limits.reservedOutputTokens)}:void 0;const memoryConfig=config.getOmniMemoryConfig?.();const memoryService=memoryConfig?new MediaMemoryService(store.getOmniRootDir(),{maxInlineTextBytes:memoryConfig.collection.maxInlineTextBytes}):void 0;if(memoryService){void runOmniGcOnce({store,memoryService,registry:config.getOmniMediaResourceRegistry?.(),uploadCache,degradationCache:new OmniDegradationCache(store.getOmniRootDir()),retentionDays:config.getOmniStorageRetentionDays?.()??14,maxTotalBytes:typeof config.getOmniStorageMaxTotalBytes==="function"?effectiveOmniStorageMaxTotalBytes(config):20*1024*1024*1024})}const registry=memoryService?config.getOmniMediaResourceRegistry?.():void 0;const bindSessionResource=__name((item,fileRefOverride)=>registry&&item.memoryBinding?registry.bind({...item.memoryBinding,fileRef:fileRefOverride??item.filePath,mediaType:item.recognized.modality}):void 0,"bindSessionResource");let sourceSha256;let sourceBinding;let sourceFileRef=filePath;if(memoryService){try{sourceSha256=await hashFileSha256(filePath,signal)}catch(err){if(signal?.aborted)throw err;debugLogger4.debug(`omni memory: hashing ${displayName} failed, skipping collection: ${sanitizeErrorMessage(err,[filePath])}`)}if(sourceSha256){const origin=options?.origin??"user";const ephemeralSource=origin==="tool"||options?.sourceUrl!==void 0;sourceFileRef=ephemeralSource?store.objectPathFor(sourceSha256,extensionForMime(recognized.detectedMimeType)):filePath;sourceBinding=await memoryService.recordFileRecognized({fileRef:sourceFileRef,sha256:sourceSha256,mediaType:recognized.modality,metadata:recognized.metadata,sizeBytes:recognized.sizeBytes,mimeType:recognized.detectedMimeType,origin,source:options?.sourceUrl!==void 0?{protocol:"url",locator:options.sourceUrl}:origin==="tool"?{protocol:"managed",locator:`sha256/${sourceSha256}`}:{protocol:"local",locator:displayName},recognition:{ingestionConfigHash:"",detectorVersion:MEDIA_DETECTOR_VERSION,probeStatus:"complete"}})}}let final={filePath,recognized,sha256:sourceSha256,memoryBinding:sourceBinding};const sessionResourceId=bindSessionResource(final,sourceFileRef)?.resourceId;const guardRejection=__name((message,options2)=>{const err=new OmniTransportGuardError(message,options2);if(sessionResourceId!==void 0){err.sessionResourceId=sessionResourceId}return err},"guardRejection");let extraDeliveries=[];const transcripts=[];const collectTranscripts=__name(files=>{for(const file of files){transcripts.push({text:file.text,disclosure:file.disclosure})}},"collectTranscripts");const textOnlyDelivery=__name((recognizedFinal,tokenEstimate2,extras)=>({fileUri:"",mimeType:recognizedFinal.detectedMimeType,sha256:"",recognized:recognizedFinal,tokenEstimate:tokenEstimate2,deduped:false,uploadCacheHit:false,degraded:true,transcripts,resourceId:sessionResourceId,...extras}),"textOnlyDelivery");const policies=processingConfig?.fixedPolicies??[];if(policies.length>0){let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath,recognized,displayName,origin:options?.origin??"user",sha256:sourceSha256},{store,policies,signal,limits:processingConfig?.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Fixed-policy processing failed for ${displayName}: ${sanitizeErrorMessage(err,[filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&transcripts.length>0){return textOnlyDelivery(recognized,evaluateTransportLimits(config,recognized,displayName).estimate)}if(deliveries.length===0){throw new OmniDeliveryError(`Fixed policies produced 0 media deliverables for ${displayName}; exactly one is supported.`)}final=deliveries[0];extraDeliveries=deliveries.slice(1);for(const delivery of deliveries)bindSessionResource(delivery)}const uploadModel=uploadConfig.model;const uploadResource=__name(async(item,estimate)=>{let sha256;try{sha256=item.sha256??await hashFileSha256(item.filePath,signal)}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to hash media file ${displayName}: ${sanitizeErrorMessage(err,[item.filePath])}`,{cause:err})}const cachedUrl=await uploadCache.get(sha256,uploadModel);if(cachedUrl){debugLogger4.debug(`omni upload cache hit: sha256=${sha256.slice(0,12)}\u2026 model=${uploadModel}`);return{fileUri:cachedUrl,sha256,deduped:true,uploadCacheHit:true}}const extension=extensionForMime(item.recognized.detectedMimeType);let objectPath;let deduped;try{const put=await store.putFile(item.filePath,sha256,extension,signal);objectPath=put.objectPath;deduped=put.deduped}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(`Failed to store media in the omni object store: ${sanitizeErrorMessage(err,[item.filePath,store.getOmniRootDir()])}`,{cause:err})}const uploader=new DashScopeUploader({apiKey:uploadConfig.apiKey,baseUrl:uploadConfig.baseUrl});let fileUri;try{fileUri=await uploader.uploadFile({filePath:objectPath,model:uploadModel,mimeType:item.recognized.detectedMimeType,signal})}catch(err){if(signal?.aborted)throw err;throw new OmniDeliveryError(sanitizeErrorMessage(err,[objectPath,store.getOmniRootDir()]),{cause:err})}debugLogger4.debug(`omni ${item.recognized.modality} delivered: sha256=${sha256.slice(0,12)}\u2026 size=${item.recognized.sizeBytes} est=${estimate.estimatedTokenCount}(${estimate.status}) deduped=${deduped} degraded=${item.degraded===true} uri=${fileUri}`);await uploadCache.put(sha256,uploadModel,fileUri);return{fileUri,sha256,deduped,uploadCacheHit:false}},"uploadResource");const processAdditionalMedia=__name(async()=>{if(extraDeliveries.length===0)return void 0;return Promise.all(extraDeliveries.map(async extra=>{const extraGuard=evaluateTransportLimits(config,extra.recognized,displayName);if(extraGuard.violation){debugLogger4.debug(`omni additional ${extra.recognized.modality} explicitly omitted (transport guard): ${extraGuard.violation}`);return{fileUri:"",mimeType:extra.recognized.detectedMimeType,sha256:extra.sha256??"",disclosure:extra.disclosure,omission:{reason:extraGuard.violation}}}const uploaded2=await uploadResource(extra,extraGuard.estimate);return{fileUri:uploaded2.fileUri,mimeType:extra.recognized.detectedMimeType,sha256:uploaded2.sha256,disclosure:extra.disclosure}}))},"processAdditionalMedia");let guard=evaluateTransportLimits(config,final.recognized,displayName);if(guard.violation&&processingConfig){const maxPasses=processingConfig.limits.maxTransportPasses;for(let pass=0;guard.violation&&pass<maxPasses;pass++){const guardPolicies=processingConfig.transportGuardPolicies.filter(p=>p.mediaTypes.includes(final.recognized.modality));if(guardPolicies.length===0)break;let deliveries;let fileDeliveries;try{({deliveries,fileDeliveries}=await runFixedPolicies(config,{filePath:final.filePath,recognized:final.recognized,displayName,origin:options?.origin??"user",sha256:final.sha256},{store,policies:guardPolicies,signal,limits:processingConfig.limits,conditionContext,memory:memoryService?{service:memoryService,sourceBinding:final.memoryBinding}:void 0}))}catch(err){if(signal?.aborted)throw err;throw guardRejection(`Transport-guard processing failed for ${displayName}: ${sanitizeErrorMessage(err,[final.filePath,store.getOmniRootDir()])}`,{cause:err})}collectTranscripts(fileDeliveries);if(deliveries.length===0&&fileDeliveries.length>0){return textOnlyDelivery(final.recognized,guard.estimate,{disclosure:final.disclosure,additionalMedia:await processAdditionalMedia()})}if(deliveries.length!==1){throw guardRejection(`Transport-guard policies produced ${deliveries.length} media deliverables for ${displayName}; exactly one is supported.`)}if(deliveries[0].filePath===final.filePath){break}const priorDisclosure=final.disclosure;final=deliveries[0];if(priorDisclosure&&final.disclosure){final={...final,disclosure:`${priorDisclosure}\uFF1B${final.disclosure}`}}else if(priorDisclosure){final={...final,disclosure:priorDisclosure}}bindSessionResource(final);guard=evaluateTransportLimits(config,final.recognized,displayName)}}if(guard.violation){if(!processingConfig){throw guardRejection(guard.violation)}debugLogger4.debug(`omni ${final.recognized.modality} explicitly omitted (transport guard): ${guard.violation}`);return{fileUri:"",mimeType:final.recognized.detectedMimeType,sha256:final.sha256??"",recognized:final.recognized,tokenEstimate:guard.estimate,deduped:false,uploadCacheHit:false,disclosure:final.disclosure,degraded:final.degraded,omission:{reason:guard.violation},transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}const tokenEstimate=guard.estimate;const uploaded=await uploadResource(final,tokenEstimate);return{fileUri:uploaded.fileUri,mimeType:final.recognized.detectedMimeType,sha256:uploaded.sha256,recognized:final.recognized,tokenEstimate,deduped:uploaded.deduped,uploadCacheHit:uploaded.uploadCacheHit,disclosure:final.disclosure,degraded:final.degraded,transcripts:transcripts.length>0?transcripts:void 0,additionalMedia:await processAdditionalMedia(),resourceId:sessionResourceId}}__name(processMediaForOmniDelivery,"processMediaForOmniDelivery");async function readMediaViaOmniDelivery(params){const{filePath,config,displayName,relativePathForDisplay,expectedModality,signal}=params;try{const delivery=await processMediaForOmniDelivery(filePath,config,{expectedModality,signal});const transcriptParts=buildTranscriptParts(displayName,delivery.transcripts);const additionalParts=buildAdditionalMediaParts(displayName,delivery.additionalMedia);const handleParts=(()=>{if(!delivery.resourceId)return[];const binding=config.getOmniMediaResourceRegistry?.()?.resolve(delivery.resourceId);if(binding&&binding.fileRef===filePath&&!/[\r\n]/.test(filePath)){return[harnessPathAnnotationPart(filePath)]}return[{text:formatResourceHandleText(displayName,delivery.resourceId)}]})();if(delivery.omission){const omissionPart={text:formatOmissionText(displayName,delivery.omission.reason)};return{llmContent:transcriptParts.length>0||additionalParts.length>0||handleParts.length>0?[...handleParts,omissionPart,...additionalParts,...transcriptParts]:omissionPart.text,returnDisplay:`Media omitted by the omni transport guard: ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}if(!delivery.fileUri&&transcriptParts.length>0){const disclosureParts=delivery.disclosure?[{text:formatDisclosureText(displayName,delivery.disclosure)}]:[];return{llmContent:[...handleParts,...disclosureParts,...additionalParts,...transcriptParts],returnDisplay:`Read ${delivery.recognized.modality} as transcript (omni policy): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}const fileDataPart={fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName}};const parts=[...handleParts];const{width,height}=delivery.recognized.metadata;if(delivery.recognized.modality==="image"&&width!==void 0&&height!==void 0){parts.push({text:delivery.disclosure?`Image ${displayName}: delivered at ${width}x${height} px after degradation. Use zoom_image to inspect details \u2014 it reads the original file.`:`Image ${displayName}: full resolution ${width}x${height} px. Use zoom_image for a closer look at details.`})}if(delivery.disclosure){parts.push({text:formatDisclosureText(displayName,delivery.disclosure)})}parts.push(fileDataPart);parts.push(...additionalParts);parts.push(...transcriptParts);const llmContent=parts.length===1?fileDataPart:parts;return{llmContent,returnDisplay:`Read ${delivery.recognized.modality} file (omni upload): ${relativePathForDisplay}`,tokenEstimate:delivery.tokenEstimate}}catch(err){if(isAbortError(err)||signal?.aborted)throw err;const message=sanitizeErrorMessage(err,[filePath]);return{llmContent:`[Omni media delivery failed for ${displayName}: ${message}]`,returnDisplay:`Failed to deliver media via omni upload: ${relativePathForDisplay}`,error:`Omni media delivery failed: ${displayName}: ${message}`,errorType:"read_content_failure"}}}__name(readMediaViaOmniDelivery,"readMediaViaOmniDelivery");function effectiveMaxDownloadFileBytes(config){const uploadCap=effectiveMaxUploadFileBytes(config);const configured=config.getOmniUrlDownloadMaxFileBytes?.();if(configured!==void 0&&configured>0){return Math.min(configured,uploadCap)}return uploadCap}__name(effectiveMaxDownloadFileBytes,"effectiveMaxDownloadFileBytes");export{OmniDownloadError,parseHttpUrlRef,downloadMediaUrl,exportOmniTrajectory,serializeOmniTrajectory,writeOmniTrajectoryJsonl,sanitizeErrorMessage,buildAdditionalMediaParts,buildTranscriptParts,OmniDeliveryError,processMediaForOmniDelivery,readMediaViaOmniDelivery,effectiveMaxDownloadFileBytes,processToolResultOmniMedia};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|