shadow-claw 1.31.0 → 1.33.0
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/.well-known/mcp/server-card.json +1 -1
- package/.well-known/mcp.json +1 -1
- package/dist/electron/main.cjs +1 -1
- package/dist/lib/components/index.js +26 -26
- package/dist/lib/components/settings/shadow-claw-accounts.js +1 -1
- package/dist/lib/components/settings/shadow-claw-channel-config.js +1 -1
- package/dist/lib/components/settings/shadow-claw-control-plane.js +1 -1
- package/dist/lib/components/settings/shadow-claw-git.js +1 -1
- package/dist/lib/components/settings/shadow-claw-integrations.js +1 -1
- package/dist/lib/components/settings/shadow-claw-llm.js +1 -1
- package/dist/lib/components/settings/shadow-claw-mcp-remote.js +1 -1
- package/dist/lib/components/settings/shadow-claw-networking.js +1 -1
- package/dist/lib/components/settings/shadow-claw-notifications.js +1 -1
- package/dist/lib/components/settings/shadow-claw-peerjs.js +1 -1
- package/dist/lib/components/settings/shadow-claw-storage.js +1 -1
- package/dist/lib/components/settings/shadow-claw-task-server.js +1 -1
- package/dist/lib/components/settings/shadow-claw-webvm.js +1 -1
- package/dist/lib/components/shadow-claw-a2ui.js +1 -1
- package/dist/lib/components/shadow-claw-accounts.js +1 -1
- package/dist/lib/components/shadow-claw-channel-config.js +1 -1
- package/dist/lib/components/shadow-claw-channels.js +1 -1
- package/dist/lib/components/shadow-claw-chat.js +1 -1
- package/dist/lib/components/shadow-claw-control-plane.js +1 -1
- package/dist/lib/components/shadow-claw-conversations.js +1 -1
- package/dist/lib/components/shadow-claw-file-viewer.js +1 -1
- package/dist/lib/components/shadow-claw-files.js +1 -1
- package/dist/lib/components/shadow-claw-git.js +1 -1
- package/dist/lib/components/shadow-claw-integrations.js +1 -1
- package/dist/lib/components/shadow-claw-llm.js +1 -1
- package/dist/lib/components/shadow-claw-mcp-remote.js +1 -1
- package/dist/lib/components/shadow-claw-networking.js +1 -1
- package/dist/lib/components/shadow-claw-notifications.js +1 -1
- package/dist/lib/components/shadow-claw-page-header.js +1 -1
- package/dist/lib/components/shadow-claw-pages.js +1 -1
- package/dist/lib/components/shadow-claw-peerjs.js +1 -1
- package/dist/lib/components/shadow-claw-settings.js +1 -1
- package/dist/lib/components/shadow-claw-storage.js +1 -1
- package/dist/lib/components/shadow-claw-task-server.js +1 -1
- package/dist/lib/components/shadow-claw-tasks.js +1 -1
- package/dist/lib/components/shadow-claw-terminal.js +1 -1
- package/dist/lib/components/shadow-claw-tools.js +1 -1
- package/dist/lib/components/shadow-claw-webvm.js +1 -1
- package/dist/lib/components/shadow-claw.js +1 -1
- package/dist/lib/{config-DjZ9QWc4.js → config-BcFbkaQv.js} +21 -4
- package/dist/lib/config-BcFbkaQv.js.map +1 -0
- package/dist/lib/{configurePeerJs-u7CYSquX.js → configurePeerJs-CBMPHbwa.js} +3 -3
- package/dist/lib/{configurePeerJs-u7CYSquX.js.map → configurePeerJs-CBMPHbwa.js.map} +1 -1
- package/dist/lib/{connections-BURqMIUv.js → connections-PZrUDf49.js} +2 -2
- package/dist/lib/{connections-BURqMIUv.js.map → connections-PZrUDf49.js.map} +1 -1
- package/dist/lib/{downloadGroupFile-B8J4up2a.js → downloadGroupFile-DSRUa9Au.js} +2 -2
- package/dist/lib/{downloadGroupFile-B8J4up2a.js.map → downloadGroupFile-DSRUa9Au.js.map} +1 -1
- package/dist/lib/{file-viewer-DoHM75Jz.js → file-viewer-11VVOpJv.js} +5 -5
- package/dist/lib/{file-viewer-DoHM75Jz.js.map → file-viewer-11VVOpJv.js.map} +1 -1
- package/dist/lib/{getGroupDir-QrN2aTo8.js → getGroupDir-BxKMYPPm.js} +3 -3
- package/dist/lib/{getGroupDir-QrN2aTo8.js.map → getGroupDir-BxKMYPPm.js.map} +1 -1
- package/dist/lib/{git-DAP_EV6R.js → git-BppibnJW.js} +27 -10
- package/dist/lib/{git-DAP_EV6R.js.map → git-BppibnJW.js.map} +1 -1
- package/dist/lib/{iframe-sanitizer-Bujgq14T.js → iframe-sanitizer-Dp8EYffI.js} +2 -2
- package/dist/lib/{iframe-sanitizer-Bujgq14T.js.map → iframe-sanitizer-Dp8EYffI.js.map} +1 -1
- package/dist/lib/index.js +27 -27
- package/dist/lib/{initChatSplitResize-BjiWoqC_.js → initChatSplitResize-CE_kWaLf.js} +2 -2
- package/dist/lib/{initChatSplitResize-BjiWoqC_.js.map → initChatSplitResize-CE_kWaLf.js.map} +1 -1
- package/dist/lib/{initControlPlane-DCK_SHeR.js → initControlPlane-BRIIOzoH.js} +18 -17
- package/dist/lib/{initControlPlane-DCK_SHeR.js.map → initControlPlane-BRIIOzoH.js.map} +1 -1
- package/dist/lib/{markdown-BFUTPQoO.js → markdown-Cq4sVwUT.js} +4 -4
- package/dist/lib/{markdown-BFUTPQoO.js.map → markdown-Cq4sVwUT.js.map} +1 -1
- package/dist/lib/{mcp-reconnect-BxJ77WSb.js → mcp-reconnect-CoHDMjmY.js} +2 -2
- package/dist/lib/{mcp-reconnect-BxJ77WSb.js.map → mcp-reconnect-CoHDMjmY.js.map} +1 -1
- package/dist/lib/{memoryStorage-D3FBwO9T.js → memoryStorage-DcFWrn_y.js} +2 -2
- package/dist/lib/{memoryStorage-D3FBwO9T.js.map → memoryStorage-DcFWrn_y.js.map} +1 -1
- package/dist/lib/{orchestrator-DNamnY-k.js → orchestrator-C3TgDZvq.js} +100 -19
- package/dist/lib/{orchestrator-DNamnY-k.js.map → orchestrator-C3TgDZvq.js.map} +1 -1
- package/dist/lib/{orchestrator-XygttQw2.js → orchestrator-Ce9_lmL2.js} +12 -12
- package/dist/lib/{orchestrator-XygttQw2.js.map → orchestrator-Ce9_lmL2.js.map} +1 -1
- package/dist/lib/{peerjs-BgkPSHKa.js → peerjs-PTYQ7yEG.js} +6 -6
- package/dist/lib/{peerjs-BgkPSHKa.js.map → peerjs-PTYQ7yEG.js.map} +1 -1
- package/dist/lib/{push-client-C09NQEk5.js → push-client-DDV5Rcg6.js} +3 -3
- package/dist/lib/{push-client-C09NQEk5.js.map → push-client-DDV5Rcg6.js.map} +1 -1
- package/dist/lib/{readGroupFileBytes-CSA7u-nJ.js → readGroupFileBytes-7C8G-yps.js} +2 -2
- package/dist/lib/{readGroupFileBytes-CSA7u-nJ.js.map → readGroupFileBytes-7C8G-yps.js.map} +1 -1
- package/dist/lib/{shadow-claw-vzcggiax.js → shadow-claw-WrWoPqFx.js} +10 -10
- package/dist/lib/{shadow-claw-vzcggiax.js.map → shadow-claw-WrWoPqFx.js.map} +1 -1
- package/dist/lib/{shadow-claw-a2ui-2I5nffIn.js → shadow-claw-a2ui-CcmJNXQP.js} +2 -2
- package/dist/lib/{shadow-claw-a2ui-2I5nffIn.js.map → shadow-claw-a2ui-CcmJNXQP.js.map} +1 -1
- package/dist/lib/{shadow-claw-accounts-DMb0y4ca.js → shadow-claw-accounts-CcB2429E.js} +3 -3
- package/dist/lib/{shadow-claw-accounts-DMb0y4ca.js.map → shadow-claw-accounts-CcB2429E.js.map} +1 -1
- package/dist/lib/{shadow-claw-channel-config-Cl3JvxIJ.js → shadow-claw-channel-config-C4v0h8oa.js} +3 -3
- package/dist/lib/{shadow-claw-channel-config-Cl3JvxIJ.js.map → shadow-claw-channel-config-C4v0h8oa.js.map} +1 -1
- package/dist/lib/{shadow-claw-channels-kv21lr_O.js → shadow-claw-channels-CyV88k9T.js} +3 -3
- package/dist/lib/{shadow-claw-channels-kv21lr_O.js.map → shadow-claw-channels-CyV88k9T.js.map} +1 -1
- package/dist/lib/{shadow-claw-chat-Cj1fHQIl.js → shadow-claw-chat-DSYtuZod.js} +11 -11
- package/dist/lib/{shadow-claw-chat-Cj1fHQIl.js.map → shadow-claw-chat-DSYtuZod.js.map} +1 -1
- package/dist/lib/{shadow-claw-control-plane-DySeKB36.js → shadow-claw-control-plane-DBSGuDT1.js} +7 -7
- package/dist/lib/{shadow-claw-control-plane-DySeKB36.js.map → shadow-claw-control-plane-DBSGuDT1.js.map} +1 -1
- package/dist/lib/{shadow-claw-conversations-DghueOOD.js → shadow-claw-conversations-Cp8pK4PM.js} +5 -5
- package/dist/lib/{shadow-claw-conversations-DghueOOD.js.map → shadow-claw-conversations-Cp8pK4PM.js.map} +1 -1
- package/dist/lib/{shadow-claw-file-viewer-C_ITv8T6.js → shadow-claw-file-viewer-B8G8yo48.js} +8 -8
- package/dist/lib/{shadow-claw-file-viewer-C_ITv8T6.js.map → shadow-claw-file-viewer-B8G8yo48.js.map} +1 -1
- package/dist/lib/{shadow-claw-files-CWBaYt9p.js → shadow-claw-files-D1COKzuC.js} +9 -9
- package/dist/lib/{shadow-claw-files-CWBaYt9p.js.map → shadow-claw-files-D1COKzuC.js.map} +1 -1
- package/dist/lib/{shadow-claw-git-XfPBpfXd.js → shadow-claw-git-60tWU4Ee.js} +6 -6
- package/dist/lib/{shadow-claw-git-XfPBpfXd.js.map → shadow-claw-git-60tWU4Ee.js.map} +1 -1
- package/dist/lib/{shadow-claw-integrations-yT7j07TM.js → shadow-claw-integrations-Bw1cG1ze.js} +4 -4
- package/dist/lib/{shadow-claw-integrations-yT7j07TM.js.map → shadow-claw-integrations-Bw1cG1ze.js.map} +1 -1
- package/dist/lib/{shadow-claw-llm-Gzx4ufL_.js → shadow-claw-llm-By5CvsFJ.js} +6 -6
- package/dist/lib/{shadow-claw-llm-Gzx4ufL_.js.map → shadow-claw-llm-By5CvsFJ.js.map} +1 -1
- package/dist/lib/{shadow-claw-mcp-remote-DGDWjByQ.js → shadow-claw-mcp-remote-BaNODd1v.js} +4 -4
- package/dist/lib/{shadow-claw-mcp-remote-DGDWjByQ.js.map → shadow-claw-mcp-remote-BaNODd1v.js.map} +1 -1
- package/dist/lib/{shadow-claw-networking-CYEbc5TR.js → shadow-claw-networking-DtZ5bsTz.js} +2 -2
- package/dist/lib/{shadow-claw-networking-CYEbc5TR.js.map → shadow-claw-networking-DtZ5bsTz.js.map} +1 -1
- package/dist/lib/{shadow-claw-notifications-DHvkTrgv.js → shadow-claw-notifications-C3VEba_A.js} +3 -3
- package/dist/lib/{shadow-claw-notifications-DHvkTrgv.js.map → shadow-claw-notifications-C3VEba_A.js.map} +1 -1
- package/dist/lib/{shadow-claw-page-header-DrAcWCZ9.js → shadow-claw-page-header-BLowJopA.js} +2 -2
- package/dist/lib/{shadow-claw-page-header-DrAcWCZ9.js.map → shadow-claw-page-header-BLowJopA.js.map} +1 -1
- package/dist/lib/{shadow-claw-pages-Bj3w3V6Y.js → shadow-claw-pages-CpeUV-hw.js} +9 -9
- package/dist/lib/{shadow-claw-pages-Bj3w3V6Y.js.map → shadow-claw-pages-CpeUV-hw.js.map} +1 -1
- package/dist/lib/{shadow-claw-peerjs-B3sx2xLA.js → shadow-claw-peerjs-DYAzJbTy.js} +3 -3
- package/dist/lib/{shadow-claw-peerjs-B3sx2xLA.js.map → shadow-claw-peerjs-DYAzJbTy.js.map} +1 -1
- package/dist/lib/{shadow-claw-settings-DK-0kp3A.js → shadow-claw-settings-ByxwW3WK.js} +9 -9
- package/dist/lib/{shadow-claw-settings-DK-0kp3A.js.map → shadow-claw-settings-ByxwW3WK.js.map} +1 -1
- package/dist/lib/{shadow-claw-storage-p9nVMQPF.js → shadow-claw-storage-CsSPYVDJ.js} +5 -5
- package/dist/lib/{shadow-claw-storage-p9nVMQPF.js.map → shadow-claw-storage-CsSPYVDJ.js.map} +1 -1
- package/dist/lib/{shadow-claw-task-server-BNKCWG2M.js → shadow-claw-task-server-De2WCEw4.js} +2 -2
- package/dist/lib/{shadow-claw-task-server-BNKCWG2M.js.map → shadow-claw-task-server-De2WCEw4.js.map} +1 -1
- package/dist/lib/{shadow-claw-tasks-Dbq9rUku.js → shadow-claw-tasks-zHWT4GaE.js} +7 -7
- package/dist/lib/{shadow-claw-tasks-Dbq9rUku.js.map → shadow-claw-tasks-zHWT4GaE.js.map} +1 -1
- package/dist/lib/{shadow-claw-terminal-Wk2qRWJ9.js → shadow-claw-terminal-Bpawfv4N.js} +2 -2
- package/dist/lib/{shadow-claw-terminal-Wk2qRWJ9.js.map → shadow-claw-terminal-Bpawfv4N.js.map} +1 -1
- package/dist/lib/{shadow-claw-tools-C9TEf2k7.js → shadow-claw-tools-BbKdWcps.js} +7 -7
- package/dist/lib/{shadow-claw-tools-C9TEf2k7.js.map → shadow-claw-tools-BbKdWcps.js.map} +1 -1
- package/dist/lib/{shadow-claw-webvm-VoKerWW8.js → shadow-claw-webvm-DLqK0AxW.js} +3 -3
- package/dist/lib/{shadow-claw-webvm-VoKerWW8.js.map → shadow-claw-webvm-DLqK0AxW.js.map} +1 -1
- package/dist/lib/subsystems/git/git.d.ts +8 -1
- package/dist/lib/subsystems/git/types.d.ts +7 -1
- package/dist/lib/subsystems/mcp/webmcp.d.ts +37 -0
- package/dist/lib/subsystems/providers/model-registry.d.ts +4 -1
- package/dist/lib/subsystems/providers/providers.d.ts +10 -0
- package/dist/lib/{syncWebMcpRegistration-DEs4JjI_.js → syncWebMcpRegistration-mlbbvcdm.js} +5 -5
- package/dist/lib/{syncWebMcpRegistration-DEs4JjI_.js.map → syncWebMcpRegistration-mlbbvcdm.js.map} +1 -1
- package/dist/lib/{tools-f1WPNDSS.js → tools-Bb2ujM2E.js} +4 -4
- package/dist/lib/{tools-f1WPNDSS.js.map → tools-Bb2ujM2E.js.map} +1 -1
- package/dist/lib/utils/index.js +1 -1
- package/dist/lib/utils/utils.js +1 -1
- package/dist/lib/{utils-B99XP70b.js → utils-mpsYPfS7.js} +3 -3
- package/dist/lib/{utils-B99XP70b.js.map → utils-mpsYPfS7.js.map} +1 -1
- package/dist/lib/webmcp-BVR2lBVo.js +1544 -0
- package/dist/lib/webmcp-BVR2lBVo.js.map +1 -0
- package/dist/public/.well-known/mcp/server-card.json +1 -1
- package/dist/public/.well-known/mcp.json +1 -1
- package/dist/public/agent.worker.js +44 -44
- package/dist/public/config-BqecTktB.js +1 -0
- package/dist/public/{configurePeerJs-B68egTBd.js → configurePeerJs-BPKfWuEt.js} +1 -1
- package/dist/public/{connections-6575KDGE.js → connections-C_3tYsmX.js} +1 -1
- package/dist/public/{custom-element-security-Da_6HQ6X.js → custom-element-security-DXwU3Lae.js} +1 -1
- package/dist/public/docs/example/article/index.html +2 -2
- package/dist/public/docs/publishing/index.html +2 -2
- package/dist/public/docs/skill-creator/index.html +2 -2
- package/dist/public/docs/subsystems/tools.md +4 -3
- package/dist/public/docs/subsystems/webmcp.md +58 -13
- package/dist/public/{downloadGroupFile-Dj-AMNsd.js → downloadGroupFile-DTyf5DIC.js} +1 -1
- package/dist/public/{e2e-bridge-DQ4Mb_eC.js → e2e-bridge-DXwWCQKw.js} +1 -1
- package/dist/public/{file-viewer-BqNHyqzy.js → file-viewer-ConEyDDG.js} +1 -1
- package/dist/public/{getGroupDir-BwprrdrQ.js → getGroupDir-ZfZsiq6d.js} +1 -1
- package/dist/public/git-BtBaLC1-.js +100 -0
- package/dist/public/git-DgFF7xTW.js +100 -0
- package/dist/public/{iframe-sanitizer-viROQkRn.js → iframe-sanitizer-Corkvo_d.js} +1 -1
- package/dist/public/index.html +2 -2
- package/dist/public/index.js +1 -1
- package/dist/public/{initChatSplitResize-BA18wLQQ.js → initChatSplitResize-CUc-TEmT.js} +1 -1
- package/dist/public/{initControlPlane-DG_LcLDy.js → initControlPlane-B_uYS8a4.js} +1 -1
- package/dist/public/main/index.html +2 -2
- package/dist/public/main/memory/index.html +2 -2
- package/dist/public/{markdown-eFKxxpVP.js → markdown-Cfa6GuJs.js} +1 -1
- package/dist/public/{mcp-reconnect-CBHuaYdF.js → mcp-reconnect-CUOkdPEz.js} +1 -1
- package/dist/public/{memoryStorage-C1llaYus.js → memoryStorage-Bh8fjmip.js} +1 -1
- package/dist/public/{orchestrator-BXwxW4N2.js → orchestrator-BcSzrg6E.js} +2 -2
- package/dist/public/{orchestrator-DAJkyJmV.js → orchestrator-Bi5OdVZD.js} +11 -11
- package/dist/public/{peerjs-BaDbzfgl.js → peerjs-CzCXG-NW.js} +1 -1
- package/dist/public/{push-client-B1CCaldJ.js → push-client-Cr3Ruahp.js} +1 -1
- package/dist/public/service-worker.js +1 -1
- package/dist/public/{shadow-claw-CpBmveOh.js → shadow-claw-CzUYuuOa.js} +2 -2
- package/dist/public/{shadow-claw-accounts-D1y-zbMs.js → shadow-claw-accounts-BgIHB_aP.js} +1 -1
- package/dist/public/{shadow-claw-channels-7Oew09u0.js → shadow-claw-channels-Ce_trJ5D.js} +1 -1
- package/dist/public/{shadow-claw-chat-CskwjDzZ.js → shadow-claw-chat-CdECLLwL.js} +1 -1
- package/dist/public/{shadow-claw-control-plane-BqjEyhx7.js → shadow-claw-control-plane-DM62UmOz.js} +2 -2
- package/dist/public/{shadow-claw-conversations-ClGgBPVY.js → shadow-claw-conversations-AM5g3C00.js} +1 -1
- package/dist/public/{shadow-claw-file-viewer-rDepUwFJ.js → shadow-claw-file-viewer-BP7gWS5g.js} +1 -1
- package/dist/public/{shadow-claw-files-C0r05PYf.js → shadow-claw-files-RPPGszcK.js} +1 -1
- package/dist/public/{shadow-claw-git-CXrECHKy.js → shadow-claw-git-BsHEvLrb.js} +2 -2
- package/dist/public/{shadow-claw-integrations-CRGL78Fy.js → shadow-claw-integrations-B0vbcOqg.js} +1 -1
- package/dist/public/{shadow-claw-llm-jeGVNciG.js → shadow-claw-llm-FNNamrc_.js} +2 -2
- package/dist/public/{shadow-claw-mcp-remote-DyGnK4S_.js → shadow-claw-mcp-remote-7mDgniQu.js} +1 -1
- package/dist/public/{shadow-claw-networking--q6MgEAT.js → shadow-claw-networking-CGsetaLp.js} +1 -1
- package/dist/public/{shadow-claw-notifications-CrFUF0fl.js → shadow-claw-notifications-pnwRcR-4.js} +1 -1
- package/dist/public/{shadow-claw-page-header-DA-FG08G.js → shadow-claw-page-header-BUy15Poz.js} +1 -1
- package/dist/public/{shadow-claw-pages-_n1wVXAV.js → shadow-claw-pages-ILAjGWNk.js} +1 -1
- package/dist/public/{shadow-claw-settings-5yIfa3ie.js → shadow-claw-settings-Bx5IgVqN.js} +3 -3
- package/dist/public/{shadow-claw-storage-PLX9EFGn.js → shadow-claw-storage-PAtNykaF.js} +1 -1
- package/dist/public/{shadow-claw-task-server-BMps7aSr.js → shadow-claw-task-server-Cbbi_2OO.js} +1 -1
- package/dist/public/{shadow-claw-tasks-CHO1xvsu.js → shadow-claw-tasks-B-jKYWZJ.js} +1 -1
- package/dist/public/{shadow-claw-terminal-BJnSXRsb.js → shadow-claw-terminal-BRejND-Z.js} +1 -1
- package/dist/public/{shadow-claw-tools-BHfxRckC.js → shadow-claw-tools-DNQe3oa-.js} +1 -1
- package/dist/public/{shadow-claw-webvm-CyI23mQT.js → shadow-claw-webvm-BFuwRifU.js} +1 -1
- package/dist/public/{syncWebMcpRegistration-R0tha3kP.js → syncWebMcpRegistration-FxKAPwaz.js} +1 -1
- package/dist/public/theme-init.js +1 -1
- package/dist/public/{tools-Cp1gequ8.js → tools-BwQKGsro.js} +1 -1
- package/dist/public/transformers-js.worker.js +1 -1
- package/dist/public/webmcp-C28PAlfy.js +1 -0
- package/dist/server.js +1 -1
- package/package.json +3 -3
- package/src/core/utils/initControlPlane.test.ts +122 -1
- package/src/core/utils/initControlPlane.ts +12 -8
- package/src/storage/staticMainSite.ts +16 -2
- package/src/stores/orchestrator.test.ts +33 -0
- package/src/stores/orchestrator.ts +36 -0
- package/src/subsystems/git/git.test.ts +99 -0
- package/src/subsystems/git/git.ts +92 -12
- package/src/subsystems/git/types.ts +7 -0
- package/src/subsystems/mcp/webmcp.test.ts +253 -1
- package/src/subsystems/mcp/webmcp.ts +147 -4
- package/src/subsystems/providers/model-registry.test.ts +139 -0
- package/src/subsystems/providers/model-registry.ts +54 -2
- package/src/subsystems/providers/providers.test.ts +329 -0
- package/src/subsystems/providers/providers.ts +135 -11
- package/dist/lib/config-DjZ9QWc4.js.map +0 -1
- package/dist/lib/webmcp-BC8_WafM.js +0 -1710
- package/dist/lib/webmcp-BC8_WafM.js.map +0 -1
- package/dist/public/config-Bnwx4EfS.js +0 -1
- package/dist/public/git-BDaM5VT5.js +0 -100
- package/dist/public/git-D4n46G9B.js +0 -100
- package/dist/public/webmcp-DBONjQWd.js +0 -2
|
@@ -52,5 +52,5 @@ ${r}${a}`+i.repeat(e)+`${r}`,o}function Gp(e,t,n,r){return`${t}${r}`+n.repeat(e)
|
|
|
52
52
|
`}):(F.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(t=>rm(t,r,i,nm,e.length)));let o=this.tokenizer(a,n);return{...await this.image_processor(e,n),...o}}},am=`<|image|>`,om=/<\|image_\d+\|>/g,sm=class extends J{static image_processor_class=Pp;static tokenizer_class=q;async _call(e,t=null,{padding:n=!0,truncation:r=!0,num_crops:i=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:i});let{num_img_tokens:s}=o,c=e.map((e,t)=>e.split(om).join(am.repeat(s[t])));a=this.tokenizer(c,{padding:n,truncation:r});let l=this.tokenizer._tokenizer.token_to_id(am);a.input_ids.map_(e=>e==l?-e:e)}else a=this.tokenizer(e);return{...a,...o}}},cm=class extends J{static tokenizer_class=q;static image_processor_class=Pp;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,image_break_token:a,image_end_token:o,patch_size:s,spatial_merge_size:c}=this.config,l=s*c,u=Math.floor(e/l),d=Math.floor(n/l);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e<t.length;++e){let n=i.repeat(d),r=n+a,s=n+o,c=r.repeat(u-1)+s;t[e]=t[e].replace(i,c)}}let i=t?this.tokenizer(t,n):{};return{...r,...i}}},lm=class extends J{static feature_extractor_class=Fd;async _call(e){return await this.feature_extractor(e)}post_process_speaker_diarization(...e){return this.feature_extractor.post_process_speaker_diarization(...e)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}},um=class extends zp{},dm=class extends um{},fm=class extends J{static image_processor_class=Pp;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}},pm=class extends fm{},mm=class extends pm{},hm=class extends J{static tokenizer_class=q;static feature_extractor_class=Ud;async _call(e){return await this.feature_extractor(e)}},gm=class extends J{static tokenizer_class=q;static feature_extractor_class=Ud;static uses_processor_config=!0;async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let i=t.length,{input_features:a}=await this.feature_extractor(t,{...n,max_length:i}),o=Math.round(i/this.config.encoder_ds_factor+1e-4),s=1+Math.ceil(o/this.config.stack_factor);r.audio_token_len=[s],r.audio_values=a;let c=this.config.audio_placeholder;if(!e.includes(c))throw Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(s))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}},_m=`[AUDIO]`,vm=`[BEGIN_AUDIO]`,ym=375;function bm(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.subarray(r,Math.min(r+t,e.length)));return n}var xm=class extends J{static tokenizer_class=q;static feature_extractor_class=Ud;static uses_processor_config=!1;async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){if(!e.includes(_m))throw Error(`The input text does not contain the audio token ${_m}.`);Array.isArray(t)||(t=[t]);let i=e.split(_m),a=i.length-1;if(a!==t.length)throw Error(`The number of audio inputs (${t.length}) does not match the number of audio tokens in the text (${a}).`);let o=this.feature_extractor.config.n_samples,s=t.map(e=>bm(e,o)),c=s.map(e=>e.length),l=s.flat(),u=(await Promise.all(l.map(e=>this.feature_extractor(e,n)))).map(e=>e.input_features);r.audio_values=u.length>1?Sl(u,0):u[0];let d=i[0];for(let e=0;e<c.length;++e){d+=vm;for(let t=0;t<c[e];++t)d+=_m.repeat(ym);d+=i[e+1]}e=d}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}},Sm=32,Cm=6,wm=8,Tm=10,Em=32,Dm=class extends J{static tokenizer_class=q;static feature_extractor_class=Ud;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(Cm+1)*wm}get num_samples_first_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*e+Math.floor(t/2)}get num_samples_per_audio_chunk(){let{hop_length:e,n_fft:t}=this.feature_extractor.config;return wm*e+t}get num_right_pad_tokens(){return Cm+1+Tm}get audio_length_per_tok(){return wm}get raw_audio_length_per_tok(){return wm*this.feature_extractor.config.hop_length}async _call(e,{is_streaming:t=!1,is_first_audio_chunk:n=!0}={}){if(Qu(e,`VoxtralRealtimeProcessor`),!t&&!n)throw Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(n)if(t){let t=Sm*this.raw_audio_length_per_tok,n=new Float32Array(t+e.length);n.set(e,t);let r=await this.feature_extractor(n,{center:!0}),i=1+(Sm+Cm),a=new BigInt64Array(i).fill(BigInt(Em));return a[0]=1n,{input_ids:new G(`int64`,a,[1,i]),...r}}else{let t=this.num_right_pad_tokens*this.raw_audio_length_per_tok,n=new Float32Array(e.length+t);return n.set(e),await this.feature_extractor(n,{center:!0})}else return await this.feature_extractor(e,{center:!1})}},Om=class extends J{static tokenizer_class=q;static feature_extractor_class=Ud;async _call(e){return await this.feature_extractor(e)}},km=class extends J{static tokenizer_class=q;static feature_extractor_class=Ud;async _call(e){return await this.feature_extractor(e)}},Am=class extends J{static tokenizer_class=q;static feature_extractor_class=Ud;async _call(e){return await this.feature_extractor(e)}},jm=class{static async from_pretrained(e,t={}){let n=await pc(e,qu,!0,t),{image_processor_type:r,feature_extractor_type:i,processor_class:a}=n;if(a&&Xu[a])return Xu[a].from_pretrained(e,t);if(!r&&!i)throw Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let o={};if(r){let e=ff[r.replace(/Fast$/,``)];if(!e)throw Error(`Unknown image_processor_type: '${r}'.`);o.image_processor=new e(n)}if(i){let e=ff[i];if(e)o.image_processor=new e(n);else{let e=$u[i];if(!e)throw Error(`Unknown feature_extractor_type: '${i}'.`);o.feature_extractor=new e(n)}}return new J({},o,null)}};async function Mm(e,t){return await pc(e,`config.json`,!0,t)}function Nm(e){let t={},n={};switch(e.model_type){case`llava`:case`paligemma`:case`gemma3`:case`florence2`:case`llava_onevision`:case`idefics3`:case`granite_speech`:case`ultravox`:case`voxtral`:case`voxtral_realtime`:case`smolvlm`:case`gemma3n`:case`gemma4`:case`lfm2_vl`:case`chatterbox`:case`lighton_ocr`:case`glm_ocr`:case`mistral3`:case`qwen2_5_vl`:case`qwen3_vl`:case`qwen3_vl_moe`:n=Nm(e.text_config);break;case`moondream1`:n=Nm(e.phi_config);break;case`musicgen`:n=Nm(e.decoder);break;case`multi_modality`:n=Nm(e.language_config);break;case`gpt2`:case`gptj`:case`jais`:case`codegen`:case`gpt_bigcode`:t.num_heads=`n_head`,t.num_layers=`n_layer`,t.hidden_size=`n_embd`;break;case`gpt_neox`:case`stablelm`:case`opt`:case`falcon`:case`modernbert-decoder`:t.num_heads=`num_attention_heads`,t.num_layers=`num_hidden_layers`,t.hidden_size=`hidden_size`;break;case`gpt_oss`:case`llama`:case`llama4_text`:case`nanochat`:case`apertus`:case`arcee`:case`afmoe`:case`lfm2`:case`lfm2_moe`:case`smollm3`:case`olmo`:case`olmo2`:case`olmo3`:case`mobilellm`:case`granite`:case`granitemoehybrid`:case`cohere`:case`cohere2`:case`mistral`:case`voxtral_realtime_text`:case`voxtral_realtime_encoder`:case`starcoder2`:case`qwen2`:case`qwen2_moe`:case`qwen2_vl`:case`qwen2_vl_text`:case`qwen2_5_vl_text`:case`qwen3_moe`:case`qwen3_vl_text`:case`qwen3_vl_moe_text`:case`phi`:case`phi3`:case`phi3_v`:case`llava_qwen2`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.hidden_size=`hidden_size`,t.num_attention_heads=`num_attention_heads`,t.dim_kv=`head_dim`;break;case`qwen3`:case`solar_open`:case`glm_ocr_text`:case`gemma`:case`gemma2`:case`vaultgemma`:case`gemma3_text`:case`gemma3n_text`:case`gemma4_text`:case`glm`:case`helium`:case`ernie4_5`:case`hunyuan_v1_dense`:case`falcon_h1`:case`nemotron_h`:case`ministral`:case`ministral3`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.dim_kv=`head_dim`;break;case`openelm`:t.num_heads=`num_kv_heads`,t.num_layers=`num_transformer_layers`,t.dim_kv=`head_dim`;break;case`gpt_neo`:case`donut-swin`:t.num_heads=`num_heads`,t.num_layers=`num_layers`,t.hidden_size=`hidden_size`;break;case`bloom`:t.num_heads=`n_head`,t.num_layers=`n_layer`,t.hidden_size=`hidden_size`;break;case`mpt`:t.num_heads=`n_heads`,t.num_layers=`n_layers`,t.hidden_size=`d_model`;break;case`exaone`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_layers`,t.dim_kv=`head_dim`,t.num_attention_heads=`num_attention_heads`;break;case`youtu`:case`deepseek_v3`:case`glm_moe_dsa`:case`mistral4`:t.num_heads=`num_key_value_heads`,t.num_layers=`num_hidden_layers`,t.dim_kv=`qk_head_dim`,t.num_attention_heads=`num_attention_heads`;break;case`t5`:case`mt5`:case`longt5`:t.num_decoder_layers=`num_decoder_layers`,t.num_decoder_heads=`num_heads`,t.decoder_dim_kv=`d_kv`,t.num_encoder_layers=`num_layers`,t.num_encoder_heads=`num_heads`,t.encoder_dim_kv=`d_kv`;break;case`bart`:case`mbart`:case`marian`:case`whisper`:case`lite-whisper`:case`m2m_100`:case`blenderbot`:case`blenderbot-small`:case`florence2_language`:t.num_decoder_layers=`decoder_layers`,t.num_decoder_heads=`decoder_attention_heads`,t.decoder_hidden_size=`d_model`,t.num_encoder_layers=`encoder_layers`,t.num_encoder_heads=`encoder_attention_heads`,t.encoder_hidden_size=`d_model`;break;case`speecht5`:t.num_decoder_layers=`decoder_layers`,t.num_decoder_heads=`decoder_attention_heads`,t.decoder_hidden_size=`hidden_size`,t.num_encoder_layers=`encoder_layers`,t.num_encoder_heads=`encoder_attention_heads`,t.encoder_hidden_size=`hidden_size`;break;case`trocr`:t.num_encoder_layers=t.num_decoder_layers=`decoder_layers`,t.num_encoder_heads=t.num_decoder_heads=`decoder_attention_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`d_model`;break;case`musicgen_decoder`:t.num_encoder_layers=t.num_decoder_layers=`num_hidden_layers`,t.num_encoder_heads=t.num_decoder_heads=`num_attention_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`hidden_size`;break;case`moonshine`:t.num_decoder_layers=`decoder_num_hidden_layers`,t.num_decoder_heads=`decoder_num_key_value_heads`,t.num_encoder_layers=`encoder_num_hidden_layers`,t.num_encoder_heads=`encoder_num_key_value_heads`,t.encoder_hidden_size=t.decoder_hidden_size=`hidden_size`;break;case`cohere_asr`:t.num_decoder_layers=`num_hidden_layers`,t.num_decoder_heads=`num_key_value_heads`,t.decoder_hidden_size=`hidden_size`,t.decoder_dim_kv=`head_dim`;let{num_hidden_layers:r,num_attention_heads:i,hidden_size:a}=e.encoder_config;n={num_encoder_layers:r,num_encoder_heads:i,encoder_hidden_size:a,encoder_dim_kv:e.head_dim};break;case`vision-encoder-decoder`:let o=Nm(e.decoder),s=`num_decoder_layers`in o,c=xi(e,[`model_type`,`is_encoder_decoder`]);return s?(c.num_decoder_layers=o.num_decoder_layers,c.num_decoder_heads=o.num_decoder_heads,c.decoder_hidden_size=o.decoder_hidden_size,c.num_encoder_layers=o.num_encoder_layers,c.num_encoder_heads=o.num_encoder_heads,c.encoder_hidden_size=o.encoder_hidden_size):(c.num_layers=o.num_layers,c.num_heads=o.num_heads,c.hidden_size=o.hidden_size),c}let r={...n,...xi(e,[`model_type`,`multi_query`,`is_encoder_decoder`])};for(let n in t)r[n]=e[t[n]];return r}function Pm(e,t){e instanceof Im||(e=new Im(e));let n=t?.prefix??`past_key_values`,r=n===`present`?`present`:`past`,i=new Set;if([`lfm2`,`lfm2_moe`].includes(e.model_type)){let{layer_types:t}=e;for(let e=0;e<t.length;++e)if(t[e]===`full_attention`)i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`);else if(t[e]===`conv`)i.add(`${r}_conv.${e}`);else throw Error(`Unsupported layer type: ${t[e]}`);return i}else if([`granitemoehybrid`,`falcon_h1`,`nemotron_h`].includes(e.model_type)){let t=e,a=t.layer_types??t.layers_block_type,o=t.num_hidden_layers??a?.length;for(let e=0;e<o;++e)(!a||a[e]===`mamba`)&&(i.add(`${r}_conv.${e}`),i.add(`${r}_ssm.${e}`)),(!a||a[e]===`attention`)&&(i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`));return i}else if([`qwen3_next`,`qwen3_5_text`,`qwen3_5_moe_text`,`olmo_hybrid`].includes(e.model_type)){let{layer_types:t}=e;for(let a=0;a<t.length;++a)if(t[a]===`full_attention`)i.add(`${n}.${a}.key`),i.add(`${n}.${a}.value`);else if(t[a]===`linear_attention`)e.model_type===`olmo_hybrid`?(i.add(`${r}_conv.${a}.key`),i.add(`${r}_conv.${a}.value`),i.add(`${r}_conv.${a}.query`)):i.add(`${r}_conv.${a}`),i.add(`${r}_recurrent.${a}`);else throw Error(`Unsupported layer type: ${t[a]}`);return i}else if([`gemma4`,`gemma4_text`].includes(e.model_type)){let t=e.model_type===`gemma4`?e.text_config:e,r=t.num_hidden_layers-(t.num_kv_shared_layers??0);for(let e=0;e<r;++e)i.add(`${n}.${e}.key`),i.add(`${n}.${e}.value`);return i}else if([`lfm2_vl`,`qwen3_5`,`qwen3_5_moe`,`voxtral_realtime`].includes(e.model_type)){let n;return n=e.model_type===`voxtral_realtime`&&t?.session_name===`audio_encoder`?e.audio_config:e.text_config,Pm(n,t)}return Fm(e,{prefix:n})}function Fm(e,{prefix:t=`past_key_values`}={}){let n=new Set,r=e.normalized_config;if(r.is_encoder_decoder&&`num_encoder_heads`in r&&`num_decoder_heads`in r)for(let e=0;e<r.num_decoder_layers;++e)n.add(`${t}.${e}.encoder.key`),n.add(`${t}.${e}.encoder.value`),n.add(`${t}.${e}.decoder.key`),n.add(`${t}.${e}.decoder.value`);else if(r.multi_query)for(let e=0;e<r.num_layers;++e)n.add(`${t}.${e}.key_value`);else for(let e=0;e<r.num_layers;++e)n.add(`${t}.${e}.key`),n.add(`${t}.${e}.value`);return n}var Im=class e{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(e){Object.assign(this,e),this.normalized_config=Nm(this)}static async from_pretrained(t,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:o=`main`}={}){r&&!(r instanceof e)&&(r=new e(r));let s=r??await Mm(t,{progress_callback:n,config:r,cache_dir:i,local_files_only:a,revision:o});return new this(s)}},Lm=class{static async from_pretrained(...e){return Im.from_pretrained(...e)}};function Rm(e,t,n){return e?typeof e==`object`&&e?e.hasOwnProperty(t)?+e[t]:e.hasOwnProperty(n)?+e[n]:0:+e:0}function zm(e,t){let n=[];for(let r=0;r<t;++r)n.push(`${e}_data${r===0?``:`_`+r}`);return n}async function Bm(e,t,n,r){let i=`${t}${r}.onnx`;return await dc(e,`${n.subfolder??``}/${i}`,!0,n,N.IS_NODE_ENV)}async function Vm(e,t,n,r,i,a={}){let o=`${t}${n}.onnx`,s=N.IS_NODE_ENV,c=[],l=Rm(i,o,t);if(l>0){if(l>Rs)throw Error(`The number of external data chunks (${l}) exceeds the maximum allowed value (${Rs}).`);let t=zm(o,l);for(let n of t){let t=`${r.subfolder??``}/${n}`;c.push(new Promise(async(i,a)=>{let o=await dc(e,t,!0,r,s);i(o instanceof Uint8Array?{path:n,data:o}:n)}))}}else a.externalData!==void 0&&(c=a.externalData.map(async t=>{if(typeof t.data==`string`){let n=await dc(e,t.data,!0,r);return{...t,data:n}}return t}));return Promise.all(c)}async function Hm(e,t,n,r=!1,i=void 0){let a=n.config?.[`transformers.js_config`]??{},o=nl(n.device??a.device,t,{warn:e=>F.info(e)}),s=Hc(o),c=a.device_config??{};c.hasOwnProperty(o)&&(a={...a,...c[o]});let l=cl(n.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:e=>F.info(e)});if(!sl.hasOwnProperty(l))throw Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys(il).join(`, `)}`);if(o===`webgpu`&&!N.IS_NODE_ENV&&l===il.fp16&&!await rl())throw Error(`The device (${o}) does not support fp16.`);let u=sl[l],d={...n.session_options};d.executionProviders??=s;let f=a.free_dimension_overrides;f?d.freeDimensionOverrides??=f:o.startsWith(`webnn`)&&!d.freeDimensionOverrides&&F.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let p=Bm(e,t,n,u),m=await Vm(e,t,u,n,n.use_external_data_format??a.use_external_data_format,d);if(m.length>0&&(!N.IS_NODE_ENV||m.some(e=>typeof e!=`string`))&&(d.externalData=m),r&&o===`webgpu`){let e=Pm(n.config,{prefix:`present`,session_name:i});if(e.size>0&&!Zc()){let t={};for(let n of e)t[n]=`gpu-buffer`;d.preferredOutputLocation=t}}return{buffer_or_path:await p,session_options:d,session_config:{dtype:l,device:o}}}async function Um(e,t,n,r=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async i=>{let a=r?.[i]??!1,{buffer_or_path:o,session_options:s,session_config:c}=await Hm(e,t[i],n,a,i);return[i,await Kc(o,s,c)]})))}function Wm(e){for(let t in e)Yc(e[t])?e[t]=new G(e[t]):typeof e[t]==`object`&&Wm(e[t]);return e}async function X(e,t){let n=Gm(e,t);try{return Wm(await Jc(e,Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=t.ort_tensor;return N.IS_NODE_ENV&&typeof Float16Array<`u`&&n.cpuData instanceof Float16Array&&(n.cpuData=new Uint16Array(n.cpuData.buffer)),[e,n]}))))}catch(e){let t=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n={type:t.type,dims:t.dims,location:t.location};return n.location!==`gpu-buffer`&&(n.data=t.data),[e,n]}));throw F.error(`An error occurred during model execution: "${e}".`),F.error(`Inputs given to model:`,t),e}}function Gm(e,t){let n=Object.create(null),r=[];for(let i of e.inputNames){let e=t[i];if(!(e instanceof G)){r.push(i);continue}n[i]=Zc()?e.clone():e}if(r.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(`, `)}.`);let i=Object.keys(t).length,a=e.inputNames.length;if(i>a){let n=Object.keys(t).filter(t=>!e.inputNames.includes(t));F.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: "${n.join(`, `)}".`)}return n}var Km=class{},Z=class extends Km{constructor({logits:e,...t}){super(),this.logits=e;let n=Object.values(t);n.length>0&&(this.attentions=n)}},qm=class extends Km{constructor({logits:e}){super(),this.logits=e}},Jm=class extends Km{constructor({logits:e}){super(),this.logits=e}},Ym=class extends Km{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},Xm=class extends Km{constructor({logits:e}){super(),this.logits=e}},Zm=class extends Km{constructor({alphas:e}){super(),this.alphas=e}},Qm=class extends fi{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},$m=class extends fi{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},eh=class extends fi{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(let t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}},th=class extends Qm{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===1){let e=t[n].data;e.fill(-1/0),e[this.bos_token_id]=0}return t}},nh=class extends Qm{constructor(e,t){super(),this.max_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===this.max_length-1){let e=t[n].data;e.fill(-1/0);for(let t of this.eos_token_id)e[t]=0}return t}},rh=class extends Qm{constructor(e){super(),this.suppress_tokens=e}_call(e,t){for(let n=0;n<e.length;++n){let e=t[n].data;for(let t of this.suppress_tokens)e[t]=-1/0}return t}},ih=class extends Qm{constructor(e,t){super(),this.begin_suppress_tokens=e,this.begin_index=t}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length===this.begin_index){let e=t[n].data;for(let t of this.begin_suppress_tokens)e[t]=-1/0}return t}},ah=class extends Qm{constructor(e,t){super(),this.eos_token_id=Array.isArray(e.eos_token_id)?e.eos_token_id[0]:e.eos_token_id,this.no_timestamps_token_id=e.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=t.length,t.at(-1)===this.no_timestamps_token_id&&--this.begin_index,this.max_initial_timestamp_index=e.max_initial_timestamp_index}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data;if(r[this.no_timestamps_token_id]=-1/0,e[n].length===this.begin_index){r.subarray(0,this.timestamp_begin).fill(-1/0);continue}let i=e[n].slice(this.begin_index),a=i.length>=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(a&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&this.max_initial_timestamp_index!==null){let e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}let s=_c(r);Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>yc(s.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},oh=class extends Qm{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r<t+1-this.no_repeat_ngram_size;++r){let t=[];for(let n=0;n<this.no_repeat_ngram_size;++n)t.push(e[r+n]);n.push(t.map(Number))}let r=new Map;for(let e of n){let t=e.slice(0,e.length-1),n=JSON.stringify(t),i=r.get(n)??[];i.push(e[e.length-1]),r.set(n,i)}return r}getGeneratedNgrams(e,t){let n=t.slice(t.length+1-this.no_repeat_ngram_size,t.length);return e.get(JSON.stringify(n.map(Number)))??[]}calcBannedNgramTokens(e){let t=[];if(e.length+1<this.no_repeat_ngram_size)return t;{let t=this.getNgrams(e);return this.getGeneratedNgrams(t,e)}}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data,i=this.calcBannedNgramTokens(e[n]);for(let e of i)r[e]=-1/0}return t}},sh=class extends Qm{constructor(e){super(),this.penalty=e}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data;for(let t of new Set(e[n])){let e=Number(t);r[e]<0?r[e]*=this.penalty:r[e]/=this.penalty}}return t}},ch=class extends Qm{constructor(e,t){super(),this.min_length=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length<this.min_length){let e=t[n].data;for(let t of this.eos_token_id)e[t]=-1/0}return t}},lh=class extends Qm{constructor(e,t,n){super(),this.prompt_length_to_skip=e,this.min_new_tokens=t,this.eos_token_id=Array.isArray(n)?n:[n]}_call(e,t){for(let n=0;n<e.length;++n)if(e[n].length-this.prompt_length_to_skip<this.min_new_tokens){let e=t[n].data;for(let t of this.eos_token_id)e[t]=-1/0}return t}},uh=class extends Qm{constructor(e,t){super(),this.bad_words_ids=e,this.eos_token_id=Array.isArray(t)?t:[t]}_call(e,t){for(let n=0;n<e.length;++n){let r=t[n].data,i=e[n];for(let e of this.bad_words_ids){if(i.length<e.length-1)continue;let t=!0;for(let n=1;n<=e.length-1;++n)if(e.at(-n-1)!=i.at(-n)){t=!1;break}t&&(r[e.at(-1)]=-1/0)}}return t}},dh=class extends Qm{constructor(e){if(super(),e<=1)throw Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let n=e.length,r=t.slice([0,n],null),i=t.slice([n,t.dims[0]],null);for(let e=0;e<i.data.length;++e)i.data[e]+=(r.data[e]-i.data[e])*this.guidance_scale;return i}},fh=class extends $m{constructor(e){if(super(),typeof e!=`number`||e<=0){let t=`\`temperature\` (=${e}) must be a strictly positive float, otherwise your next token scores will be invalid.`;e===0&&(t+=" If you're looking for greedy decoding strategies, set `do_sample=false`.")}this.temperature=e}_call(e,t){let n=t.data;for(let e=0;e<n.length;++e)n[e]/=this.temperature;return t}},ph=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(e){Object.assign(this,xi(e,Object.getOwnPropertyNames(this)))}},mh=class extends fi{_call(e,t){throw Error(`StoppingCriteria needs to be subclassed`)}},hh=class e extends fi{constructor(){super(),this.criteria=[]}push(e){this.criteria.push(e)}extend(t){t instanceof e?t=t.criteria:t instanceof mh&&(t=[t]),this.criteria.push(...t)}_call(e,t){let n=Array(e.length).fill(!1);for(let r of this.criteria){let i=r(e,t);for(let e=0;e<n.length;++e)n[e]||=i[e]}return n}[Symbol.iterator](){return this.criteria.values()}},gh=class extends mh{constructor(e,t=null){super(),this.max_length=e,this.max_position_embeddings=t}_call(e){return e.map(e=>e.length>=this.max_length)}},_h=class extends mh{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(e=>{let t=e.at(-1);return this.eos_token_id.some(e=>t==e)})}},vh=class extends fi{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error(`sample should be implemented in subclasses.`)}getLogits(e,t){let n=e.dims.at(-1),r=e.data;if(t===-1)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return r}randomSelect(e){return Ps(e)}static getSampler(e){if(e.do_sample)return new bh(e);if(e.num_beams>1)return new xh(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new yh(e)}},yh=class extends vh{async sample(e){let t=yc(e.data)[1];return[[BigInt(t),0]]}},bh=class extends vh{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await hl(e,t),i=gc(n.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]})}},xh=class extends vh{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await hl(e,t),i=gc(n.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[r.data[t],Math.log(i[t])])}},Sh=class{constructor(e){if(e)for(let t in e){if(t in this)throw TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let n=e[t];if(!(n instanceof G))throw TypeError(`Expected a Tensor for key "${t}", got ${typeof n}`);this[t]=n}}get_seq_length(){let e=this;if(Object.keys(e).length===0)return 0;for(let t in e)if(t.startsWith(`past_key_values.`))return e[t].dims.at(-2);throw Error(`Unable to determine sequence length from the cache.`)}update(e){for(let t in e){let n=this[t],r=e[t];n&&n!==r&&n.location===`gpu-buffer`&&n.dispose(),this[t]=r}}async dispose(){let e=[];for(let t of Object.values(this))t.location===`gpu-buffer`&&e.push(t.dispose());await Promise.all(e)}},Q={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},Ch={[Q.DecoderOnly]:{sessions:(e,t)=>({model:t.model_file_name??`model`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.DecoderOnlyWithoutHead]:{sessions:(e,t)=>({model:t.model_file_name??`model`})},[Q.Seq2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.Vision2Seq]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.Musicgen]:{sessions:()=>({model:`text_encoder`,decoder_model_merged:`decoder_model_merged`,encodec_decode:`encodec_decode`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.EncoderDecoder]:{sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0}},[Q.MaskGeneration]:{sessions:()=>({model:`vision_encoder`,prompt_encoder_mask_decoder:`prompt_encoder_mask_decoder`})},[Q.ImageTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...Ch[Q.ImageTextToText].text_only_sessions};return n||(r.vision_encoder=`vision_encoder`),e.is_encoder_decoder&&(r.model=`encoder_model`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.AudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...Ch[Q.AudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...Ch[Q.ImageAudioTextToText].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`,r.vision_encoder=`vision_encoder`),r},optional_configs:{generation_config:`generation_config.json`}},[Q.Phi3V]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`model`,vision_encoder:`vision_encoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.MultiModality]:{sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`language_model`,lm_head:`lm_head`,gen_head:`gen_head`,gen_img_embeds:`gen_img_embeds`,image_decode:`image_decode`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.AutoEncoder]:{sessions:()=>({encoder_model:`encoder_model`,decoder_model:`decoder_model`})},[Q.Supertonic]:{sessions:()=>({text_encoder:`text_encoder`,latent_denoiser:`latent_denoiser`,voice_decoder:`voice_decoder`})},[Q.Chatterbox]:{sessions:()=>({embed_tokens:`embed_tokens`,speech_encoder:`speech_encoder`,model:`language_model`,conditional_decoder:`conditional_decoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.VoxtralRealtime]:{text_only_sessions:{embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`},sessions:(e,t,n)=>{let r={...Ch[Q.VoxtralRealtime].text_only_sessions};return n||(r.audio_encoder=`audio_encoder`),r},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:`generation_config.json`}},default:{sessions:(e,t)=>({model:t.model_file_name??`model`})}};function wh(e,t,n={}){let r=Ch[e]??Ch.default;return{sessions:r.sessions(t,n,n.textOnly??!1),cache_sessions:r.cache_sessions,optional_configs:r.optional_configs}}function Th(e,{warn:t=!0}={}){let n=e.architectures||[];for(let e of n){let t=Ph.get(e);if(t!==void 0)return t}if(e.model_type){let t=Ph.get(e.model_type);if(t!==void 0)return t;for(let t of Object.values(Oh))if(t.has(e.model_type)){let n=Ph.get(t.get(e.model_type));if(n!==void 0)return n}}if(t){let t=n.length>0?n.join(`, `):`(none)`;F.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${t}] for model type '${e.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${Gu}`)}return Q.EncoderOnly}function Eh(e,{config:t=null,cache_dir:n=null,local_files_only:r=!1,revision:i=`main`}={}){return t===null?ec(JSON.stringify([e,n,r,i]),()=>Lm.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})):Lm.from_pretrained(e,{config:t,cache_dir:n,local_files_only:r,revision:i})}async function Dh(e,{config:t=null,dtype:n=null,device:r=null,model_file_name:i=null}={}){t=await Eh(e,{config:t});let a=[`config.json`],o=t[`transformers.js_config`]??{},s=o.use_external_data_format,c=`onnx`,l=r??o.device,u=n??o.dtype,d=Th(t),f=(e,t=null)=>{t??=e;let n=nl(l,e),r=sl[cl(u,e,n)]??``,i=`${t}${r}.onnx`,o=`${c}/${i}`;a.push(o);let d=Rm(s,i,e);for(let e of zm(i,d)){let t=`${c}/${e}`;a.push(t)}},{sessions:p,optional_configs:m}=wh(d,t,{model_file_name:i});for(let[e,t]of Object.entries(p))f(e,t);if(m)for(let e of Object.values(m))a.push(e);return a}var Oh=null;function kh(e){Oh=e}function Ah(e){if(e instanceof G)return e;if(e.length===0)throw Error(`items must be non-empty`);if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.`);return new G(`int64`,BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}else return new G(`int64`,BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length])}function jh(e){return new G(`bool`,[e],[1])}var Mh={[Q.DecoderOnly]:{can_generate:!0,forward:Wh,prepare_inputs:Xh},[Q.DecoderOnlyWithoutHead]:{can_generate:!1,forward:Wh,prepare_inputs:Xh},[Q.Seq2Seq]:{can_generate:!0,forward:Lh,prepare_inputs:Zh},[Q.Vision2Seq]:{can_generate:!0,forward:Lh,prepare_inputs:Zh},[Q.Musicgen]:{can_generate:!0,forward:Lh},[Q.EncoderDecoder]:{can_generate:!1,forward:Lh},[Q.ImageTextToText]:{can_generate:!0,forward:qh,prepare_inputs:Qh},[Q.AudioTextToText]:{can_generate:!0,forward:Kh,prepare_inputs:Qh},[Q.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:Qh},[Q.Phi3V]:{can_generate:!0,prepare_inputs:Qh},[Q.MultiModality]:{can_generate:!0},[Q.AutoEncoder]:{can_generate:!1,forward:zh},[Q.Chatterbox]:{can_generate:!0,forward:Rh},[Q.VoxtralRealtime]:{can_generate:!0,prepare_inputs:Xh},default:{can_generate:!1,forward:Rh}};function Nh(e,t){let n=Ph.get(e),r=!1,i=t?.architectures?.[0];if(i&&i!==e&&e?.endsWith(`ForCausalLM`)&&i.endsWith(`ForConditionalGeneration`)){let e=Ph.get(i);e!==void 0&&(n=e,r=!0)}let a=Mh[n]??Mh.default,o=Ch[n]??Ch.default;return{typeConfig:{...a,...o},textOnly:r,modelType:n}}var Ph=new Map,Fh=new Map,Ih=new Map,$=class extends fi{main_input_name=`input_ids`;forward_params=[`input_ids`,`attention_mask`];_return_dict_in_generate_keys=null;constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;let{typeConfig:r}=Nh(Ih.get(this.constructor),e);this.can_generate=r.can_generate,this._forward=r.forward,this._prepare_inputs_for_generation=r.prepare_inputs,this.can_generate&&this.forward_params.push(`past_key_values`),this.custom_config=this.config[`transformers.js_config`]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d},p=Ih.get(this);n=f.config=await Lm.from_pretrained(e,f);let{typeConfig:m,textOnly:h,modelType:g}=Nh(p,n);if(g===void 0){let e=p??n?.model_type;e!==`custom`&&F.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${Gu}.`)}if(t&&!(t instanceof mi)){let r={};try{let t=await Dh(e,{config:n,dtype:l,device:c,model_file_name:o});(await Promise.all(t.map(t=>nc(e,t,f)))).forEach((e,n)=>{if(e.exists){let i=t[n]===`config.json`;r[t[n]]={loaded:i?e.size??0:0,total:e.size??0}}})}catch(e){F.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`)}Object.keys(r).length>0&&(f.progress_callback=new mi(t,r))}let _=[Um(e,m.sessions(n,f,h),f,m.cache_sessions)];m.optional_configs&&_.push(ng(e,m.optional_configs,f));let v=await Promise.all(_);return new this(n,...v)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,n=null){let r=new eh;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new sh(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new oh(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new uh(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new ch(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&r.push(new lh(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new th(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new nh(e.max_length,e.forced_eos_token_id)),e.suppress_tokens!==null&&r.push(new rh(e.suppress_tokens)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new ih(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new dh(e.guidance_scale)),e.temperature===0&&e.do_sample&&(F.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&r.push(new fh(e.temperature)),n!==null&&r.extend(n),r}_prepare_generation_config(e,t,n=ph){let r={...this.config};for(let e of[`decoder`,`generator`,`text_config`])e in r&&Object.assign(r,r[e]);let i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,xi(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){let n=new hh;return e.max_length!==null&&n.push(new gh(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new _h(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){let e=[Oh.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,Oh.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,Oh.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,Oh.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=Ih.get(this.constructor),n=new Set,r=this.config.model_type;for(let t of e){let e=t?.get(r);e&&n.add(e)}let i=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(`, `)}`),Error(i)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw Error(`prepare_inputs_for_generation is not implemented for this model.`);return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=Bh(t,n.past_key_values),n.input_ids=new G(`int64`,e.flat(),[e.length,1]),r?`decoder_attention_mask`in n&&(n.decoder_attention_mask=Sl([n.decoder_attention_mask,jl([n.decoder_attention_mask.dims[0],1])],1)):n.attention_mask=Sl([n.attention_mask,jl([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){let r=xi(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes(`inputs_embeds`)&&!t.inputs_embeds&&`_prepare_inputs_embeds`in this){let{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...xi(a,[`inputs_embeds`,`attention_mask`])}}let{last_hidden_state:i}=await Rh(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)i=Sl([i,Al(i,0)],0),`attention_mask`in t&&(t.attention_mask=Sl([t.attention_mask,Pl(t.attention_mask)],0));else if(t.decoder_input_ids){let e=Ah(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(i.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=Sl(Array.from({length:e},()=>i),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:o,...s}=n;if(!(o instanceof G)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(r??=i,this.config.model_type===`musicgen`)o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[r]);else if(Array.isArray(r)){if(r.length!==e)throw Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=Ah(o)}return s.decoder_attention_mask=Ml(o),{input_ids:o,model_inputs:s}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:s,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),l=this.config.is_encoder_decoder;l&&(`encoder_outputs`in s||(s=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:s,model_input_name:c,generation_config:t})));let u;l?{input_ids:u,model_inputs:s}=this._prepare_decoder_input_ids_for_generation({batch_size:s[c].dims.at(0),model_input_name:c,model_kwargs:s,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):u=s[c];let d=u.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=d+t.max_new_tokens);let f=this._get_logits_processor(t,d,n),p=this._get_stopping_criteria(t,r),m=s[c].dims.at(0),h=vh.getSampler(t),g=Array(m).fill(0),_=u.tolist();i&&i.put(_);let v,y={},b={};for(;;){if(s=this.prepare_inputs_for_generation(_,s,t),v=await this.forward(s),t.return_dict_in_generate)if(t.output_attentions){let e=Vh(v);for(let t in e)t in y||(y[t]=[]),y[t].push(e[t])}else this._return_dict_in_generate_keys&&Object.assign(b,xi(v,this._return_dict_in_generate_keys));let e=f(_,v.logits.slice(null,-1,null).to(`float32`)),n=[];for(let t=0;t<e.dims.at(0);++t){let r=e[t],i=await h(r);for(let[e,r]of i){let i=BigInt(e);g[t]+=r,_[t].push(i),n.push([i]);break}}if(i&&i.put(n),p(_).every(e=>e))break;s=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:v,model_inputs:s,is_encoder_decoder:l})}i&&i.end();let x=new G(`int64`,_.flat(),[_.length,_[0].length]),S=Bh(v,s.past_key_values),C=new Set(Object.values(S));for(let e of Object.values(v))e.location===`gpu-buffer`&&!C.has(e)&&e.dispose();return`past_key_values`in a||t.return_dict_in_generate||await S.dispose(),t.return_dict_in_generate?{sequences:x,past_key_values:S,...y,...b}:x}async _encode_input(e,t,n){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let r=this.sessions[e];return(await X(r,xi(t,r.inputNames)))[n]}async encode_image(e){return this._encode_input(`vision_encoder`,e,`image_features`)}async encode_text(e){return this._encode_input(`embed_tokens`,e,`inputs_embeds`)}async encode_audio(e){return this._encode_input(`audio_encoder`,e,`audio_features`)}};async function Lh(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,decoder_attention_mask:a,...o}=t;return n||=(await Rh(e,xi(t,e.sessions.model.inputNames))).last_hidden_state,o.input_ids=i,o.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes(`encoder_attention_mask`)&&(o.encoder_attention_mask=t.attention_mask),a&&!o.attention_mask&&(o.attention_mask=a),await Wh(e,o,!0)}async function Rh(e,t){let n=e.sessions.model,r=xi(t,n.inputNames);if(n.inputNames.includes(`inputs_embeds`)&&!r.inputs_embeds){if(!t.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(n.inputNames.includes(`token_type_ids`)&&!r.token_type_ids){if(!r.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");r.token_type_ids=Pl(r.input_ids)}if(n.inputNames.includes(`pixel_mask`)&&!r.pixel_mask){if(!r.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let e=r.pixel_values.dims;r.pixel_mask=jl([e[0],e[2],e[3]])}return await X(n,r)}async function zh(e,t){let n=await e.encode(t);return await e.decode(n)}function Bh(e,t){let n=Object.create(null);for(let r in e)if(r.startsWith(`present`)){let i=r.replace(`present_ssm`,`past_ssm`).replace(`present_conv`,`past_conv`).replace(`present_recurrent`,`past_recurrent`).replace(`present`,`past_key_values`);r.includes(`encoder`)&&t?n[i]=t[i]:n[i]=e[r]}return t?(t.update(n),t):new Sh(n)}function Vh(e){let t={};for(let n of[`cross_attentions`,`encoder_attentions`,`decoder_attentions`])for(let r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}function Hh(e,t){return e.map(e=>typeof e==`number`?e:t[e]??0)}function Uh(e,t,n){if(n&&Object.keys(n).length>0)return Object.assign(t,n),n;let r=e.sessions.decoder_model_merged??e.sessions.model,i=(t[e.main_input_name]??t.attention_mask)?.dims?.[0]??1,a=Pm(e.config),o=e.config?.normalized_config?.num_heads,s={batch_size:i};typeof o==`number`&&(s[`batch_size x num_heads`]=i*o);let c=Object.create(null);for(let e of r.inputMetadata){if(!a.has(e.name))continue;let n=Hh(e.shape,s),r=n.reduce((e,t)=>e*t,1),i=ll[e.type],o=new G(e.type,new i(r),n);t[e.name]=o,c[e.name]=o}return n?(n.update(c),n):new Sh(c)}async function Wh(e,t,n=!1){let r=e.sessions[n?`decoder_model_merged`:`model`],{past_key_values:i,...a}=t;return r.inputNames.includes(`use_cache_branch`)&&(a.use_cache_branch=jh(i!=null&&Object.keys(i).length>0)),r.inputNames.includes(`position_ids`)&&a.attention_mask&&!a.position_ids&&(a.position_ids=Yh(a,i,+!![`paligemma`,`gemma3_text`,`gemma3`].includes(e.config.model_type))),r.inputNames.includes(`num_logits_to_keep`)&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new G(`int64`,[0n],[])),Uh(e,a,i),await X(r,xi(a,r.inputNames))}async function Gh(e,{encode_function:t,merge_function:n,modality_input_names:r,modality_output_name:i,input_ids:a=null,attention_mask:o=null,position_ids:s=null,inputs_embeds:c=null,past_key_values:l=null,generation_config:u=null,logits_processor:d=null,...f}){if(!c){c=await e.encode_text({input_ids:a,...f});let s=xi(f,r);if(Object.keys(s).length>0){if(a.dims[1]!==1){let e=await t({...s,...f});({inputs_embeds:c,attention_mask:o}=n({[i]:e,inputs_embeds:c,input_ids:a,attention_mask:o}))}else if(l&&a.dims[1]===1){let e=a.dims[1],t=l.get_seq_length();o=Sl([jl([a.dims[0],t]),o.slice(null,[o.dims[1]-e,o.dims[1]])],1)}}}if(!s&&[`qwen2_vl`,`qwen2_vl_text`,`qwen2_5_vl`,`qwen2_5_vl_text`,`qwen3_vl`,`qwen3_vl_text`,`qwen3_vl_moe`,`qwen3_vl_moe_text`,`qwen3_5`,`qwen3_5_text`,`qwen3_5_moe`,`qwen3_5_moe_text`,`glm_ocr`,`glm_ocr_text`].includes(e.config.model_type)){let{image_grid_thw:t,video_grid_thw:n}=f;[s]=e.get_rope_index(a,t,n,o)}return await Wh(e,{inputs_embeds:c,past_key_values:l,attention_mask:o,position_ids:s,generation_config:u,logits_processor:d},!0)}async function Kh(e,t){return await Gh(e,{...t,modality_input_names:[`audio_values`,`input_features`],modality_output_name:`audio_features`,encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function qh(e,t){return await Gh(e,{...t,modality_input_names:[`pixel_values`],modality_output_name:`image_features`,encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function Jh(e,t=0){let[n,r]=e.dims,i=e.data,a=new BigInt64Array(i.length);for(let e=0;e<n;++e){let n=e*r,o=BigInt(t);for(let e=0;e<r;++e){let t=n+e;i[t]===0n?a[t]=BigInt(1):(a[t]=o,o+=i[t])}}return{data:a,dims:e.dims}}function Yh(e,t=null,n=0){let{input_ids:r,inputs_embeds:i,attention_mask:a}=e,{data:o,dims:s}=Jh(a,n),c=new G(`int64`,o,s);if(t){let e=-(r??i).dims.at(1);c=c.slice(null,[e,null])}return c}function Xh(e,t,n,r){let i=n.past_key_values?n.past_key_values.get_seq_length():0;if((e.sessions.decoder_model_merged??e.sessions.model)?.inputNames.includes(`num_logits_to_keep`)&&!n.num_logits_to_keep&&(n.num_logits_to_keep=new G(`int64`,[1n],[])),!n.attention_mask){let e;for(let t of[`input_ids`,`inputs_embeds`,`position_ids`])if(n[t]){e=n[t].dims;break}if(!e)throw Error(`attention_mask is not provided, and unable to infer its shape from model inputs.`);n.attention_mask=jl([e[0],i+e[1]])}if(n.past_key_values){let{input_ids:e,attention_mask:t}=n;t&&t.dims[1]>e.dims[1]||i<e.dims[1]&&(n.input_ids=e.slice(null,[i,null]))}return n}function Zh(e,t,n,r){return n.past_key_values&&(t=t.map(e=>[e.at(-1)])),{...n,decoder_input_ids:Ah(t)}}function Qh(e,...t){return e.config.is_encoder_decoder?Zh(e,...t):Xh(e,...t)}function $h({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i}){let a=r.tolist().map(t=>t.reduce((t,n,r)=>(n==e&&t.push(r),t),[])),o=a.reduce((e,t)=>e+t.length,0),s=n.dims[0];if(o!==s)throw Error(`Number of tokens and features do not match: tokens: ${o}, features ${s}`);let c=0;for(let e=0;e<a.length;++e){let r=a[e],i=t[e];for(let e=0;e<r.length;++e)i[r[e]].data.set(n[c++].data)}return{inputs_embeds:t,attention_mask:i}}function eg({image_token_id:e,inputs_embeds:t,image_features:n,input_ids:r,attention_mask:i}){return $h({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i})}function tg({audio_token_id:e,inputs_embeds:t,audio_features:n,input_ids:r,attention_mask:i}){return $h({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i})}async function ng(e,t,n){return Object.fromEntries(await Promise.all(Object.keys(t).map(async r=>[r,await pc(e,t[r],!1,n)])))}var rg={};Fr(rg,{ASTForAudioClassification:()=>bg,ASTModel:()=>yg,ASTPreTrainedModel:()=>vg,AfmoeForCausalLM:()=>mg,AfmoeModel:()=>pg,AfmoePreTrainedModel:()=>fg,AlbertForMaskedLM:()=>cg,AlbertForQuestionAnswering:()=>sg,AlbertForSequenceClassification:()=>og,AlbertModel:()=>ag,AlbertPreTrainedModel:()=>ig,ApertusForCausalLM:()=>dg,ApertusModel:()=>ug,ApertusPreTrainedModel:()=>lg,ArceeForCausalLM:()=>_g,ArceeModel:()=>gg,ArceePreTrainedModel:()=>hg,BartForConditionalGeneration:()=>Cg,BartForSequenceClassification:()=>wg,BartModel:()=>Sg,BartPretrainedModel:()=>xg,BeitForImageClassification:()=>Dg,BeitModel:()=>Eg,BeitPreTrainedModel:()=>Tg,BertForMaskedLM:()=>Ag,BertForQuestionAnswering:()=>Ng,BertForSequenceClassification:()=>jg,BertForTokenClassification:()=>Mg,BertModel:()=>kg,BertPreTrainedModel:()=>Og,BlenderbotForConditionalGeneration:()=>Ig,BlenderbotModel:()=>Fg,BlenderbotPreTrainedModel:()=>Pg,BlenderbotSmallForConditionalGeneration:()=>zg,BlenderbotSmallModel:()=>Rg,BlenderbotSmallPreTrainedModel:()=>Lg,BloomForCausalLM:()=>Hg,BloomModel:()=>Vg,BloomPreTrainedModel:()=>Bg,CHMv2ForDepthEstimation:()=>n_,CHMv2PreTrainedModel:()=>t_,CLIPModel:()=>c_,CLIPPreTrainedModel:()=>s_,CLIPSegForImageSegmentation:()=>h_,CLIPSegModel:()=>m_,CLIPSegPreTrainedModel:()=>p_,CLIPTextModel:()=>l_,CLIPTextModelWithProjection:()=>u_,CLIPVisionModel:()=>d_,CLIPVisionModelWithProjection:()=>f_,CamembertForMaskedLM:()=>Gg,CamembertForQuestionAnswering:()=>Jg,CamembertForSequenceClassification:()=>Kg,CamembertForTokenClassification:()=>qg,CamembertModel:()=>Wg,CamembertPreTrainedModel:()=>Ug,ChatterboxModel:()=>Qg,ChatterboxPreTrainedModel:()=>Zg,ChineseCLIPModel:()=>e_,ChineseCLIPPreTrainedModel:()=>$g,ClapAudioModelWithProjection:()=>o_,ClapModel:()=>i_,ClapPreTrainedModel:()=>r_,ClapTextModelWithProjection:()=>a_,CodeGenForCausalLM:()=>v_,CodeGenModel:()=>__,CodeGenPreTrainedModel:()=>g_,Cohere2ForCausalLM:()=>w_,Cohere2Model:()=>C_,Cohere2PreTrainedModel:()=>S_,CohereAsrForConditionalGeneration:()=>D_,CohereAsrModel:()=>E_,CohereAsrPreTrainedModel:()=>T_,CohereForCausalLM:()=>x_,CohereModel:()=>b_,CoherePreTrainedModel:()=>y_,ConvBertForMaskedLM:()=>A_,ConvBertForQuestionAnswering:()=>N_,ConvBertForSequenceClassification:()=>j_,ConvBertForTokenClassification:()=>M_,ConvBertModel:()=>k_,ConvBertPreTrainedModel:()=>O_,ConvNextForImageClassification:()=>I_,ConvNextModel:()=>F_,ConvNextPreTrainedModel:()=>P_,ConvNextV2ForImageClassification:()=>z_,ConvNextV2Model:()=>R_,ConvNextV2PreTrainedModel:()=>L_,DFineForObjectDetection:()=>K_,DFineModel:()=>G_,DFinePreTrainedModel:()=>W_,DINOv3ConvNextModel:()=>Iv,DINOv3ConvNextPreTrainedModel:()=>Fv,DINOv3ViTModel:()=>Rv,DINOv3ViTPreTrainedModel:()=>Lv,DPTForDepthEstimation:()=>Yv,DPTModel:()=>Jv,DPTPreTrainedModel:()=>qv,DacDecoderModel:()=>Q_,DacDecoderOutput:()=>J_,DacEncoderModel:()=>Z_,DacEncoderOutput:()=>q_,DacModel:()=>X_,DacPreTrainedModel:()=>Y_,DebertaForMaskedLM:()=>tv,DebertaForQuestionAnswering:()=>iv,DebertaForSequenceClassification:()=>nv,DebertaForTokenClassification:()=>rv,DebertaModel:()=>ev,DebertaPreTrainedModel:()=>$_,DebertaV2ForMaskedLM:()=>uv,DebertaV2ForQuestionAnswering:()=>pv,DebertaV2ForSequenceClassification:()=>dv,DebertaV2ForTokenClassification:()=>fv,DebertaV2Model:()=>lv,DebertaV2PreTrainedModel:()=>cv,DecisionTransformerModel:()=>hv,DecisionTransformerPreTrainedModel:()=>mv,DeepseekV3ForCausalLM:()=>sv,DeepseekV3Model:()=>ov,DeepseekV3PreTrainedModel:()=>av,DeiTForImageClassification:()=>vv,DeiTModel:()=>_v,DeiTPreTrainedModel:()=>gv,DepthAnythingForDepthEstimation:()=>bv,DepthAnythingPreTrainedModel:()=>yv,DepthProForDepthEstimation:()=>Sv,DepthProPreTrainedModel:()=>xv,DetrForObjectDetection:()=>Tv,DetrForSegmentation:()=>Ev,DetrModel:()=>wv,DetrObjectDetectionOutput:()=>Dv,DetrPreTrainedModel:()=>Cv,DetrSegmentationOutput:()=>Ov,Dinov2ForImageClassification:()=>jv,Dinov2Model:()=>Av,Dinov2PreTrainedModel:()=>kv,Dinov2WithRegistersForImageClassification:()=>Pv,Dinov2WithRegistersModel:()=>Nv,Dinov2WithRegistersPreTrainedModel:()=>Mv,DistilBertForMaskedLM:()=>Wv,DistilBertForQuestionAnswering:()=>Uv,DistilBertForSequenceClassification:()=>Vv,DistilBertForTokenClassification:()=>Hv,DistilBertModel:()=>Bv,DistilBertPreTrainedModel:()=>zv,DonutSwinModel:()=>Kv,DonutSwinPreTrainedModel:()=>Gv,EdgeTamModel:()=>ET,EfficientNetForImageClassification:()=>Qv,EfficientNetModel:()=>Zv,EfficientNetPreTrainedModel:()=>Xv,ElectraForMaskedLM:()=>ty,ElectraForQuestionAnswering:()=>iy,ElectraForSequenceClassification:()=>ny,ElectraForTokenClassification:()=>ry,ElectraModel:()=>ey,ElectraPreTrainedModel:()=>$v,Ernie4_5ForCausalLM:()=>sy,Ernie4_5Model:()=>oy,Ernie4_5PretrainedModel:()=>ay,EsmForMaskedLM:()=>uy,EsmForSequenceClassification:()=>dy,EsmForTokenClassification:()=>fy,EsmModel:()=>ly,EsmPreTrainedModel:()=>cy,EuroBertForMaskedLM:()=>hy,EuroBertForSequenceClassification:()=>gy,EuroBertForTokenClassification:()=>_y,EuroBertModel:()=>my,EuroBertPreTrainedModel:()=>py,ExaoneForCausalLM:()=>by,ExaoneModel:()=>yy,ExaonePreTrainedModel:()=>vy,FalconForCausalLM:()=>Cy,FalconH1ForCausalLM:()=>Ey,FalconH1Model:()=>Ty,FalconH1PreTrainedModel:()=>wy,FalconModel:()=>Sy,FalconPreTrainedModel:()=>xy,FastViTForImageClassification:()=>ky,FastViTModel:()=>Oy,FastViTPreTrainedModel:()=>Dy,Florence2ForConditionalGeneration:()=>jy,Florence2PreTrainedModel:()=>Ay,GLPNForDepthEstimation:()=>db,GLPNModel:()=>ub,GLPNPreTrainedModel:()=>lb,GPT2LMHeadModel:()=>Eb,GPT2Model:()=>Tb,GPT2PreTrainedModel:()=>wb,GPTBigCodeForCausalLM:()=>mb,GPTBigCodeModel:()=>pb,GPTBigCodePreTrainedModel:()=>fb,GPTJForCausalLM:()=>kb,GPTJModel:()=>Ob,GPTJPreTrainedModel:()=>Db,GPTNeoForCausalLM:()=>_b,GPTNeoModel:()=>gb,GPTNeoPreTrainedModel:()=>hb,GPTNeoXForCausalLM:()=>bb,GPTNeoXModel:()=>yb,GPTNeoXPreTrainedModel:()=>vb,Gemma2ForCausalLM:()=>Ly,Gemma2Model:()=>Iy,Gemma2PreTrainedModel:()=>Fy,Gemma3ForCausalLM:()=>Gy,Gemma3ForConditionalGeneration:()=>Wy,Gemma3Model:()=>Uy,Gemma3PreTrainedModel:()=>Hy,Gemma3nForCausalLM:()=>Jy,Gemma3nForConditionalGeneration:()=>qy,Gemma3nPreTrainedModel:()=>Ky,Gemma4ForCausalLM:()=>Xy,Gemma4ForConditionalGeneration:()=>Yy,GemmaForCausalLM:()=>Py,GemmaModel:()=>Ny,GemmaPreTrainedModel:()=>My,GlmForCausalLM:()=>$y,GlmModel:()=>Qy,GlmMoeDsaForCausalLM:()=>nb,GlmMoeDsaModel:()=>tb,GlmMoeDsaPreTrainedModel:()=>eb,GlmOcrForConditionalGeneration:()=>cb,GlmPreTrainedModel:()=>Zy,GptOssForCausalLM:()=>Cb,GptOssModel:()=>Sb,GptOssPreTrainedModel:()=>xb,GraniteForCausalLM:()=>Mb,GraniteModel:()=>jb,GraniteMoeHybridForCausalLM:()=>Fb,GraniteMoeHybridModel:()=>Pb,GraniteMoeHybridPreTrainedModel:()=>Nb,GranitePreTrainedModel:()=>Ab,GraniteSpeechForConditionalGeneration:()=>Rb,GroundingDinoForObjectDetection:()=>Bb,GroundingDinoPreTrainedModel:()=>zb,GroupViTModel:()=>Hb,GroupViTPreTrainedModel:()=>Vb,HeliumForCausalLM:()=>Gb,HeliumModel:()=>Wb,HeliumPreTrainedModel:()=>Ub,HieraForImageClassification:()=>Jb,HieraModel:()=>qb,HieraPreTrainedModel:()=>Kb,HubertForCTC:()=>nx,HubertForSequenceClassification:()=>rx,HubertModel:()=>tx,HubertPreTrainedModel:()=>ex,HunYuanDenseV1ForCausalLM:()=>ox,HunYuanDenseV1Model:()=>ax,HunYuanDenseV1PreTrainedModel:()=>ix,IJepaForImageClassification:()=>ux,IJepaModel:()=>lx,IJepaPreTrainedModel:()=>cx,Idefics3ForConditionalGeneration:()=>sx,JAISLMHeadModel:()=>px,JAISModel:()=>fx,JAISPreTrainedModel:()=>dx,JinaCLIPModel:()=>hx,JinaCLIPPreTrainedModel:()=>mx,JinaCLIPTextModel:()=>gx,JinaCLIPVisionModel:()=>_x,Lfm2ForCausalLM:()=>bx,Lfm2Model:()=>yx,Lfm2MoeForCausalLM:()=>wx,Lfm2MoeModel:()=>Cx,Lfm2MoePreTrainedModel:()=>Sx,Lfm2PreTrainedModel:()=>vx,Lfm2VlForConditionalGeneration:()=>Tx,LightOnOcrForConditionalGeneration:()=>xx,LiteWhisperForConditionalGeneration:()=>FD,Llama4ForCausalLM:()=>Ax,Llama4PreTrainedModel:()=>kx,LlamaForCausalLM:()=>Ox,LlamaModel:()=>Dx,LlamaPreTrainedModel:()=>Ex,LlavaForConditionalGeneration:()=>zy,LlavaOnevisionForConditionalGeneration:()=>zy,LlavaPreTrainedModel:()=>Ry,LlavaQwen2ForCausalLM:()=>Vy,LongT5ForConditionalGeneration:()=>Nx,LongT5Model:()=>Mx,LongT5PreTrainedModel:()=>jx,M2M100ForConditionalGeneration:()=>Ix,M2M100Model:()=>Fx,M2M100PreTrainedModel:()=>Px,MBartForCausalLM:()=>qx,MBartForConditionalGeneration:()=>Gx,MBartForSequenceClassification:()=>Kx,MBartModel:()=>Wx,MBartPreTrainedModel:()=>Ux,MPNetForMaskedLM:()=>nC,MPNetForQuestionAnswering:()=>aC,MPNetForSequenceClassification:()=>rC,MPNetForTokenClassification:()=>iC,MPNetModel:()=>tC,MPNetPreTrainedModel:()=>eC,MT5ForConditionalGeneration:()=>dC,MT5Model:()=>uC,MT5PreTrainedModel:()=>lC,MarianMTModel:()=>zx,MarianModel:()=>Rx,MarianPreTrainedModel:()=>Lx,MaskFormerForInstanceSegmentation:()=>Hx,MaskFormerModel:()=>Vx,MaskFormerPreTrainedModel:()=>Bx,Metric3DForDepthEstimation:()=>Yx,Metric3DPreTrainedModel:()=>Jx,Metric3Dv2ForDepthEstimation:()=>Zx,Metric3Dv2PreTrainedModel:()=>Xx,MgpstrForSceneTextRecognition:()=>eS,MgpstrModelOutput:()=>Qx,MgpstrPreTrainedModel:()=>$x,MimiDecoderModel:()=>oS,MimiDecoderOutput:()=>nS,MimiEncoderModel:()=>aS,MimiEncoderOutput:()=>tS,MimiModel:()=>iS,MimiPreTrainedModel:()=>rS,Mistral4ForCausalLM:()=>fS,Mistral4Model:()=>dS,Mistral4PreTrainedModel:()=>uS,MistralForCausalLM:()=>lS,MistralModel:()=>cS,MistralPreTrainedModel:()=>sS,MobileBertForMaskedLM:()=>hS,MobileBertForQuestionAnswering:()=>_S,MobileBertForSequenceClassification:()=>gS,MobileBertModel:()=>mS,MobileBertPreTrainedModel:()=>pS,MobileLLMForCausalLM:()=>bS,MobileLLMModel:()=>yS,MobileLLMPreTrainedModel:()=>vS,MobileNetV1ForImageClassification:()=>CS,MobileNetV1ForSemanticSegmentation:()=>wS,MobileNetV1Model:()=>SS,MobileNetV1PreTrainedModel:()=>xS,MobileNetV2ForImageClassification:()=>DS,MobileNetV2ForSemanticSegmentation:()=>OS,MobileNetV2Model:()=>ES,MobileNetV2PreTrainedModel:()=>TS,MobileNetV3ForImageClassification:()=>jS,MobileNetV3ForSemanticSegmentation:()=>MS,MobileNetV3Model:()=>AS,MobileNetV3PreTrainedModel:()=>kS,MobileNetV4ForImageClassification:()=>FS,MobileNetV4ForSemanticSegmentation:()=>IS,MobileNetV4Model:()=>PS,MobileNetV4PreTrainedModel:()=>NS,MobileViTForImageClassification:()=>zS,MobileViTModel:()=>RS,MobileViTPreTrainedModel:()=>LS,MobileViTV2ForImageClassification:()=>HS,MobileViTV2Model:()=>VS,MobileViTV2PreTrainedModel:()=>BS,ModernBertDecoderForCausalLM:()=>XS,ModernBertDecoderModel:()=>YS,ModernBertDecoderPreTrainedModel:()=>JS,ModernBertForMaskedLM:()=>GS,ModernBertForSequenceClassification:()=>KS,ModernBertForTokenClassification:()=>qS,ModernBertModel:()=>WS,ModernBertPreTrainedModel:()=>US,Moondream1ForConditionalGeneration:()=>By,MoonshineForConditionalGeneration:()=>$S,MoonshineModel:()=>QS,MoonshinePreTrainedModel:()=>ZS,MptForCausalLM:()=>cC,MptModel:()=>sC,MptPreTrainedModel:()=>oC,MultiModalityCausalLM:()=>pC,MultiModalityPreTrainedModel:()=>fC,MusicgenForCausalLM:()=>gC,MusicgenForConditionalGeneration:()=>_C,MusicgenModel:()=>hC,MusicgenPreTrainedModel:()=>mC,NanoChatForCausalLM:()=>bC,NanoChatModel:()=>yC,NanoChatPreTrainedModel:()=>vC,NemotronHForCausalLM:()=>CC,NemotronHModel:()=>SC,NemotronHPreTrainedModel:()=>xC,NeoBertForMaskedLM:()=>EC,NeoBertForQuestionAnswering:()=>kC,NeoBertForSequenceClassification:()=>DC,NeoBertForTokenClassification:()=>OC,NeoBertModel:()=>TC,NeoBertPreTrainedModel:()=>wC,NomicBertModel:()=>jC,NomicBertPreTrainedModel:()=>AC,OPTForCausalLM:()=>QC,OPTModel:()=>ZC,OPTPreTrainedModel:()=>XC,Olmo2ForCausalLM:()=>LC,Olmo2Model:()=>IC,Olmo2PreTrainedModel:()=>FC,Olmo3ForCausalLM:()=>BC,Olmo3Model:()=>zC,Olmo3PreTrainedModel:()=>RC,OlmoForCausalLM:()=>PC,OlmoHybridForCausalLM:()=>UC,OlmoHybridModel:()=>HC,OlmoHybridPreTrainedModel:()=>VC,OlmoModel:()=>NC,OlmoPreTrainedModel:()=>MC,OpenAIPrivacyFilterForTokenClassification:()=>KC,OpenAIPrivacyFilterModel:()=>GC,OpenAIPrivacyFilterPreTrainedModel:()=>WC,OpenELMForCausalLM:()=>YC,OpenELMModel:()=>JC,OpenELMPreTrainedModel:()=>qC,OwlViTForObjectDetection:()=>iw,OwlViTModel:()=>rw,OwlViTPreTrainedModel:()=>nw,Owlv2ForObjectDetection:()=>tw,Owlv2Model:()=>ew,Owlv2PreTrainedModel:()=>$C,PaliGemmaForConditionalGeneration:()=>aw,ParakeetForCTC:()=>sw,ParakeetPreTrainedModel:()=>ow,PatchTSMixerForPrediction:()=>uw,PatchTSMixerModel:()=>lw,PatchTSMixerPreTrainedModel:()=>cw,PatchTSTForPrediction:()=>pw,PatchTSTModel:()=>fw,PatchTSTPreTrainedModel:()=>dw,Phi3ForCausalLM:()=>yw,Phi3Model:()=>vw,Phi3PreTrainedModel:()=>_w,Phi3VForCausalLM:()=>xw,Phi3VPreTrainedModel:()=>bw,PhiForCausalLM:()=>gw,PhiModel:()=>hw,PhiPreTrainedModel:()=>mw,PreTrainedModel:()=>$,PvtForImageClassification:()=>ww,PvtModel:()=>Cw,PvtPreTrainedModel:()=>Sw,PyAnnoteForAudioFrameClassification:()=>Dw,PyAnnoteModel:()=>Ew,PyAnnotePreTrainedModel:()=>Tw,Qwen2ForCausalLM:()=>Aw,Qwen2Model:()=>kw,Qwen2MoeForCausalLM:()=>Nw,Qwen2MoeModel:()=>Mw,Qwen2MoePreTrainedModel:()=>jw,Qwen2PreTrainedModel:()=>Ow,Qwen2VLForCausalLM:()=>ab,Qwen2VLForConditionalGeneration:()=>ib,Qwen2VLPreTrainedModel:()=>rb,Qwen2_5_VLForCausalLM:()=>sb,Qwen2_5_VLForConditionalGeneration:()=>ob,Qwen3ForCausalLM:()=>Iw,Qwen3Model:()=>Fw,Qwen3MoeForCausalLM:()=>zw,Qwen3MoeModel:()=>Rw,Qwen3MoePreTrainedModel:()=>Lw,Qwen3NextForCausalLM:()=>Hw,Qwen3NextModel:()=>Vw,Qwen3NextPreTrainedModel:()=>Bw,Qwen3PreTrainedModel:()=>Pw,Qwen3VLForCausalLM:()=>Ww,Qwen3VLForConditionalGeneration:()=>Uw,Qwen3VLMoeForCausalLM:()=>Kw,Qwen3VLMoeForConditionalGeneration:()=>Gw,Qwen3_5ForCausalLM:()=>Jw,Qwen3_5ForConditionalGeneration:()=>qw,Qwen3_5MoeForCausalLM:()=>Xw,Qwen3_5MoeForConditionalGeneration:()=>Yw,RFDetrForObjectDetection:()=>nT,RFDetrModel:()=>tT,RFDetrObjectDetectionOutput:()=>rT,RFDetrPreTrainedModel:()=>eT,RTDetrForObjectDetection:()=>H_,RTDetrModel:()=>V_,RTDetrObjectDetectionOutput:()=>U_,RTDetrPreTrainedModel:()=>B_,RTDetrV2ForObjectDetection:()=>vT,RTDetrV2Model:()=>_T,RTDetrV2ObjectDetectionOutput:()=>yT,RTDetrV2PreTrainedModel:()=>gT,ResNetForImageClassification:()=>$w,ResNetModel:()=>Qw,ResNetPreTrainedModel:()=>Zw,RoFormerForMaskedLM:()=>fT,RoFormerForQuestionAnswering:()=>hT,RoFormerForSequenceClassification:()=>pT,RoFormerForTokenClassification:()=>mT,RoFormerModel:()=>dT,RoFormerPreTrainedModel:()=>uT,RobertaForMaskedLM:()=>oT,RobertaForQuestionAnswering:()=>lT,RobertaForSequenceClassification:()=>sT,RobertaForTokenClassification:()=>cT,RobertaModel:()=>aT,RobertaPreTrainedModel:()=>iT,Sam2ImageSegmentationOutput:()=>CT,Sam2Model:()=>TT,Sam2PreTrainedModel:()=>wT,Sam3TrackerModel:()=>DT,SamImageSegmentationOutput:()=>bT,SamModel:()=>ST,SamPreTrainedModel:()=>xT,SapiensForDepthEstimation:()=>AT,SapiensForNormalEstimation:()=>jT,SapiensForSemanticSegmentation:()=>kT,SapiensPreTrainedModel:()=>OT,SegformerForImageClassification:()=>PT,SegformerForSemanticSegmentation:()=>FT,SegformerModel:()=>NT,SegformerPreTrainedModel:()=>MT,SiglipModel:()=>LT,SiglipPreTrainedModel:()=>IT,SiglipTextModel:()=>RT,SiglipVisionModel:()=>zT,SmolLM3ForCausalLM:()=>HT,SmolLM3Model:()=>VT,SmolLM3PreTrainedModel:()=>BT,SmolVLMForConditionalGeneration:()=>UT,SnacDecoderModel:()=>qT,SnacEncoderModel:()=>KT,SnacModel:()=>GT,SnacPreTrainedModel:()=>WT,SolarOpenForCausalLM:()=>XT,SolarOpenModel:()=>YT,SolarOpenPreTrainedModel:()=>JT,SpeechT5ForSpeechToText:()=>$T,SpeechT5ForTextToSpeech:()=>eE,SpeechT5HifiGan:()=>tE,SpeechT5Model:()=>QT,SpeechT5PreTrainedModel:()=>ZT,SqueezeBertForMaskedLM:()=>iE,SqueezeBertForQuestionAnswering:()=>oE,SqueezeBertForSequenceClassification:()=>aE,SqueezeBertModel:()=>rE,SqueezeBertPreTrainedModel:()=>nE,StableLmForCausalLM:()=>lE,StableLmModel:()=>cE,StableLmPreTrainedModel:()=>sE,Starcoder2ForCausalLM:()=>fE,Starcoder2Model:()=>dE,Starcoder2PreTrainedModel:()=>uE,StyleTextToSpeech2Model:()=>mE,StyleTextToSpeech2PreTrainedModel:()=>pE,SupertonicForConditionalGeneration:()=>gE,SupertonicPreTrainedModel:()=>hE,Swin2SRForImageSuperResolution:()=>CE,Swin2SRModel:()=>SE,Swin2SRPreTrainedModel:()=>xE,SwinForImageClassification:()=>yE,SwinForSemanticSegmentation:()=>bE,SwinModel:()=>vE,SwinPreTrainedModel:()=>_E,T5ForConditionalGeneration:()=>EE,T5Model:()=>TE,T5PreTrainedModel:()=>wE,TableTransformerForObjectDetection:()=>kE,TableTransformerModel:()=>OE,TableTransformerObjectDetectionOutput:()=>AE,TableTransformerPreTrainedModel:()=>DE,TrOCRForCausalLM:()=>ME,TrOCRPreTrainedModel:()=>jE,UltravoxModel:()=>Lb,UltravoxPreTrainedModel:()=>Ib,UniSpeechForCTC:()=>FE,UniSpeechForSequenceClassification:()=>IE,UniSpeechModel:()=>PE,UniSpeechPreTrainedModel:()=>NE,UniSpeechSatForAudioFrameClassification:()=>VE,UniSpeechSatForCTC:()=>zE,UniSpeechSatForSequenceClassification:()=>BE,UniSpeechSatModel:()=>RE,UniSpeechSatPreTrainedModel:()=>LE,VaultGemmaForCausalLM:()=>WE,VaultGemmaModel:()=>UE,VaultGemmaPreTrainedModel:()=>HE,ViTForImageClassification:()=>JE,ViTMAEModel:()=>XE,ViTMAEPreTrainedModel:()=>YE,ViTMSNForImageClassification:()=>$E,ViTMSNModel:()=>QE,ViTMSNPreTrainedModel:()=>ZE,ViTModel:()=>qE,ViTPreTrainedModel:()=>KE,VisionEncoderDecoderModel:()=>GE,VitMatteForImageMatting:()=>tD,VitMattePreTrainedModel:()=>eD,VitPoseForPoseEstimation:()=>rD,VitPosePreTrainedModel:()=>nD,VitsModel:()=>oD,VitsModelOutput:()=>iD,VitsPreTrainedModel:()=>aD,VoxtralForConditionalGeneration:()=>sD,VoxtralRealtimeForConditionalGeneration:()=>_D,VoxtralRealtimePreTrainedModel:()=>gD,Wav2Vec2BertForCTC:()=>bD,Wav2Vec2BertForSequenceClassification:()=>xD,Wav2Vec2BertModel:()=>yD,Wav2Vec2BertPreTrainedModel:()=>vD,Wav2Vec2ForAudioFrameClassification:()=>$b,Wav2Vec2ForCTC:()=>Zb,Wav2Vec2ForSequenceClassification:()=>Qb,Wav2Vec2Model:()=>Xb,Wav2Vec2PreTrainedModel:()=>Yb,WavLMForAudioFrameClassification:()=>OD,WavLMForCTC:()=>TD,WavLMForSequenceClassification:()=>ED,WavLMForXVector:()=>DD,WavLMModel:()=>wD,WavLMPreTrainedModel:()=>CD,WeSpeakerResNetModel:()=>AD,WeSpeakerResNetPreTrainedModel:()=>kD,WhisperForConditionalGeneration:()=>PD,WhisperModel:()=>ND,WhisperPreTrainedModel:()=>MD,XLMForQuestionAnswering:()=>VD,XLMForSequenceClassification:()=>zD,XLMForTokenClassification:()=>BD,XLMModel:()=>LD,XLMPreTrainedModel:()=>ID,XLMRobertaForMaskedLM:()=>WD,XLMRobertaForQuestionAnswering:()=>qD,XLMRobertaForSequenceClassification:()=>GD,XLMRobertaForTokenClassification:()=>KD,XLMRobertaModel:()=>UD,XLMRobertaPreTrainedModel:()=>HD,XLMWithLMHeadModel:()=>RD,XVectorOutput:()=>SD,YolosForObjectDetection:()=>XD,YolosModel:()=>YD,YolosObjectDetectionOutput:()=>ZD,YolosPreTrainedModel:()=>JD,YoutuForCausalLM:()=>eO,YoutuModel:()=>$D,YoutuPreTrainedModel:()=>QD});var ig=class extends ${},ag=class extends ig{},og=class extends ig{async _call(e){return new Z(await super._call(e))}},sg=class extends ig{async _call(e){return new Ym(await super._call(e))}},cg=class extends ig{async _call(e){return new Jm(await super._call(e))}},lg=class extends ${},ug=class extends lg{},dg=class extends lg{},fg=class extends ${},pg=class extends fg{},mg=class extends fg{},hg=class extends ${},gg=class extends hg{},_g=class extends hg{},vg=class extends ${},yg=class extends vg{},bg=class extends vg{},xg=class extends ${},Sg=class extends xg{},Cg=class extends xg{},wg=class extends xg{async _call(e){return new Z(await super._call(e))}},Tg=class extends ${},Eg=class extends Tg{},Dg=class extends Tg{async _call(e){return new Z(await super._call(e))}},Og=class extends ${},kg=class extends Og{},Ag=class extends Og{async _call(e){return new Jm(await super._call(e))}},jg=class extends Og{async _call(e){return new Z(await super._call(e))}},Mg=class extends Og{async _call(e){return new qm(await super._call(e))}},Ng=class extends Og{async _call(e){return new Ym(await super._call(e))}},Pg=class extends ${},Fg=class extends Pg{},Ig=class extends Pg{},Lg=class extends ${},Rg=class extends Lg{},zg=class extends Lg{},Bg=class extends ${},Vg=class extends Bg{},Hg=class extends Bg{},Ug=class extends ${},Wg=class extends Ug{},Gg=class extends Ug{async _call(e){return new Jm(await super._call(e))}},Kg=class extends Ug{async _call(e){return new Z(await super._call(e))}},qg=class extends Ug{async _call(e){return new qm(await super._call(e))}},Jg=class extends Ug{async _call(e){return new Ym(await super._call(e))}},Yg=4299n,Xg=6561n,Zg=class extends ${forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`audio_values`,`exaggeration`,`audio_features`,`audio_tokens`,`speaker_embeddings`,`speaker_features`,`past_key_values`];main_input_name=`input_ids`;_return_dict_in_generate_keys=[`audio_tokens`,`speaker_embeddings`,`speaker_features`]},Qg=class extends Zg{async encode_speech(e){return X(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:n=null,exaggeration:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,audio_features:l=null,audio_tokens:u=null,speaker_embeddings:d=null,speaker_features:f=null,...p}){let m;if(!a){let s=this.sessions.embed_tokens.inputNames,c={input_ids:e};if(s.includes(`exaggeration`)){if(!(r instanceof G)){let t=e.dims[0];if(r==null)r=kl([t],.5);else if(typeof r==`number`)r=kl([t],r);else if(Array.isArray(r))r=new G(`float32`,r,[t]);else throw Error("Unsupported type for `exaggeration` input")}c.exaggeration=r}if(s.includes(`position_ids`)&&(c.position_ids=i),{inputs_embeds:a}=await X(this.sessions.embed_tokens,c),l&&u&&d&&f&&(m={audio_features:l,audio_tokens:u,speaker_embeddings:d,speaker_features:f}),m||n)m??=await this.encode_speech(n),a=Sl([m.audio_features,a],1),t=jl([a.dims[0],a.dims[1]]);else{let e=a.dims[1];if(!o||e!==1)throw Error(`Incorrect state encountered during generation.`);let n=o.get_seq_length();t=jl([a.dims[0],n+e])}}return{...await Wh(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:s,logits_processor:c},!1),...m}}prepare_inputs_for_generation(e,t,n){return!t.position_ids&&this.sessions.embed_tokens.inputNames.includes(`position_ids`)&&(t.input_ids.dims[1]===1?t.position_ids=new G(`int64`,Array.from({length:e.length},(t,n)=>e[n].length-e[n].findLastIndex(e=>e==Xg)-1),[e.length,1]):t.position_ids=new G(`int64`,t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=Xg?0:t++)}).flat(),t.input_ids.dims)),t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),Xh(this,e,t,n)}async generate(e){let{sequences:t,audio_tokens:n,speaker_embeddings:r,speaker_features:i}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=Sl([n,a,kl([a.dims[0],3],Yg)],1),{waveform:s}=await X(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:i,speaker_embeddings:r});return s}},$g=class extends ${},e_=class extends $g{},t_=class extends ${},n_=class extends t_{},r_=class extends ${},i_=class extends r_{},a_=class extends r_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},o_=class extends r_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`audio_model`})}},s_=class extends ${},c_=class extends s_{},l_=class extends s_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},u_=class extends s_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},d_=class extends s_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},f_=class extends s_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},p_=class extends ${},m_=class extends p_{},h_=class extends p_{},g_=class extends ${},__=class extends g_{},v_=class extends g_{},y_=class extends ${},b_=class extends y_{},x_=class extends y_{},S_=class extends ${},C_=class extends S_{},w_=class extends S_{},T_=class extends ${requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},E_=class extends T_{},D_=class extends T_{},O_=class extends ${},k_=class extends O_{},A_=class extends O_{async _call(e){return new Jm(await super._call(e))}},j_=class extends O_{async _call(e){return new Z(await super._call(e))}},M_=class extends O_{async _call(e){return new qm(await super._call(e))}},N_=class extends O_{async _call(e){return new Ym(await super._call(e))}},P_=class extends ${},F_=class extends P_{},I_=class extends P_{async _call(e){return new Z(await super._call(e))}},L_=class extends ${},R_=class extends L_{},z_=class extends L_{async _call(e){return new Z(await super._call(e))}},B_=class extends ${},V_=class extends B_{},H_=class extends B_{async _call(e){return new U_(await super._call(e))}},U_=class extends Km{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},W_=class extends ${},G_=class extends W_{},K_=class extends W_{async _call(e){return new U_(await super._call(e))}},q_=class extends Km{constructor({audio_codes:e}){super(),this.audio_codes=e}},J_=class extends Km{constructor({audio_values:e}){super(),this.audio_values=e}},Y_=class extends ${main_input_name=`input_values`;forward_params=[`input_values`]},X_=class extends Y_{async encode(e){return new q_(await X(this.sessions.encoder_model,e))}async decode(e){return new J_(await X(this.sessions.decoder_model,e))}},Z_=class extends Y_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},Q_=class extends Y_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},$_=class extends ${},ev=class extends $_{},tv=class extends $_{async _call(e){return new Jm(await super._call(e))}},nv=class extends $_{async _call(e){return new Z(await super._call(e))}},rv=class extends $_{async _call(e){return new qm(await super._call(e))}},iv=class extends $_{async _call(e){return new Ym(await super._call(e))}},av=class extends ${},ov=class extends av{},sv=class extends av{},cv=class extends ${},lv=class extends cv{},uv=class extends cv{async _call(e){return new Jm(await super._call(e))}},dv=class extends cv{async _call(e){return new Z(await super._call(e))}},fv=class extends cv{async _call(e){return new qm(await super._call(e))}},pv=class extends cv{async _call(e){return new Ym(await super._call(e))}},mv=class extends ${},hv=class extends mv{},gv=class extends ${},_v=class extends gv{},vv=class extends gv{async _call(e){return new Z(await super._call(e))}},yv=class extends ${},bv=class extends yv{},xv=class extends ${},Sv=class extends xv{},Cv=class extends ${},wv=class extends Cv{},Tv=class extends Cv{async _call(e){return new Dv(await super._call(e))}},Ev=class extends Cv{async _call(e){return new Ov(await super._call(e))}},Dv=class extends Km{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},Ov=class extends Km{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}},kv=class extends ${},Av=class extends kv{},jv=class extends kv{async _call(e){return new Z(await super._call(e))}},Mv=class extends ${},Nv=class extends Mv{},Pv=class extends Mv{async _call(e){return new Z(await super._call(e))}},Fv=class extends ${},Iv=class extends Fv{},Lv=class extends ${},Rv=class extends Lv{},zv=class extends ${},Bv=class extends zv{},Vv=class extends zv{async _call(e){return new Z(await super._call(e))}},Hv=class extends zv{async _call(e){return new qm(await super._call(e))}},Uv=class extends zv{async _call(e){return new Ym(await super._call(e))}},Wv=class extends zv{async _call(e){return new Jm(await super._call(e))}},Gv=class extends ${},Kv=class extends Gv{},qv=class extends ${},Jv=class extends qv{},Yv=class extends qv{},Xv=class extends ${},Zv=class extends Xv{},Qv=class extends Xv{async _call(e){return new Z(await super._call(e))}},$v=class extends ${},ey=class extends $v{},ty=class extends $v{async _call(e){return new Jm(await super._call(e))}},ny=class extends $v{async _call(e){return new Z(await super._call(e))}},ry=class extends $v{async _call(e){return new qm(await super._call(e))}},iy=class extends $v{async _call(e){return new Ym(await super._call(e))}},ay=class extends ${},oy=class extends ay{},sy=class extends ay{},cy=class extends ${},ly=class extends cy{},uy=class extends cy{async _call(e){return new Jm(await super._call(e))}},dy=class extends cy{async _call(e){return new Z(await super._call(e))}},fy=class extends cy{async _call(e){return new qm(await super._call(e))}},py=class extends ${},my=class extends py{},hy=class extends py{async _call(e){return new Jm(await super._call(e))}},gy=class extends py{async _call(e){return new Z(await super._call(e))}},_y=class extends py{async _call(e){return new qm(await super._call(e))}},vy=class extends ${},yy=class extends vy{},by=class extends vy{},xy=class extends ${},Sy=class extends xy{},Cy=class extends xy{},wy=class extends ${},Ty=class extends wy{},Ey=class extends wy{},Dy=class extends ${},Oy=class extends Dy{},ky=class extends Dy{async _call(e){return new Z(await super._call(e))}},Ay=class extends ${forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`pixel_values`,`encoder_outputs`,`decoder_input_ids`,`decoder_inputs_embeds`,`decoder_attention_mask`,`past_key_values`];main_input_name=`inputs_embeds`},jy=class extends Ay{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:n,attention_mask:r}){return{inputs_embeds:Sl([t,e],1),attention_mask:Sl([jl(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:n,attention_mask:r}){if(!e&&!t)throw Error("Either `input_ids` or `pixel_values` should be provided.");let i,a;return e&&(i=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),i&&a?{inputs_embeds:n,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:i,image_features:a,input_ids:e,attention_mask:r}):n=i||a,{inputs_embeds:n,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:n,decoder_input_ids:r,decoder_attention_mask:i,encoder_outputs:a,past_key_values:o,inputs_embeds:s,decoder_inputs_embeds:c}){if(s||({inputs_embeds:s,attention_mask:n}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n})),!a){let{last_hidden_state:e}=await Rh(this,{inputs_embeds:s,attention_mask:n});a=e}if(!c){if(!r)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:r})}let l={inputs_embeds:c,attention_mask:i,encoder_attention_mask:n,encoder_hidden_states:a,past_key_values:o};return await Wh(this,l,!0)}},My=class extends ${},Ny=class extends My{},Py=class extends My{},Fy=class extends ${},Iy=class extends Fy{},Ly=class extends Fy{},Ry=class extends ${forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`position_ids`,`past_key_values`]},zy=class extends Ry{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return eg({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:n})}},By=class extends zy{},Vy=class extends zy{},Hy=class extends ${},Uy=class extends Hy{},Wy=class extends zy{},Gy=class extends Wy{},Ky=class extends ${forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`input_features`,`input_features_mask`,`past_key_values`]},qy=class extends Ky{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,input_features:r=null,input_features_mask:i=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:s=null,past_key_values:c=null,generation_config:l=null,logits_processor:u=null,...d}){if((!o||!s)&&({inputs_embeds:o,per_layer_inputs:s}=await X(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(n){let{image_features:r}=await this._encode_vision({pixel_values:n,...d});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:r,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(r){let{audio_features:n}=await X(this.sessions.audio_encoder,{input_features:r,input_features_mask:i});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:n,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await Wh(this,{inputs_embeds:o,per_layer_inputs:s,past_key_values:c,attention_mask:t,position_ids:a,generation_config:l,logits_processor:u},!0)}_encode_vision(e){return X(this.sessions.vision_encoder,{pixel_values:e.pixel_values})}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return eg({image_token_id:this.config.image_token_id,...e,image_features:n})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return tg({audio_token_id:this.config.audio_token_id,...e,audio_features:n})}},Jy=class extends qy{},Yy=class extends qy{forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`image_position_ids`,`input_features`,`input_features_mask`,`past_key_values`];_encode_vision(e){return X(this.sessions.vision_encoder,{pixel_values:e.pixel_values,pixel_position_ids:e.image_position_ids})}},Xy=class extends Yy{},Zy=class extends ${},Qy=class extends Zy{},$y=class extends Zy{},eb=class extends ${},tb=class extends eb{},nb=class extends eb{},rb=class extends ${forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`,`pixel_values`,`image_grid_thw`]},ib=class extends rb{image_grid_thw_name=`grid_thw`;_get_text_only_rope_index(e,t){if(t){let{data:e,dims:n}=Jh(t),r=BigInt64Array.from({length:3*e.length},(t,n)=>e[n%e.length]),i=Array.from({length:n[0]},(t,r)=>yc(e.subarray(n[1]*r,n[1]*(r+1)))[0]+1n+BigInt(n[1]));return[new G(`int64`,r,[3,...n]),new G(`int64`,i,[i.length,1])]}else{let[t,n]=e.dims;return[new G(`int64`,BigInt64Array.from({length:3*t*n},(e,r)=>BigInt(Math.floor(r%n/t))),[3,...e.dims]),Nl([t,1])]}}_reorder_and_write_positions(e,t,n,r){let i=e.reduce((e,t)=>e+t.length,0),a=Array(i),o=0;for(let t=0;t<3;++t)for(let n of e){let e=n.length/3;for(let r=t*e;r<(t+1)*e;++r)a[o++]=n[r]}let s=0;for(let e=0;e<t.length;++e)if(t[e]==1){for(let t=0;t<3;++t)n[t][r][e]=a[t*i/3+s];++s}return a}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a,video_token_id:o,vision_start_token_id:s}=this.config,c=e,l=c.reduce((e,t,n)=>(t==s&&e.push(n),e),[]).map(e=>c[e+1]),u=l.filter(e=>e==a).length,d=l.filter(e=>e==o).length,f=[],p=0,m=u,h=d;for(let e=0;e<l.length;++e){let e=c.findIndex((e,t)=>t>p&&e==a),s=c.findIndex((e,t)=>t>p&&e==o),l=m>0&&e!==-1?e:c.length+1,u=h>0&&s!==-1?s:c.length+1,d,g,_,v;l<u?([g,_,v]=t[i.image_index],++i.image_index,--m,d=l):([g,_,v]=n[i.video_index],++i.video_index,--h,d=u);let[y,b,x]=[Number(g),Math.floor(Number(_)/r),Math.floor(Number(v)/r)],S=d-p,C=f.length>0?yc(f.at(-1))[0]+1:0;f.push(Array.from({length:3*S},(e,t)=>C+t%S));let ee=S+C,w=y*b*x,T=Array.from({length:w},(e,t)=>ee+Math.floor(t/(b*x))),te=Array.from({length:w},(e,t)=>ee+Math.floor(t/x)%b),ne=Array.from({length:w},(e,t)=>ee+t%x);f.push([T,te,ne].flat()),p=d+w}if(p<c.length){let e=f.length>0?yc(f.at(-1))[0]+1:0,t=c.length-p;f.push(Array.from({length:3*t},(n,r)=>e+r%t))}return f}get_rope_index(e,t,n,r){let{vision_config:i}=this.config,a=i.spatial_merge_size??2;if(t||n){let i=e.tolist();r||=Ml(e);let o=r.tolist(),s=Array.from({length:3},()=>Array.from({length:e.dims[0]},()=>Array.from({length:e.dims[1]},()=>0))),c=t?t.tolist():[],l=n?n.tolist():[],u={image_index:0,video_index:0},d=[];for(let e=0;e<i.length;++e){let t=i[e].filter((t,n)=>o[e][n]==1),n=this._get_multimodal_rope_positions({filtered_ids:t,image_grid_thw_list:c,video_grid_thw_list:l,spatial_merge_size:a,state:u}),r=this._reorder_and_write_positions(n,o[e],s,e);d.push(yc(r)[0]+1-i[e].length)}return[new G(`int64`,s.flat(1/0),[3,e.dims[0],e.dims[1]]),new G(`int64`,d,[d.length,1])]}else return this._get_text_only_rope_index(e,r)}async encode_image({pixel_values:e,image_grid_thw:t}){return(await X(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return eg({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,n){if(!t.attention_mask||t.position_ids||!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes(`position_ids`))return t;if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(e<t.input_ids.dims[1]){let[n,r]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);t.rope_deltas=r,t.position_ids=n.slice(null,null,[e,null]),t.input_ids=t.input_ids.slice(null,[e,null])}else{t.rope_deltas||([,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask));let n=BigInt(e),r=t.rope_deltas.map(e=>n+e);t.position_ids=Cl([r,r,r],0)}}return t}},ab=class extends ib{},ob=class extends ib{image_grid_thw_name=`image_grid_thw`},sb=class extends ab{image_grid_thw_name=`image_grid_thw`},cb=class extends ob{get_vision_position_ids(e,t,n,r){let i=Math.floor(t[0]/n),a=Math.floor(t[1]/r),o=Math.floor(t[2]/r),s=a*o*i,c=Array.from({length:s},()=>e),l=Array.from({length:s},(t,n)=>e+Math.floor(n/(o*i))),u=Array.from({length:s},(t,n)=>e+n%o);return[...c,...l,...u]}_get_multimodal_rope_positions({filtered_ids:e,image_grid_thw_list:t,video_grid_thw_list:n,spatial_merge_size:r,state:i}){let{image_token_id:a}=this.config,o=[],s=0,c=+(e[0]==a);for(let t=1;t<=e.length;++t){let n=t<e.length?+(e[t]==a):-1;n!==c&&(o.push([c,s,t]),s=t,c=n)}let l=0,u=[];for(let[e,n,a]of o)if(e===0){let e=a-n;u.push(Array.from({length:3*e},(t,n)=>l+n%e)),l+=e}else{let e=t[i.image_index++].map(Number),n=e[0];u.push(this.get_vision_position_ids(l,e,n,r)),l+=Math.max(e[1],e[2])/r}return u}},lb=class extends ${},ub=class extends lb{},db=class extends lb{},fb=class extends ${},pb=class extends fb{},mb=class extends fb{},hb=class extends ${},gb=class extends hb{},_b=class extends hb{},vb=class extends ${},yb=class extends vb{},bb=class extends vb{},xb=class extends ${},Sb=class extends xb{},Cb=class extends xb{},wb=class extends ${},Tb=class extends wb{},Eb=class extends wb{},Db=class extends ${},Ob=class extends Db{},kb=class extends Db{},Ab=class extends ${},jb=class extends Ab{},Mb=class extends Ab{},Nb=class extends ${},Pb=class extends Nb{},Fb=class extends Nb{},Ib=class extends ${forward_params=[`input_ids`,`attention_mask`,`position_ids`,`audio_values`,`past_key_values`]},Lb=class extends Ib{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return tg({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:n})}},Rb=class extends Lb{forward_params=[`input_ids`,`attention_mask`,`input_features`,`past_key_values`]},zb=class extends ${},Bb=class extends zb{},Vb=class extends ${},Hb=class extends Vb{},Ub=class extends ${},Wb=class extends Ub{},Gb=class extends Ub{},Kb=class extends ${},qb=class extends Kb{},Jb=class extends Kb{async _call(e){return new Z(await super._call(e))}},Yb=class extends ${},Xb=class extends Yb{},Zb=class extends Yb{async _call(e){return new Xm(await super._call(e))}},Qb=class extends Yb{async _call(e){return new Z(await super._call(e))}},$b=class extends Yb{async _call(e){return new qm(await super._call(e))}},ex=class extends ${},tx=class extends Yb{},nx=class extends Yb{async _call(e){return new Xm(await super._call(e))}},rx=class extends Yb{async _call(e){return new Z(await super._call(e))}},ix=class extends ${},ax=class extends ix{},ox=class extends ix{},sx=class extends zy{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`position_ids`,`past_key_values`]},cx=class extends ${},lx=class extends cx{},ux=class extends cx{async _call(e){return new Z(await super._call(e))}},dx=class extends ${},fx=class extends dx{},px=class extends dx{},mx=class extends ${},hx=class extends mx{async forward(e){let t=!e.input_ids,n=!e.pixel_values;if(t&&n)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=jl([e.pixel_values.dims[0],1])),n){let{image_size:t}=this.config.vision_config;e.pixel_values=kl([0,3,t,t],0)}let{text_embeddings:r,image_embeddings:i,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),s={};return t||(s.text_embeddings=r,s.l2norm_text_embeddings=a),n||(s.image_embeddings=i,s.l2norm_image_embeddings=o),s}},gx=class extends mx{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},_x=class extends mx{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},vx=class extends ${},yx=class extends vx{},bx=class extends vx{},xx=class extends zy{},Sx=class extends ${},Cx=class extends Sx{},wx=class extends Sx{},Tx=class extends zy{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`spatial_shapes`,`position_ids`,`past_key_values`]},Ex=class extends ${},Dx=class extends Ex{},Ox=class extends Ex{},kx=class extends ${},Ax=class extends kx{},jx=class extends ${},Mx=class extends jx{},Nx=class extends jx{},Px=class extends ${},Fx=class extends Px{},Ix=class extends Px{},Lx=class extends ${},Rx=class extends Lx{},zx=class extends Lx{},Bx=class extends ${},Vx=class extends Bx{},Hx=class extends Bx{},Ux=class extends ${},Wx=class extends Ux{},Gx=class extends Ux{},Kx=class extends Ux{async _call(e){return new Z(await super._call(e))}},qx=class extends Ux{},Jx=class extends ${},Yx=class extends Jx{},Xx=class extends ${},Zx=class extends Xx{},Qx=class extends Km{constructor({char_logits:e,bpe_logits:t,wp_logits:n}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=n}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},$x=class extends ${},eS=class extends $x{async _call(e){return new Qx(await super._call(e))}},tS=class extends Km{constructor({audio_codes:e}){super(),this.audio_codes=e}},nS=class extends Km{constructor({audio_values:e}){super(),this.audio_values=e}},rS=class extends ${main_input_name=`input_values`;forward_params=[`input_values`]},iS=class extends rS{async encode(e){return new tS(await X(this.sessions.encoder_model,e))}async decode(e){return new nS(await X(this.sessions.decoder_model,e))}},aS=class extends rS{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},oS=class extends rS{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},sS=class extends ${},cS=class extends sS{},lS=class extends sS{},uS=class extends ${},dS=class extends uS{},fS=class extends uS{},pS=class extends ${},mS=class extends pS{},hS=class extends pS{async _call(e){return new Jm(await super._call(e))}},gS=class extends pS{async _call(e){return new Z(await super._call(e))}},_S=class extends pS{async _call(e){return new Ym(await super._call(e))}},vS=class extends ${},yS=class extends vS{},bS=class extends vS{},xS=class extends ${},SS=class extends xS{},CS=class extends xS{async _call(e){return new Z(await super._call(e))}},wS=class extends xS{},TS=class extends ${},ES=class extends TS{},DS=class extends TS{async _call(e){return new Z(await super._call(e))}},OS=class extends TS{},kS=class extends ${},AS=class extends kS{},jS=class extends kS{async _call(e){return new Z(await super._call(e))}},MS=class extends kS{},NS=class extends ${},PS=class extends NS{},FS=class extends NS{async _call(e){return new Z(await super._call(e))}},IS=class extends NS{},LS=class extends ${},RS=class extends LS{},zS=class extends LS{async _call(e){return new Z(await super._call(e))}},BS=class extends ${},VS=class extends BS{},HS=class extends BS{async _call(e){return new Z(await super._call(e))}},US=class extends ${},WS=class extends US{},GS=class extends US{async _call(e){return new Jm(await super._call(e))}},KS=class extends US{async _call(e){return new Z(await super._call(e))}},qS=class extends US{async _call(e){return new qm(await super._call(e))}},JS=class extends ${},YS=class extends JS{},XS=class extends JS{},ZS=class extends ${requires_attention_mask=!1;main_input_name=`input_values`;forward_params=[`input_values`,`decoder_input_ids`,`past_key_values`]},QS=class extends ZS{},$S=class extends ZS{},eC=class extends ${},tC=class extends eC{},nC=class extends eC{async _call(e){return new Jm(await super._call(e))}},rC=class extends eC{async _call(e){return new Z(await super._call(e))}},iC=class extends eC{async _call(e){return new qm(await super._call(e))}},aC=class extends eC{async _call(e){return new Ym(await super._call(e))}},oC=class extends ${},sC=class extends oC{},cC=class extends oC{},lC=class extends ${},uC=class extends lC{},dC=class extends lC{},fC=class extends ${},pC=class extends fC{forward_params=[`input_ids`,`pixel_values`,`images_seq_mask`,`images_emb_mask`,`attention_mask`,`position_ids`,`past_key_values`];constructor(...e){super(...e),this._generation_mode=`text`}async forward(e){let t=this._generation_mode??`text`,n;if(t===`text`||!e.past_key_values){let t=this.sessions.prepare_inputs_embeds;n=await X(t,xi(e,t.inputNames))}else{let t=this.sessions.gen_img_embeds;n=await X(t,xi({image_ids:e.input_ids},t.inputNames))}let r={...e,...n},i=await Wh(this,r),a=this.sessions[t===`text`?`lm_head`:`gen_head`];if(!a)throw Error(`Unable to find "${a}" generation head`);let o=await X(a,xi(i,a.inputNames));return{...n,...i,...o}}prepare_inputs_for_generation(e,t,n){let r=!!t.past_key_values;return n.guidance_scale!==null&&n.guidance_scale>1&&(r?t.input_ids=Sl([t.input_ids,t.input_ids],0):(t.input_ids=Sl([t.input_ids,Al(t.input_ids,BigInt(n.pad_token_id))],0),t.attention_mask=Sl([t.attention_mask,Al(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=kl([0,0,3,384,384],1)),r&&(t.images_seq_mask=new G(`bool`,[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new G(`bool`,[].fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode=`text`,super.generate(e)}async generate_images(e){this._generation_mode=`image`;let t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),r=this.sessions.image_decode,{decoded_image:i}=await X(r,{generated_tokens:n}),a=i.add_(1).mul_(255/2).clamp_(0,255).to(`uint8`),o=[];for(let e of a){let t=$d.fromTensor(e);o.push(t)}return o}},mC=class extends ${},hC=class extends mC{},gC=class extends mC{},_C=class extends ${forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`];_apply_and_filter_by_delay_pattern_mask(e){let[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r,a=0;for(let t=0;t<e.size;++t){if(e.data[t]==this.config.decoder.pad_token_id)continue;let o=t%n-Math.floor(t/n)%r;o>0&&o<=i&&(e.data[a++]=e.data[t])}let o=Math.floor(t/r),s=a/(o*r);return new G(e.type,e.data.slice(0,a),[o,r,s])}prepare_inputs_for_generation(e,t,n){let r=BigInt(this.config.decoder.pad_token_id),i=structuredClone(e);for(let e=0;e<i.length;++e)for(let t=0;t<i[e].length;++t)e%this.config.decoder.num_codebooks>=t&&(i[e][t]=r);return n.guidance_scale!==null&&n.guidance_scale>1&&(i=i.concat(i)),Zh(this,i,t,n)}async generate(e){let t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await X(this.sessions.encodec_decode,{audio_codes:n});return r}},vC=class extends ${},yC=class extends vC{},bC=class extends vC{},xC=class extends ${},SC=class extends xC{},CC=class extends xC{},wC=class extends ${},TC=class extends wC{},EC=class extends wC{async _call(e){return new Jm(await super._call(e))}},DC=class extends wC{async _call(e){return new Z(await super._call(e))}},OC=class extends wC{async _call(e){return new qm(await super._call(e))}},kC=class extends wC{async _call(e){return new Ym(await super._call(e))}},AC=class extends ${},jC=class extends AC{},MC=class extends ${},NC=class extends MC{},PC=class extends MC{},FC=class extends ${},IC=class extends FC{},LC=class extends FC{},RC=class extends ${},zC=class extends RC{},BC=class extends RC{},VC=class extends ${},HC=class extends VC{},UC=class extends VC{},WC=class extends ${},GC=class extends WC{},KC=class extends WC{async _call(e){return new Z(await super._call(e))}},qC=class extends ${},JC=class extends qC{},YC=class extends qC{},XC=class extends ${},ZC=class extends XC{},QC=class extends XC{},$C=class extends ${},ew=class extends $C{},tw=class extends $C{},nw=class extends ${},rw=class extends nw{},iw=class extends nw{},aw=class extends zy{},ow=class extends ${},sw=class extends ow{async _call(e){return new Xm(await super._call(e))}},cw=class extends ${},lw=class extends cw{},uw=class extends cw{},dw=class extends ${},fw=class extends dw{},pw=class extends dw{},mw=class extends ${},hw=class extends mw{},gw=class extends mw{},_w=class extends ${},vw=class extends _w{},yw=class extends _w{},bw=class extends ${forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`pixel_values`,`image_sizes`,`past_key_values`]},xw=class extends bw{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,image_sizes:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,...l}){if(!a){let t;if(n&&e.dims[1]!==1){if(!r)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:t}=await X(this.sessions.vision_encoder,{pixel_values:n,image_sizes:r}))}else{let e=this.config.normalized_config.hidden_size;t=new G(`float32`,[],[0,e])}({inputs_embeds:a}=await X(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await Wh(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:i,generation_config:s,logits_processor:c},!1)}},Sw=class extends ${},Cw=class extends Sw{},ww=class extends Sw{async _call(e){return new Z(await super._call(e))}},Tw=class extends ${},Ew=class extends Tw{},Dw=class extends Tw{async _call(e){return new qm(await super._call(e))}},Ow=class extends ${},kw=class extends Ow{},Aw=class extends Ow{},jw=class extends ${},Mw=class extends jw{},Nw=class extends jw{},Pw=class extends ${},Fw=class extends Pw{},Iw=class extends Pw{},Lw=class extends ${},Rw=class extends Lw{},zw=class extends Lw{},Bw=class extends ${},Vw=class extends Bw{},Hw=class extends Bw{},Uw=class extends ob{},Ww=class extends sb{},Gw=class extends Uw{},Kw=class extends Ww{},qw=class extends Uw{},Jw=class extends qw{},Yw=class extends qw{},Xw=class extends Jw{},Zw=class extends ${},Qw=class extends Zw{},$w=class extends Zw{async _call(e){return new Z(await super._call(e))}},eT=class extends ${},tT=class extends eT{},nT=class extends eT{async _call(e){return new rT(await super._call(e))}},rT=class extends U_{},iT=class extends ${},aT=class extends iT{},oT=class extends iT{async _call(e){return new Jm(await super._call(e))}},sT=class extends iT{async _call(e){return new Z(await super._call(e))}},cT=class extends iT{async _call(e){return new qm(await super._call(e))}},lT=class extends iT{async _call(e){return new Ym(await super._call(e))}},uT=class extends ${},dT=class extends uT{},fT=class extends uT{async _call(e){return new Jm(await super._call(e))}},pT=class extends uT{async _call(e){return new Z(await super._call(e))}},mT=class extends uT{async _call(e){return new qm(await super._call(e))}},hT=class extends uT{async _call(e){return new Ym(await super._call(e))}},gT=class extends ${},_T=class extends gT{},vT=class extends gT{async _call(e){return new yT(await super._call(e))}},yT=class extends U_{},bT=class extends Km{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},xT=class extends ${},ST=class extends xT{async get_image_embeddings({pixel_values:e}){return await Rh(this,{pixel_values:e})}async forward(e){e=!e.image_embeddings||!e.image_positional_embeddings?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_labels??=jl(e.input_points.dims.slice(0,-1));let t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await X(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new bT(await super._call(e))}},CT=class extends Km{constructor({iou_scores:e,pred_masks:t,object_score_logits:n}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=n}},wT=class extends ${},TT=class extends wT{async get_image_embeddings({pixel_values:e}){return await Rh(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(e=Array.from({length:t},(e,t)=>`image_embeddings.${t}`).some(t=>!e[t])?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let t=e.input_points.dims;e.input_labels??=jl(t.slice(0,-1)),e.input_boxes??=kl([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=kl([t[0],t[1],0],-1n),e.input_points=kl([t[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder;return await X(n,xi(e,n.inputNames))}async _call(e){return new CT(await super._call(e))}},ET=class extends TT{},DT=class extends TT{},OT=class extends ${},kT=class extends OT{},AT=class extends OT{},jT=class extends OT{},MT=class extends ${},NT=class extends MT{},PT=class extends MT{},FT=class extends MT{},IT=class extends ${},LT=class extends IT{},RT=class extends IT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},zT=class extends s_{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},BT=class extends ${},VT=class extends BT{},HT=class extends BT{},UT=class extends sx{},WT=class extends ${main_input_name=`input_values`;forward_params=[`input_values`]},GT=class extends WT{async encode(e){return await X(this.sessions.encoder_model,e)}async decode(e){return await X(this.sessions.decoder_model,e)}},KT=class extends WT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},qT=class extends WT{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},JT=class extends ${},YT=class extends JT{},XT=class extends JT{},ZT=class extends ${},QT=class extends ZT{},$T=class extends ZT{},eE=class extends ZT{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){let o={input_ids:e},{encoder_outputs:s,encoder_attention_mask:c}=await Rh(this,o),l=s.dims[1]/this.config.reduction_factor,u=Math.floor(l*i),d=Math.floor(l*r),f=this.config.num_mel_bins,p=[],m=null,h=null,g=0;for(;;){++g;let e=jh(!!h),r;r=h?h.output_sequence_out:new G(`float32`,new Float32Array(f),[1,1,f]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:c,speaker_embeddings:t,encoder_hidden_states:s};Uh(this,i,m),h=await X(this.sessions.decoder_model_merged,i),m=Bh(h,m);let{prob:a,spectrum:o}=h;if(p.push(o),g>=d&&(Array.from(a.data).filter(e=>e>=n).length>0||g>=u))break}let _=Sl(p),{waveform:v}=await X(a.sessions.model,{spectrogram:_});return{spectrogram:_,waveform:v}}},tE=class extends ${main_input_name=`spectrogram`},nE=class extends ${},rE=class extends nE{},iE=class extends nE{async _call(e){return new Jm(await super._call(e))}},aE=class extends nE{async _call(e){return new Z(await super._call(e))}},oE=class extends nE{async _call(e){return new Ym(await super._call(e))}},sE=class extends ${},cE=class extends sE{},lE=class extends sE{},uE=class extends ${},dE=class extends uE{},fE=class extends uE{},pE=class extends ${},mE=class extends pE{},hE=class extends ${},gE=class extends hE{async generate_speech({input_ids:e,attention_mask:t,style:n,num_inference_steps:r=5,speed:i=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:s,latent_dim:c}=this.config,{last_hidden_state:l,durations:u}=await X(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:n}),d=u.div(i).mul_(a),f=s*o,p=d.data,m=Int32Array.from(p,e=>Math.ceil(e/f)),h=Math.max(...m),g=e.dims[0],_=new BigInt64Array(g*h);for(let e=0;e<g;++e)_.fill(1n,e*h,e*h+m[e]);let v=new G(`int64`,_,[g,h]),y=c*o,b=y*h,x=Fl([g,y,h]),S=x.data;for(let e=0;e<g;++e)if(m[e]!==h)for(let t=0;t<y;++t)S.fill(0,e*b+t*h+m[e],e*b+(t+1)*h);let C=kl([g],r);for(let e=0;e<r;++e){let r=kl([g],e);({denoised_latents:x}=await X(this.sessions.latent_denoiser,{style:n,noisy_latents:x,latent_mask:v,encoder_outputs:l,attention_mask:t,timestep:r,num_inference_steps:C}))}let{waveform:ee}=await X(this.sessions.voice_decoder,{latents:x});return{waveform:ee,durations:d}}},_E=class extends ${},vE=class extends _E{},yE=class extends _E{async _call(e){return new Z(await super._call(e))}},bE=class extends _E{},xE=class extends ${},SE=class extends xE{},CE=class extends xE{},wE=class extends ${forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},TE=class extends wE{},EE=class extends wE{},DE=class extends ${},OE=class extends DE{},kE=class extends DE{async _call(e){return new AE(await super._call(e))}},AE=class extends Dv{},jE=class extends ${},ME=class extends jE{},NE=class extends ${},PE=class extends NE{},FE=class extends NE{async _call(e){return new Xm(await super._call(e))}},IE=class extends NE{async _call(e){return new Z(await super._call(e))}},LE=class extends ${},RE=class extends LE{},zE=class extends LE{async _call(e){return new Xm(await super._call(e))}},BE=class extends LE{async _call(e){return new Z(await super._call(e))}},VE=class extends LE{async _call(e){return new qm(await super._call(e))}},HE=class extends ${},UE=class extends HE{},WE=class extends HE{},GE=class extends ${main_input_name=`pixel_values`;forward_params=[`pixel_values`,`decoder_input_ids`,`encoder_hidden_states`,`past_key_values`]},KE=class extends ${},qE=class extends KE{},JE=class extends KE{async _call(e){return new Z(await super._call(e))}},YE=class extends ${},XE=class extends YE{},ZE=class extends ${},QE=class extends ZE{},$E=class extends ZE{async _call(e){return new Z(await super._call(e))}},eD=class extends ${},tD=class extends eD{async _call(e){return new Zm(await super._call(e))}},nD=class extends ${},rD=class extends nD{},iD=class extends Km{constructor({waveform:e,spectrogram:t}){super(),this.waveform=e,this.spectrogram=t}},aD=class extends ${},oD=class extends aD{async _call(e){return new iD(await super._call(e))}},sD=class extends Lb{},cD=2,lD=1,uD=new WeakMap;function dD(e,t){let{text_config:n,audio_config:r}=e.config,i=e.sessions.audio_encoder,{num_mel_bins:a,hidden_size:o}=r,s=a+o,c=new Sh,l=Pm(r),u={batch_size:1},d=`float32`;for(let e of i.inputMetadata){if(e.name===`past_padding_cache`){d=e.type;continue}if(!l.has(e.name))continue;let t=Hh(e.shape,u),n=t.reduce((e,t)=>e*t,1),r=ll[e.type];c[e.name]=new G(e.type,new r(n),t)}let f=ll[d],p=new G(d,new f(s*cD),[1,s,cD]),m=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!m)throw Error(`input_features must be iterable or async iterable`);return{encoder_session:i,enc_kv_cache:c,enc_padding_cache:p,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:m,text_hidden_size:n.hidden_size}}async function fD(e,t){let n=t.dims[2],r=Math.floor((lD+n-3)/2)+1,i=new G(`int64`,BigInt64Array.from({length:r},(t,n)=>BigInt(e.enc_past_seq_len+n)),[1,r]),a=e.enc_past_seq_len+r,o=jl([1,a]),{audio_embeds:s,present_padding_cache:c,...l}=await X(e.encoder_session,{input_features:t,attention_mask:o,position_ids:i,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location===`gpu-buffer`&&e.enc_padding_cache.dispose(),e.enc_padding_cache=c;for(let t in l)if(t.startsWith(`present.`)){let n=t.replace(`present`,`past_key_values`),r=e.enc_kv_cache[n];r?.location===`gpu-buffer`&&r.dispose(),e.enc_kv_cache[n]=l[t]}return e.enc_past_seq_len=a,s}async function pD(e,t){for(;e.audio_embed_total_tokens<t&&!e.stream_exhausted;){let t=await e.chunks_iter.next();if(t.done){e.stream_exhausted=!0;break}let n=await fD(e,t.value);e.audio_embed_queue.push({data:n.data,tokens:n.dims[1]}),e.audio_embed_total_tokens+=n.dims[1]}}function mD(e,t,n){if(e.audio_embed_queue.length===0)return;let r=t.data,i=0,a=n;for(;a>0&&e.audio_embed_queue.length>0;){let t=e.audio_embed_queue[0],n=t.tokens-e.audio_queue_offset,o=Math.min(a,n),s=e.audio_queue_offset*e.text_hidden_size;for(let n=0;n<o*e.text_hidden_size;++n)r[i*e.text_hidden_size+n]+=t.data[s+n];i+=o,a-=o,e.audio_queue_offset+=o,e.audio_queue_offset>=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=n-a}var hD=class extends mh{constructor(e){super(),this._s=e}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},gD=class extends ${forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`]},_D=class extends gD{async forward({input_ids:e,past_key_values:t,...n}){let r=e.dims[1],i=uD.get(this);i&&await pD(i,i.audio_consumed+r);let{inputs_embeds:a}=await X(this.sessions.embed_tokens,{input_ids:e});i&&mD(i,a,r);let o={inputs_embeds:a,...n};Uh(this,o,t);let s=this.sessions.decoder_model_merged;return await X(s,xi(o,s.inputNames))}async generate({input_features:e,stopping_criteria:t,...n}){if(!e)throw Error(`input_features (generator/iterable) must be provided`);let r=dD(this,e);uD.set(this,r);let i=new hh;i.push(new hD(r)),t&&i.extend(t);try{return await super.generate({...n,stopping_criteria:i})}finally{r.enc_kv_cache.dispose(),uD.delete(this)}}},vD=class extends ${},yD=class extends vD{},bD=class extends vD{async _call(e){return new Xm(await super._call(e))}},xD=class extends vD{async _call(e){return new Z(await super._call(e))}},SD=class extends Km{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},CD=class extends ${},wD=class extends CD{},TD=class extends CD{async _call(e){return new Xm(await super._call(e))}},ED=class extends CD{async _call(e){return new Z(await super._call(e))}},DD=class extends CD{async _call(e){return new SD(await super._call(e))}},OD=class extends CD{async _call(e){return new qm(await super._call(e))}},kD=class extends ${},AD=class extends kD{},jD=class extends ph{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},MD=class extends ${requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`attention_mask`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},ND=class extends MD{},PD=class extends MD{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,jD)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],n=e.language,r=e.task;if(e.is_multilingual){n||=(F.warn(`No language specified - defaulting to English (en).`),`en`);let i=`<|${zu(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??`transcribe`])}else if(n||r)throw Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(F.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(e=>e!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);let a=i.decoder_input_ids instanceof G?zl(i.decoder_input_ids):i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new eh,n.push(new ah(t,a))),t.begin_suppress_tokens&&(n??=new eh,n.push(new ih(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task===`translate`&&F.warn(`Token-level timestamps may not be reliable for task 'translate'.`),t.output_attentions=!0,t.return_dict_in_generate=!0}if(t.return_timestamps&&!i.max_new_tokens)return this._generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:a,kwargs:i});let o=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames,.02,a.length)),o}async _generate_with_seek({inputs:e,generation_config:t,logits_processor:n,init_tokens:r,kwargs:i}){let a=t.no_timestamps_token_id+1,o=Array.isArray(t.eos_token_id)?t.eos_token_id[0]:t.eos_token_id,s=t.return_token_timestamps,c=e,l=c.dims[2],u=2*this.config.max_source_positions,d=0,f=[],p=[];for(;d<l;){let e=Math.min(d+u,l),m=c.slice(null,null,[d,e]),h,g=m.dims[2];if(g<u){let e=c.dims[1],t=new Float32Array(e*u),n=m.data;for(let r=0;r<e;++r)t.set(n.subarray(r*g,(r+1)*g),r*u);h=new G(`float32`,t,[1,e,u])}else h=m;if(n)for(let e of n)`begin_index`in e&&(e.begin_index=r.length);let _=await super.generate({inputs:h,generation_config:t,logits_processor:n,decoder_input_ids:r,...i}),v=(s?_.sequences:_)[0].tolist().map(Number).slice(r.length),y;if(s){_.token_timestamps=this._extract_token_timestamps(_,t.alignment_heads,Math.floor((e-d)/2),.02,r.length);let n=d/2*.02;y=_.token_timestamps[0].tolist().slice(r.length).map(e=>e+n)}if(v.length>0&&v.at(-1)===o&&v.pop(),v.length===0)break;let b=v.map(e=>e>=a),x=v.length>=2&&b[v.length-1]&&!b[v.length-2],S=[];for(let e=0;e<v.length-1;++e)b[e]&&b[e+1]&&S.push(e+1);let C,ee=v.length;if(S.length>0)if(x)C=e-d;else{let e=S.at(-1);C=(v[e-1]-a)*2,ee=e}else C=e-d;let w=Math.floor(d/2),T=a+1500;for(let e=0;e<ee;++e)v[e]>=a&&(v[e]=Math.min(v[e]+w,T));f.push(...v.slice(0,ee)),y&&p.push(...y.slice(0,ee)),d+=C}f.push(o);let m=[...r,...f];if(s){let e=new G(`int64`,m.map(BigInt),[1,m.length]),t=[...Array(r.length).fill(0),...p,0];return{sequences:e,token_timestamps:new G(`float32`,new Float32Array(t),[1,t.length])}}return new G(`int64`,m.map(BigInt),[1,m.length])}_extract_token_timestamps(e,t,n=null,r=.02,i=0){if(!e.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");n??F.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let a=this.config.median_filter_width;a===void 0&&(F.warn("Model config has no `median_filter_width`, using default value of 7."),a=7);let o=e.cross_attentions,s=Array.from({length:this.config.decoder_layers},(e,t)=>Sl(o.map(e=>e[t]),2)),c=Cl(t.map(([e,t])=>{if(e>=s.length)throw Error(`Layer index ${e} is out of bounds for cross attentions (length ${s.length}).`);return n?s[e].slice(null,t,null,[0,n]):s[e].slice(null,t)})).transpose(1,0,2,3),[l,u]=Tl(c,-2,0,!0),d=c.clone();for(let e=0;e<d.dims[0];++e){let t=d[e];for(let n=0;n<t.dims[0];++n){let r=t[n],i=l[e][n][0].data,o=u[e][n][0].data;for(let e=0;e<r.dims[0];++e){let t=r[e].data;for(let e=0;e<t.length;++e)t[e]=(t[e]-o[e])/i[e];t.set(wc(t,a))}}}let f=[El(i>0?d.slice(null,null,[i,d.dims[2]],null):d,1)],p=e.sequences.dims,m=new G(`float32`,new Float32Array(p[0]*p[1]),p);for(let e=0;e<p[0];++e){let[t,n]=Dc(f[e].neg().squeeze_(0).tolist()),a=vi([1],Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n])).map(e=>!!e),o=[];for(let e=0;e<a.length;++e)a[e]&&o.push(n[e]*r);let s=Array(i).fill(0);s.push(...o),o.length>0&&s.push(o.at(-1)),m[e].data.set(s)}return m}},FD=class extends PD{},ID=class extends ${},LD=class extends ID{},RD=class extends ID{async _call(e){return new Jm(await super._call(e))}},zD=class extends ID{async _call(e){return new Z(await super._call(e))}},BD=class extends ID{async _call(e){return new qm(await super._call(e))}},VD=class extends ID{async _call(e){return new Ym(await super._call(e))}},HD=class extends ${},UD=class extends HD{},WD=class extends HD{async _call(e){return new Jm(await super._call(e))}},GD=class extends HD{async _call(e){return new Z(await super._call(e))}},KD=class extends HD{async _call(e){return new qm(await super._call(e))}},qD=class extends HD{async _call(e){return new Ym(await super._call(e))}},JD=class extends ${},YD=class extends JD{},XD=class extends JD{async _call(e){return new ZD(await super._call(e))}},ZD=class extends Km{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},QD=class extends ${},$D=class extends QD{},eO=class extends QD{},tO=new Map([[`bert`,`BertModel`],[`eurobert`,`EuroBertModel`],[`neobert`,`NeoBertModel`],[`modernbert`,`ModernBertModel`],[`nomic_bert`,`NomicBertModel`],[`roformer`,`RoFormerModel`],[`electra`,`ElectraModel`],[`esm`,`EsmModel`],[`convbert`,`ConvBertModel`],[`camembert`,`CamembertModel`],[`deberta`,`DebertaModel`],[`deberta-v2`,`DebertaV2Model`],[`mpnet`,`MPNetModel`],[`albert`,`AlbertModel`],[`distilbert`,`DistilBertModel`],[`roberta`,`RobertaModel`],[`xlm`,`XLMModel`],[`xlm-roberta`,`XLMRobertaModel`],[`clap`,`ClapModel`],[`clip`,`CLIPModel`],[`clipseg`,`CLIPSegModel`],[`chinese_clip`,`ChineseCLIPModel`],[`siglip`,`SiglipModel`],[`jina_clip`,`JinaCLIPModel`],[`mobilebert`,`MobileBertModel`],[`squeezebert`,`SqueezeBertModel`],[`wav2vec2`,`Wav2Vec2Model`],[`wav2vec2-bert`,`Wav2Vec2BertModel`],[`unispeech`,`UniSpeechModel`],[`unispeech-sat`,`UniSpeechSatModel`],[`hubert`,`HubertModel`],[`wavlm`,`WavLMModel`],[`audio-spectrogram-transformer`,`ASTModel`],[`vits`,`VitsModel`],[`pyannote`,`PyAnnoteModel`],[`wespeaker-resnet`,`WeSpeakerResNetModel`],[`detr`,`DetrModel`],[`rt_detr`,`RTDetrModel`],[`rt_detr_v2`,`RTDetrV2Model`],[`rf_detr`,`RFDetrModel`],[`d_fine`,`DFineModel`],[`table-transformer`,`TableTransformerModel`],[`vit`,`ViTModel`],[`ijepa`,`IJepaModel`],[`pvt`,`PvtModel`],[`vit_msn`,`ViTMSNModel`],[`vit_mae`,`ViTMAEModel`],[`groupvit`,`GroupViTModel`],[`fastvit`,`FastViTModel`],[`mobilevit`,`MobileViTModel`],[`mobilevitv2`,`MobileViTV2Model`],[`owlvit`,`OwlViTModel`],[`owlv2`,`Owlv2Model`],[`beit`,`BeitModel`],[`deit`,`DeiTModel`],[`hiera`,`HieraModel`],[`convnext`,`ConvNextModel`],[`convnextv2`,`ConvNextV2Model`],[`dinov2`,`Dinov2Model`],[`dinov2_with_registers`,`Dinov2WithRegistersModel`],[`dinov3_vit`,`DINOv3ViTModel`],[`dinov3_convnext`,`DINOv3ConvNextModel`],[`resnet`,`ResNetModel`],[`swin`,`SwinModel`],[`swin2sr`,`Swin2SRModel`],[`donut-swin`,`DonutSwinModel`],[`yolos`,`YolosModel`],[`dpt`,`DPTModel`],[`glpn`,`GLPNModel`],[`hifigan`,`SpeechT5HifiGan`],[`efficientnet`,`EfficientNetModel`],[`decision_transformer`,`DecisionTransformerModel`],[`patchtst`,`PatchTSTModel`],[`patchtsmixer`,`PatchTSMixerModel`],[`mobilenet_v1`,`MobileNetV1Model`],[`mobilenet_v2`,`MobileNetV2Model`],[`mobilenet_v3`,`MobileNetV3Model`],[`mobilenet_v4`,`MobileNetV4Model`],[`maskformer`,`MaskFormerModel`],[`mgp-str`,`MgpstrForSceneTextRecognition`],[`style_text_to_speech_2`,`StyleTextToSpeech2Model`],[`openai_privacy_filter`,`OpenAIPrivacyFilterModel`]]),nO=new Map([[`t5`,`T5Model`],[`longt5`,`LongT5Model`],[`mt5`,`MT5Model`],[`bart`,`BartModel`],[`mbart`,`MBartModel`],[`marian`,`MarianModel`],[`whisper`,`WhisperModel`],[`cohere_asr`,`CohereAsrModel`],[`m2m_100`,`M2M100Model`],[`blenderbot`,`BlenderbotModel`],[`blenderbot-small`,`BlenderbotSmallModel`]]),rO=new Map([[`mimi`,`MimiModel`],[`dac`,`DacModel`],[`snac`,`SnacModel`]]),iO=new Map([[`bloom`,`BloomModel`],[`jais`,`JAISModel`],[`gpt2`,`GPT2Model`],[`gpt_oss`,`GptOssModel`],[`gptj`,`GPTJModel`],[`gpt_bigcode`,`GPTBigCodeModel`],[`gpt_neo`,`GPTNeoModel`],[`gpt_neox`,`GPTNeoXModel`],[`codegen`,`CodeGenModel`],[`llama`,`LlamaModel`],[`apertus`,`ApertusModel`],[`nanochat`,`NanoChatModel`],[`arcee`,`ArceeModel`],[`afmoe`,`AfmoeModel`],[`lfm2`,`Lfm2Model`],[`lfm2_moe`,`Lfm2MoeModel`],[`smollm3`,`SmolLM3Model`],[`exaone`,`ExaoneModel`],[`olmo`,`OlmoModel`],[`olmo2`,`Olmo2Model`],[`olmo3`,`Olmo3Model`],[`olmo_hybrid`,`OlmoHybridModel`],[`mobilellm`,`MobileLLMModel`],[`granite`,`GraniteModel`],[`granitemoehybrid`,`GraniteMoeHybridModel`],[`cohere`,`CohereModel`],[`cohere2`,`Cohere2Model`],[`gemma`,`GemmaModel`],[`gemma2`,`Gemma2Model`],[`vaultgemma`,`VaultGemmaModel`],[`gemma3_text`,`Gemma3Model`],[`helium`,`HeliumModel`],[`glm`,`GlmModel`],[`glm_moe_dsa`,`GlmMoeDsaModel`],[`openelm`,`OpenELMModel`],[`qwen2`,`Qwen2Model`],[`qwen2_moe`,`Qwen2MoeModel`],[`qwen3`,`Qwen3Model`],[`qwen3_moe`,`Qwen3MoeModel`],[`qwen3_next`,`Qwen3NextModel`],[`phi`,`PhiModel`],[`phi3`,`Phi3Model`],[`mpt`,`MptModel`],[`opt`,`OPTModel`],[`mistral`,`MistralModel`],[`mistral4`,`Mistral4Model`],[`ministral`,`MinistralModel`],[`ministral3`,`Ministral3Model`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2Model`],[`deepseek_v3`,`DeepseekV3Model`],[`falcon`,`FalconModel`],[`falcon_h1`,`FalconH1Model`],[`nemotron_h`,`NemotronHModel`],[`solar_open`,`SolarOpenModel`],[`stablelm`,`StableLmModel`],[`modernbert-decoder`,`ModernBertDecoderModel`],[`hunyuan_v1_dense`,`HunYuanDenseV1Model`],[`youtu`,`YoutuModel`]]),aO=new Map([[`speecht5`,`SpeechT5ForSpeechToText`],[`whisper`,`WhisperForConditionalGeneration`],[`lite-whisper`,`LiteWhisperForConditionalGeneration`],[`moonshine`,`MoonshineForConditionalGeneration`],[`cohere_asr`,`CohereAsrForConditionalGeneration`]]),oO=new Map([[`speecht5`,`SpeechT5ForTextToSpeech`]]),sO=new Map([[`vits`,`VitsModel`],[`musicgen`,`MusicgenForConditionalGeneration`],[`supertonic`,`SupertonicForConditionalGeneration`]]),cO=new Map([[`bert`,`BertForSequenceClassification`],[`eurobert`,`EuroBertForSequenceClassification`],[`neobert`,`NeoBertForSequenceClassification`],[`modernbert`,`ModernBertForSequenceClassification`],[`roformer`,`RoFormerForSequenceClassification`],[`electra`,`ElectraForSequenceClassification`],[`esm`,`EsmForSequenceClassification`],[`convbert`,`ConvBertForSequenceClassification`],[`camembert`,`CamembertForSequenceClassification`],[`deberta`,`DebertaForSequenceClassification`],[`deberta-v2`,`DebertaV2ForSequenceClassification`],[`mpnet`,`MPNetForSequenceClassification`],[`albert`,`AlbertForSequenceClassification`],[`distilbert`,`DistilBertForSequenceClassification`],[`roberta`,`RobertaForSequenceClassification`],[`xlm`,`XLMForSequenceClassification`],[`xlm-roberta`,`XLMRobertaForSequenceClassification`],[`bart`,`BartForSequenceClassification`],[`mbart`,`MBartForSequenceClassification`],[`mobilebert`,`MobileBertForSequenceClassification`],[`squeezebert`,`SqueezeBertForSequenceClassification`]]),lO=new Map([[`bert`,`BertForTokenClassification`],[`eurobert`,`EuroBertForTokenClassification`],[`neobert`,`NeoBertForTokenClassification`],[`modernbert`,`ModernBertForTokenClassification`],[`roformer`,`RoFormerForTokenClassification`],[`electra`,`ElectraForTokenClassification`],[`esm`,`EsmForTokenClassification`],[`convbert`,`ConvBertForTokenClassification`],[`camembert`,`CamembertForTokenClassification`],[`deberta`,`DebertaForTokenClassification`],[`deberta-v2`,`DebertaV2ForTokenClassification`],[`mpnet`,`MPNetForTokenClassification`],[`distilbert`,`DistilBertForTokenClassification`],[`roberta`,`RobertaForTokenClassification`],[`xlm`,`XLMForTokenClassification`],[`xlm-roberta`,`XLMRobertaForTokenClassification`],[`openai_privacy_filter`,`OpenAIPrivacyFilterForTokenClassification`]]),uO=new Map([[`t5`,`T5ForConditionalGeneration`],[`longt5`,`LongT5ForConditionalGeneration`],[`mt5`,`MT5ForConditionalGeneration`],[`bart`,`BartForConditionalGeneration`],[`mbart`,`MBartForConditionalGeneration`],[`marian`,`MarianMTModel`],[`m2m_100`,`M2M100ForConditionalGeneration`],[`blenderbot`,`BlenderbotForConditionalGeneration`],[`blenderbot-small`,`BlenderbotSmallForConditionalGeneration`]]),dO=new Map([[`bloom`,`BloomForCausalLM`],[`gpt2`,`GPT2LMHeadModel`],[`gpt_oss`,`GptOssForCausalLM`],[`jais`,`JAISLMHeadModel`],[`gptj`,`GPTJForCausalLM`],[`gpt_bigcode`,`GPTBigCodeForCausalLM`],[`gpt_neo`,`GPTNeoForCausalLM`],[`gpt_neox`,`GPTNeoXForCausalLM`],[`codegen`,`CodeGenForCausalLM`],[`llama`,`LlamaForCausalLM`],[`nanochat`,`NanoChatForCausalLM`],[`apertus`,`ApertusForCausalLM`],[`llama4_text`,`Llama4ForCausalLM`],[`arcee`,`ArceeForCausalLM`],[`afmoe`,`AfmoeForCausalLM`],[`lfm2`,`Lfm2ForCausalLM`],[`lfm2_moe`,`Lfm2MoeForCausalLM`],[`smollm3`,`SmolLM3ForCausalLM`],[`exaone`,`ExaoneForCausalLM`],[`olmo`,`OlmoForCausalLM`],[`olmo2`,`Olmo2ForCausalLM`],[`olmo3`,`Olmo3ForCausalLM`],[`olmo_hybrid`,`OlmoHybridForCausalLM`],[`mobilellm`,`MobileLLMForCausalLM`],[`granite`,`GraniteForCausalLM`],[`granitemoehybrid`,`GraniteMoeHybridForCausalLM`],[`cohere`,`CohereForCausalLM`],[`cohere2`,`Cohere2ForCausalLM`],[`gemma`,`GemmaForCausalLM`],[`gemma2`,`Gemma2ForCausalLM`],[`vaultgemma`,`VaultGemmaForCausalLM`],[`gemma3_text`,`Gemma3ForCausalLM`],[`gemma3`,`Gemma3ForCausalLM`],[`helium`,`HeliumForCausalLM`],[`glm`,`GlmForCausalLM`],[`glm_moe_dsa`,`GlmMoeDsaForCausalLM`],[`openelm`,`OpenELMForCausalLM`],[`qwen2`,`Qwen2ForCausalLM`],[`qwen2_moe`,`Qwen2MoeForCausalLM`],[`qwen3`,`Qwen3ForCausalLM`],[`qwen3_moe`,`Qwen3MoeForCausalLM`],[`qwen3_next`,`Qwen3NextForCausalLM`],[`qwen2_vl`,`Qwen2VLForCausalLM`],[`qwen2_5_vl`,`Qwen2_5_VLForCausalLM`],[`qwen3_vl`,`Qwen3VLForCausalLM`],[`qwen3_vl_moe`,`Qwen3VLMoeForCausalLM`],[`qwen3_5`,`Qwen3_5ForCausalLM`],[`qwen3_5_text`,`Qwen3_5ForCausalLM`],[`qwen3_5_moe`,`Qwen3_5MoeForCausalLM`],[`gemma3n`,`Gemma3nForCausalLM`],[`gemma4`,`Gemma4ForCausalLM`],[`phi`,`PhiForCausalLM`],[`phi3`,`Phi3ForCausalLM`],[`mpt`,`MptForCausalLM`],[`opt`,`OPTForCausalLM`],[`mbart`,`MBartForCausalLM`],[`mistral`,`MistralForCausalLM`],[`mistral4`,`Mistral4ForCausalLM`],[`ministral`,`MinistralForCausalLM`],[`ministral3`,`Ministral3ForCausalLM`],[`ernie4_5`,`Ernie4_5ForCausalLM`],[`starcoder2`,`Starcoder2ForCausalLM`],[`deepseek_v3`,`DeepseekV3ForCausalLM`],[`falcon`,`FalconForCausalLM`],[`falcon_h1`,`FalconH1ForCausalLM`],[`nemotron_h`,`NemotronHForCausalLM`],[`trocr`,`TrOCRForCausalLM`],[`solar_open`,`SolarOpenForCausalLM`],[`stablelm`,`StableLmForCausalLM`],[`modernbert-decoder`,`ModernBertDecoderForCausalLM`],[`hunyuan_v1_dense`,`HunYuanDenseV1ForCausalLM`],[`youtu`,`YoutuForCausalLM`],[`phi3_v`,`Phi3VForCausalLM`]]),fO=new Map([[`multi_modality`,`MultiModalityCausalLM`]]),pO=new Map([[`bert`,`BertForMaskedLM`],[`eurobert`,`EuroBertForMaskedLM`],[`neobert`,`NeoBertForMaskedLM`],[`modernbert`,`ModernBertForMaskedLM`],[`roformer`,`RoFormerForMaskedLM`],[`electra`,`ElectraForMaskedLM`],[`esm`,`EsmForMaskedLM`],[`convbert`,`ConvBertForMaskedLM`],[`camembert`,`CamembertForMaskedLM`],[`deberta`,`DebertaForMaskedLM`],[`deberta-v2`,`DebertaV2ForMaskedLM`],[`mpnet`,`MPNetForMaskedLM`],[`albert`,`AlbertForMaskedLM`],[`distilbert`,`DistilBertForMaskedLM`],[`roberta`,`RobertaForMaskedLM`],[`xlm`,`XLMWithLMHeadModel`],[`xlm-roberta`,`XLMRobertaForMaskedLM`],[`mobilebert`,`MobileBertForMaskedLM`],[`squeezebert`,`SqueezeBertForMaskedLM`]]),mO=new Map([[`bert`,`BertForQuestionAnswering`],[`neobert`,`NeoBertForQuestionAnswering`],[`roformer`,`RoFormerForQuestionAnswering`],[`electra`,`ElectraForQuestionAnswering`],[`convbert`,`ConvBertForQuestionAnswering`],[`camembert`,`CamembertForQuestionAnswering`],[`deberta`,`DebertaForQuestionAnswering`],[`deberta-v2`,`DebertaV2ForQuestionAnswering`],[`mpnet`,`MPNetForQuestionAnswering`],[`albert`,`AlbertForQuestionAnswering`],[`distilbert`,`DistilBertForQuestionAnswering`],[`roberta`,`RobertaForQuestionAnswering`],[`xlm`,`XLMForQuestionAnswering`],[`xlm-roberta`,`XLMRobertaForQuestionAnswering`],[`mobilebert`,`MobileBertForQuestionAnswering`],[`squeezebert`,`SqueezeBertForQuestionAnswering`]]),hO=new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`]]),gO=new Map([[`llava`,`LlavaForConditionalGeneration`],[`llava_onevision`,`LlavaOnevisionForConditionalGeneration`],[`moondream1`,`Moondream1ForConditionalGeneration`],[`florence2`,`Florence2ForConditionalGeneration`],[`qwen2_vl`,`Qwen2VLForConditionalGeneration`],[`qwen2_5_vl`,`Qwen2_5_VLForConditionalGeneration`],[`qwen3_vl`,`Qwen3VLForConditionalGeneration`],[`qwen3_vl_moe`,`Qwen3VLMoeForConditionalGeneration`],[`qwen3_5`,`Qwen3_5ForConditionalGeneration`],[`qwen3_5_moe`,`Qwen3_5MoeForConditionalGeneration`],[`lfm2_vl`,`Lfm2VlForConditionalGeneration`],[`idefics3`,`Idefics3ForConditionalGeneration`],[`smolvlm`,`SmolVLMForConditionalGeneration`],[`paligemma`,`PaliGemmaForConditionalGeneration`],[`llava_qwen2`,`LlavaQwen2ForCausalLM`],[`gemma3`,`Gemma3ForConditionalGeneration`],[`gemma3n`,`Gemma3nForConditionalGeneration`],[`gemma4`,`Gemma4ForConditionalGeneration`],[`mistral3`,`Mistral3ForConditionalGeneration`],[`lighton_ocr`,`LightOnOcrForConditionalGeneration`],[`glm_ocr`,`GlmOcrForConditionalGeneration`]]),_O=new Map([[`granite_speech`,`GraniteSpeechForConditionalGeneration`],[`ultravox`,`UltravoxModel`],[`voxtral`,`VoxtralForConditionalGeneration`],[`voxtral_realtime`,`VoxtralRealtimeForConditionalGeneration`]]),vO=new Map([[`vision-encoder-decoder`,`VisionEncoderDecoderModel`]]),yO=new Map([[`vit`,`ViTForImageClassification`],[`ijepa`,`IJepaForImageClassification`],[`pvt`,`PvtForImageClassification`],[`vit_msn`,`ViTMSNForImageClassification`],[`fastvit`,`FastViTForImageClassification`],[`mobilevit`,`MobileViTForImageClassification`],[`mobilevitv2`,`MobileViTV2ForImageClassification`],[`beit`,`BeitForImageClassification`],[`deit`,`DeiTForImageClassification`],[`hiera`,`HieraForImageClassification`],[`convnext`,`ConvNextForImageClassification`],[`convnextv2`,`ConvNextV2ForImageClassification`],[`dinov2`,`Dinov2ForImageClassification`],[`dinov2_with_registers`,`Dinov2WithRegistersForImageClassification`],[`resnet`,`ResNetForImageClassification`],[`swin`,`SwinForImageClassification`],[`segformer`,`SegformerForImageClassification`],[`efficientnet`,`EfficientNetForImageClassification`],[`mobilenet_v1`,`MobileNetV1ForImageClassification`],[`mobilenet_v2`,`MobileNetV2ForImageClassification`],[`mobilenet_v3`,`MobileNetV3ForImageClassification`],[`mobilenet_v4`,`MobileNetV4ForImageClassification`]]),bO=new Map([[`detr`,`DetrForObjectDetection`],[`rt_detr`,`RTDetrForObjectDetection`],[`rt_detr_v2`,`RTDetrV2ForObjectDetection`],[`rf_detr`,`RFDetrForObjectDetection`],[`d_fine`,`DFineForObjectDetection`],[`table-transformer`,`TableTransformerForObjectDetection`],[`yolos`,`YolosForObjectDetection`]]),xO=new Map([[`owlvit`,`OwlViTForObjectDetection`],[`owlv2`,`Owlv2ForObjectDetection`],[`grounding-dino`,`GroundingDinoForObjectDetection`]]),SO=new Map([[`detr`,`DetrForSegmentation`],[`clipseg`,`CLIPSegForImageSegmentation`]]),CO=new Map([[`segformer`,`SegformerForSemanticSegmentation`],[`sapiens`,`SapiensForSemanticSegmentation`],[`swin`,`SwinForSemanticSegmentation`],[`mobilenet_v1`,`MobileNetV1ForSemanticSegmentation`],[`mobilenet_v2`,`MobileNetV2ForSemanticSegmentation`],[`mobilenet_v3`,`MobileNetV3ForSemanticSegmentation`],[`mobilenet_v4`,`MobileNetV4ForSemanticSegmentation`]]),wO=new Map([[`detr`,`DetrForSegmentation`],[`maskformer`,`MaskFormerForInstanceSegmentation`]]),TO=new Map([[`sam`,`SamModel`],[`sam2`,`Sam2Model`],[`edgetam`,`EdgeTamModel`],[`sam3_tracker`,`Sam3TrackerModel`]]),EO=new Map([[`wav2vec2`,`Wav2Vec2ForCTC`],[`wav2vec2-bert`,`Wav2Vec2BertForCTC`],[`unispeech`,`UniSpeechForCTC`],[`unispeech-sat`,`UniSpeechSatForCTC`],[`wavlm`,`WavLMForCTC`],[`hubert`,`HubertForCTC`],[`parakeet_ctc`,`ParakeetForCTC`]]),DO=new Map([[`wav2vec2`,`Wav2Vec2ForSequenceClassification`],[`wav2vec2-bert`,`Wav2Vec2BertForSequenceClassification`],[`unispeech`,`UniSpeechForSequenceClassification`],[`unispeech-sat`,`UniSpeechSatForSequenceClassification`],[`wavlm`,`WavLMForSequenceClassification`],[`hubert`,`HubertForSequenceClassification`],[`audio-spectrogram-transformer`,`ASTForAudioClassification`]]),OO=new Map([[`wavlm`,`WavLMForXVector`]]),kO=new Map([[`unispeech-sat`,`UniSpeechSatForAudioFrameClassification`],[`wavlm`,`WavLMForAudioFrameClassification`],[`wav2vec2`,`Wav2Vec2ForAudioFrameClassification`],[`pyannote`,`PyAnnoteForAudioFrameClassification`]]),AO=new Map([[`vitmatte`,`VitMatteForImageMatting`]]),jO=new Map([[`patchtst`,`PatchTSTForPrediction`],[`patchtsmixer`,`PatchTSMixerForPrediction`]]),MO=new Map([[`swin2sr`,`Swin2SRForImageSuperResolution`]]),NO=new Map([[`chmv2`,`CHMv2ForDepthEstimation`],[`dpt`,`DPTForDepthEstimation`],[`depth_anything`,`DepthAnythingForDepthEstimation`],[`glpn`,`GLPNForDepthEstimation`],[`sapiens`,`SapiensForDepthEstimation`],[`depth_pro`,`DepthProForDepthEstimation`],[`metric3d`,`Metric3DForDepthEstimation`],[`metric3dv2`,`Metric3Dv2ForDepthEstimation`]]),PO=new Map([[`sapiens`,`SapiensForNormalEstimation`]]),FO=new Map([[`vitpose`,`VitPoseForPoseEstimation`]]),IO=new Map([[`clip`,`CLIPVisionModelWithProjection`],[`siglip`,`SiglipVisionModel`],[`jina_clip`,`JinaCLIPVisionModel`]]),LO=[[tO,Q.EncoderOnly],[nO,Q.EncoderDecoder],[iO,Q.DecoderOnlyWithoutHead],[rO,Q.AutoEncoder],[cO,Q.EncoderOnly],[lO,Q.EncoderOnly],[uO,Q.Seq2Seq],[aO,Q.Seq2Seq],[dO,Q.DecoderOnly],[fO,Q.MultiModality],[pO,Q.EncoderOnly],[mO,Q.EncoderOnly],[hO,Q.Vision2Seq],[gO,Q.ImageTextToText],[_O,Q.AudioTextToText],[yO,Q.EncoderOnly],[SO,Q.EncoderOnly],[wO,Q.EncoderOnly],[CO,Q.EncoderOnly],[AO,Q.EncoderOnly],[jO,Q.EncoderOnly],[MO,Q.EncoderOnly],[NO,Q.EncoderOnly],[PO,Q.EncoderOnly],[FO,Q.EncoderOnly],[bO,Q.EncoderOnly],[xO,Q.EncoderOnly],[TO,Q.MaskGeneration],[EO,Q.EncoderOnly],[DO,Q.EncoderOnly],[oO,Q.Seq2Seq],[sO,Q.EncoderOnly],[OO,Q.EncoderOnly],[kO,Q.EncoderOnly],[IO,Q.EncoderOnly]];for(let[e,t]of LO)for(let n of e.values()){Ph.set(n,t);let e=rg[n];Ih.set(e,n),Fh.set(n,e)}var RO=[[`MusicgenForConditionalGeneration`,_C,Q.Musicgen],[`Phi3VForCausalLM`,xw,Q.Phi3V],[`CLIPTextModelWithProjection`,u_,Q.EncoderOnly],[`SiglipTextModel`,RT,Q.EncoderOnly],[`JinaCLIPTextModel`,gx,Q.EncoderOnly],[`ClapTextModelWithProjection`,a_,Q.EncoderOnly],[`ClapAudioModelWithProjection`,o_,Q.EncoderOnly],[`DacEncoderModel`,Z_,Q.EncoderOnly],[`DacDecoderModel`,Q_,Q.EncoderOnly],[`MimiEncoderModel`,aS,Q.EncoderOnly],[`MimiDecoderModel`,oS,Q.EncoderOnly],[`SnacEncoderModel`,KT,Q.EncoderOnly],[`SnacDecoderModel`,qT,Q.EncoderOnly],[`Gemma3nForConditionalGeneration`,qy,Q.ImageAudioTextToText],[`Gemma4ForConditionalGeneration`,Yy,Q.ImageAudioTextToText],[`SupertonicForConditionalGeneration`,gE,Q.Supertonic],[`ChatterboxModel`,Qg,Q.Chatterbox],[`VoxtralRealtimeForConditionalGeneration`,_D,Q.VoxtralRealtime]];for(let[e,t,n]of RO)Ph.set(e,n),Ih.set(t,e),Fh.set(e,t);var zO=new Map([[`modnet`,SO],[`birefnet`,SO],[`isnet`,SO],[`ben`,SO]]);for(let[e,t]of zO.entries())t.set(e,`PreTrainedModel`),Ph.set(e,Q.EncoderOnly),Fh.set(e,$);var BO=new Set(zO.keys());Ph.set(`PreTrainedModel`,Q.EncoderOnly),Ih.set($,`PreTrainedModel`);var VO={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:cO,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:lO,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:oO,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:sO,MODEL_FOR_MASKED_LM_MAPPING_NAMES:pO,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:mO,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:yO,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:SO,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:CO,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:wO,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:bO,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:xO,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:TO,MODEL_FOR_CTC_MAPPING_NAMES:EO,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:DO,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:OO,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:kO,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:vO,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:AO,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:MO,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:NO,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:PO,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:FO,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:IO,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:gO,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:_O,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:uO,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:aO,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:dO,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:hO};kh(VO);var HO=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(e){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let t of this.MODEL_CLASS_MAPPINGS)if(t.has(e))return!0;return this.BASE_IF_FAIL}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d};if(f.config=await Lm.from_pretrained(e,f),!this.MODEL_CLASS_MAPPINGS)throw Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:p}=f.config;for(let t of this.MODEL_CLASS_MAPPINGS){let n=t.get(p);if(!n){for(let e of t.values())if(e[0]===p){n=e;break}if(!n)continue}return await rg[n].from_pretrained(e,f)}if(this.BASE_IF_FAIL)return BO.has(p)||F.warn(`Unknown model class "${p}", attempting to construct from base class.`),await $.from_pretrained(e,f);throw Error(`Unsupported model type: ${p}`)}},UO=class extends HO{static MODEL_CLASS_MAPPINGS=LO.map(e=>e[0]);static BASE_IF_FAIL=!0},WO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},GO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},KO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},qO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},JO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},YO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},XO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},ZO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},QO=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},$O=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},ek=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},tk=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},nk=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},rk=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},ik=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},ak=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var ok=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_CTC_MAPPING_NAMES]},sk=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]}),class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]};var ck=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var lk=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},uk=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]}),class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]};var dk=class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]};(class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]}),class extends HO{static MODEL_CLASS_MAPPINGS=[VO.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function fk(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>$d.read(e)))}async function pk(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>typeof e==`string`||e instanceof URL?rd(e,t):e instanceof Float64Array?new Float32Array(e):e))}function mk(e,t){t&&(e=e.map(e=>e|0));let[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}var hk=class extends fi{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}},gk=class extends hk{async _call(e,{top_k:t=1}={}){let n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),{problem_type:i,id2label:a}=this.model.config,o=i===`multi_label_classification`?e=>e.sigmoid():e=>new G(`float32`,gc(e.data),e.dims),s=[];for(let e of r.logits){let n=await hl(o(e),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));t===1?s.push(...i):s.push(i)}return Array.isArray(e)||t===1?s:s[0]}},_k=class extends hk{async _call(e,{ignore_labels:t=[`O`],aggregation_strategy:n=`none`}={}){if(n!==`none`&&n!==`simple`)throw Error(`Invalid aggregation_strategy: "${n}". Must be one of "none" or "simple".`);let r=Array.isArray(e),i=this.tokenizer(r?e:[e],{padding:!0,truncation:!0}),a=(await this.model(i)).logits,o=this.model.config.id2label,s=[];for(let e=0;e<a.dims[0];++e){let r=i.input_ids[e].tolist(),c=a[e],l=[];for(let e=0;e<c.dims[0];++e){let n=c[e],i=yc(n.data)[1],a=o?o[i]:`LABEL_${i}`;if(t.includes(a))continue;let s=this.tokenizer.decode([r[e]],{skip_special_tokens:!0});if(s===``)continue;let u=gc(n.data);l.push({entity:a,score:u[i],index:e,word:s})}s.push(n===`simple`?yk(l,r,this.tokenizer):l)}return r?s:s[0]}};function vk(e){let t=e[0];return e[1]===`-`&&(t===`B`||t===`I`||t===`E`||t===`S`)?[t,e.slice(2)]:[`I`,e]}function yk(e,t,n){let r=[],i=null;for(let t=0;t<e.length;++t){let[n,a]=vk(e[t].entity);i===a&&n!==`B`&&n!==`S`?(r[r.length-1].end=t+1,n===`E`&&(i=null)):(r.push({tag:a,start:t,end:t+1}),i=n===`S`?null:a)}return r.map(({tag:r,start:i,end:a})=>{let o=0,s=[];for(let n=i;n<a;++n)o+=e[n].score,s.push(t[e[n].index]);return{entity_group:r,score:o/(a-i),word:n.decode(s,{skip_special_tokens:!0})}})}var bk=class extends hk{async _call(e,t,{top_k:n=1}={}){let r=this.tokenizer(e,{text_pair:t,padding:!0,truncation:!0}),i=Array.isArray(e),{start_logits:a,end_logits:o}=await this.model(r),s=r.input_ids.tolist(),c=r.attention_mask.tolist(),{all_special_ids:l,sep_token_id:u}=this.tokenizer,d=[];for(let e=0;e<a.dims[0];++e){let t=s[e],r=t.findIndex(e=>e==u),i=a[e].tolist(),f=o[e].tolist();for(let n=1;n<i.length;++n)(c[e]==0||n<=r||l.findIndex(e=>e==t[n])!==-1)&&(i[n]=-1/0,f[n]=-1/0);let p=gc(i).map((e,t)=>[e,t]),m=gc(f).map((e,t)=>[e,t]);p[0][0]=0,m[0][0]=0;let h=yi(p,m).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]),g=[];for(let e=0;e<Math.min(h.length,n);++e){let[n,r,i]=h[e],a=t.slice(n,r+1),o=this.tokenizer.decode(a,{skip_special_tokens:!0});g.push({answer:o,score:i})}n===1?d.push(...g):d.push(g)}return i?d:d[0]}},xk=class extends hk{async _call(e,{top_k:t=5}={}){let{mask_token_id:n,mask_token:r}=this.tokenizer,i=this.tokenizer(e,{padding:!0,truncation:!0}),{logits:a}=await this.model(i),o=[],s=i.input_ids.tolist();for(let e=0;e<s.length;++e){let i=s[e],c=i.findIndex(e=>e==n);if(c===-1)throw Error(`Mask token (${r}) not found in text.`);let l=a[e][c],u=await hl(new G(`float32`,gc(l.data),l.dims),t),d=u[0].tolist(),f=u[1].tolist();o.push(f.map((e,t)=>{let n=i.slice();return n[c]=e,{score:d[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(n,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},Sk=class extends hk{_default_generation_config={max_new_tokens:256};_key=`generated_text`;async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let r=this.tokenizer,i={padding:!0,truncation:!0},a;a=this.task===`translation`&&`_build_translation_inputs`in r?r._build_translation_inputs(e,i,t):r(e,i);let o=await this.model.generate({...a,...this._default_generation_config,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},Ck=class extends Sk{_key=`summary_text`},wk=class extends Sk{_key=`translation_text`};function Tk(e){return Array.isArray(e)&&e.every(e=>`role`in e&&`content`in e)}var Ek=class extends hk{_default_generation_config={max_new_tokens:256};async _call(e,t={}){let{add_special_tokens:n,return_full_text:r,tools:i,documents:a,chat_template:o,tokenizer_encode_kwargs:s,...c}=t,l=!1,u=!1,d=n??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,f=s,p;if(typeof e==`string`)p=e=[e];else if(Array.isArray(e)&&e.every(e=>typeof e==`string`))l=!0,p=e;else{if(Tk(e))e=[e];else if(Array.isArray(e)&&e.every(Tk))l=!0;else throw Error(`Input must be a string, an array of strings, a Chat, or an array of Chats`);u=!0;let t={tokenize:!1,add_generation_prompt:!0,...xi({tools:i,documents:a,chat_template:o},[`tools`,`documents`,`chat_template`]),...f};p=e.map(e=>this.tokenizer.apply_chat_template(e,t)),d=!1,f=void 0}let m=u?!1:r??!0;this.tokenizer.padding_side=`left`;let h=this.tokenizer(p,{add_special_tokens:d,padding:!0,truncation:!0,...f}),g=await this.model.generate({...h,...this._default_generation_config,...c}),_=this.tokenizer.batch_decode(g,{skip_special_tokens:!0}),v;!m&&h.input_ids.dims.at(-1)>0&&(v=this.tokenizer.batch_decode(h.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let y=Array.from({length:e.length},e=>[]);for(let t=0;t<_.length;++t){let n=Math.floor(t/g.dims[0]*e.length);v&&(_[t]=_[t].slice(v[n])),y[n].push({generated_text:u?[...e[n],{role:`assistant`,content:_[t]}]:_[t]})}return!l&&y.length===1?y[0]:y}},Dk=class extends hk{constructor(e){super(e),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([e,t])=>[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(F.warn(`Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.`),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(F.warn(`Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.`),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n=`This example is {}.`,multi_label:r=!1}={}){let i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(e=>n.replace(`{}`,e)),o=r||t.length===1,s=[];for(let n of e){let e=[];for(let t of a){let r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);o?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}let r=(o?e.map(e=>gc(e)[1]):gc(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);s.push({sequence:n,labels:r.map(e=>t[e[1]]),scores:r.map(e=>e[0])})}return i?s:s[0]}},Ok=class extends hk{async _call(e,{top_k:t=5}={}){let n=this.processor.feature_extractor.config.sampling_rate,r=await pk(e,n),i=this.model.config.id2label,a=[];for(let e of r){let n=await this.processor(e),r=(await this.model(n)).logits[0],o=await hl(new G(`float32`,gc(r.data),r.dims),t),s=o[0].tolist(),c=o[1].tolist().map((e,t)=>({label:i?i[e]:`LABEL_${e}`,score:s[t]}));a.push(c)}return Array.isArray(e)?a:a[0]}},kk=class extends hk{async _call(e,t,{hypothesis_template:n=`This is a sound of {}.`}={}){let r=!Array.isArray(e);r&&(e=[e]);let i=t.map(e=>n.replace(`{}`,e)),a=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,s=await pk(e,o),c=[];for(let e of s){let n=await this.processor(e),r=gc((await this.model({...a,...n})).logits_per_audio.data);c.push([...r].map((e,n)=>({score:e,label:t[n]})))}return r?c[0]:c}},Ak=class extends hk{_default_generation_config={};async _call(e,t={}){switch(t={...this._default_generation_config,...t},this.model.config.model_type){case`whisper`:case`lite-whisper`:return this._call_whisper(e,t);case`wav2vec2`:case`wav2vec2-bert`:case`unispeech`:case`unispeech-sat`:case`hubert`:case`parakeet_ctc`:return this._call_wav2vec2(e,t);case`moonshine`:return this._call_moonshine(e,t);case`cohere_asr`:return this._call_cohere_asr(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&F.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&F.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await pk(r,i),o=[];for(let e of a){let t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(let e of n)r.push(yc(e.data)[1]);let i=this.tokenizer.decode(r,{skip_special_tokens:!0}).trim();o.push({text:i})}return n?o[0]:o}async _call_whisper(e,t){let n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};n===`word`&&(o.return_token_timestamps=!0,o.return_timestamps=!0);let s=!Array.isArray(e),c=s?[e]:e,l=this.processor.feature_extractor.config,u=l.chunk_length/this.model.config.max_source_positions,d=l.hop_length,f=l.sampling_rate,p=await pk(c,f),m=[];for(let e of p){let t=[];if(r>0){if(a===null)a=r/6;else if(r<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let n=f*r,i=f*a,o=n-2*i,s=0;for(;;){let r=s+n,a=e.subarray(s,r),c=await this.processor(a),l=s===0,u=r>=e.length;if(t.push({stride:[a.length,l?0:i,u?0:i],input_features:c.input_features,is_last:u}),u)break;s+=o}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of t){o.num_frames=Math.floor(e.stride[0]/d);let t=await this.model.generate({inputs:e.input_features,...o});if(n===`word`){let n=t.sequences.tolist()[0],r=t.token_timestamps.tolist()[0],i=this.tokenizer.timestamp_begin,a=Math.max(n.findIndex(e=>Number(e)>=i),0);e.tokens=n.slice(a),e.token_timestamps=r.slice(a).map(e=>Tc(e,2))}else e.tokens=t[0].tolist();e.stride=e.stride.map(e=>e/f)}let[s,c]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:s,...c})}return s?m[0]:m}async _call_moonshine(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await pk(r,i),o=[];for(let e of a){let n=await this.processor(e),r=Math.floor(e.length/i)*6,a=await this.model.generate({max_new_tokens:r,...t,...n}),s=this.processor.batch_decode(a,{skip_special_tokens:!0})[0];o.push({text:s})}return n?o[0]:o}async _call_cohere_asr(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor,a=i.config.sampling_rate,o=await pk(r,a),s=t.language??`en`,c=this.processor.get_decoder_prompt_ids(s),l=[];for(let e of o){let n=i.split_audio(e),r=[];for(let e of n){let n=await this.processor(e),i=await this.model.generate({...n,decoder_input_ids:c,...t}),a=this.tokenizer.decode(i[0].tolist(),{skip_special_tokens:!0}).trim();r.push(a)}let a=this.processor.constructor.join_chunks(r,s);l.push({text:a})}return n?l[0]:l}},jk=class extends hk{DEFAULT_VOCODER_ID=`Xenova/speecht5_hifigan`;constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e==`string`||e instanceof URL)&&(e=new Float32Array(await(await P.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new G(`float32`,e,[e.length]);else if(!(e instanceof G))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,n,r=null){let i=t.data,[a,o]=t.dims,s=r?r.data:null,c=[];for(let e=0;e<a;++e){let t=s?Math.min(Math.ceil(s[e]),o):o,r=e*o;c.push(new Sd(i.slice(r,r+t),n))}return Array.isArray(e)?c:c[0]}async _call(e,t){return this.processor?this._call_text_to_spectrogram(e,t):this.model.config.model_type===`supertonic`?this._call_supertonic(e,t):this._call_text_to_waveform(e)}async _call_supertonic(e,{speaker_embeddings:t,num_inference_steps:n,speed:r}){if(!t)throw Error(`Speaker embeddings must be provided for Supertonic models.`);let{sampling_rate:i,style_dim:a}=this.model.config,o=this.tokenizer(e,{padding:!0,truncation:!0}),s=o.input_ids.dims[0];t=await this._prepare_speaker_embeddings(t,s),t=t.view(s,-1,a);let{waveform:c,durations:l}=await this.model.generate_speech({...o,style:t,num_inference_steps:n,speed:r});return this._postprocess_waveform(e,c,i,l)}async _call_text_to_waveform(e){let t=this.tokenizer(e,{padding:!0,truncation:!0}),{waveform:n}=await this.model(t),r=this.model.config.sampling_rate;return this._postprocess_waveform(e,n,r)}async _call_text_to_spectrogram(e,{speaker_embeddings:t}){this.vocoder||=(F.info(`No vocoder specified, using default HifiGan vocoder.`),await UO.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:`fp32`}));let{input_ids:n}=this.tokenizer(e,{padding:!0,truncation:!0}),r=n.dims[0];t=await this._prepare_speaker_embeddings(t,r),t=t.view(r,-1);let{waveform:i}=await this.model.generate_speech(n,t,{vocoder:this.vocoder}),a=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(e,i,a)}},Mk=class extends hk{async _call(e,t={}){let n=Array.isArray(e),r=await fk(e),{pixel_values:i}=await this.processor(r),a=[];for(let e of i){e.dims=[1,...e.dims];let n=await this.model.generate({inputs:e,...t}),r=this.tokenizer.batch_decode(n,{skip_special_tokens:!0}).map(e=>({generated_text:e.trim()}));a.push(r)}return n?a:a[0]}},Nk=class extends hk{async _call(e,{top_k:t=5}={}){let n=await fk(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),{id2label:a}=this.model.config,o=[];for(let e of i.logits){let n=await hl(new G(`float32`,gc(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));o.push(i)}return Array.isArray(e)?o:o[0]}},Pk={panoptic:`post_process_panoptic_segmentation`,instance:`post_process_instance_segmentation`,semantic:`post_process_semantic_segmentation`},Fk=class extends hk{async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error(`Image segmentation pipeline currently only supports a batch size of 1.`);let s=await fk(e),c=s.map(e=>[e.height,e.width]),l=await this.processor(s),{inputNames:u,outputNames:d}=this.model.sessions.model;if(!u.includes(`pixel_values`)){if(u.length!==1)throw Error(`Expected a single input name, but got ${u.length} inputs: ${u}.`);let e=u[0];if(e in l)throw Error(`Input name ${e} already exists in the inputs.`);l[e]=l.pixel_values}let f=await this.model(l),p=null;if(o!==null)p=Pk[o];else if(this.processor.image_processor){for(let[e,t]of Object.entries(Pk))if(t in this.processor.image_processor){p=this.processor.image_processor[t].bind(this.processor.image_processor),o=e;break}}let m=this.model.config.id2label,h=[];if(!o){let e=f[d[0]];for(let t=0;t<c.length;++t){let n=c[t],r=e[t];r.data.some(e=>e<-1e-5||e>1.00001)&&r.sigmoid_();let i=await $d.fromTensor(r.mul_(255).to(`uint8`)).resize(n[1],n[0]);h.push({label:null,score:null,mask:i})}}else if(o===`panoptic`||o===`instance`){let e=p(f,t,n,r,i,a??c)[0],o=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(o.data.length);for(let n=0;n<o.data.length;++n)o.data[n]===t.id&&(e[n]=255);let n=new $d(e,o.dims[1],o.dims[0],1);h.push({score:t.score,label:m[t.label_id],mask:n})}}else if(o===`semantic`){let{segmentation:e,labels:t}=p(f,a??c)[0];for(let n of t){let t=new Uint8ClampedArray(e.data.length);for(let r=0;r<e.data.length;++r)e.data[r]===n&&(t[r]=255);let r=new $d(t,e.dims[1],e.dims[0],1);h.push({score:null,label:m[n],mask:r})}}else throw Error(`Subtask ${o} not supported.`);return h}};Object.freeze({"text-classification":{pipeline:gk,model:WO,default:{model:`Xenova/distilbert-base-uncased-finetuned-sst-2-english`},type:`text`},"token-classification":{pipeline:_k,model:GO,default:{model:`Xenova/bert-base-multilingual-cased-ner-hrl`},type:`text`},"question-answering":{pipeline:bk,model:QO,default:{model:`Xenova/distilbert-base-cased-distilled-squad`},type:`text`},"fill-mask":{pipeline:xk,model:ZO,default:{model:`onnx-community/ettin-encoder-32m-ONNX`,dtype:`fp32`},type:`text`},summarization:{pipeline:Ck,model:KO,default:{model:`Xenova/distilbart-cnn-6-6`},type:`text`},translation:{pipeline:wk,model:KO,default:{model:`Xenova/t5-small`},type:`text`},"text2text-generation":{pipeline:Sk,model:KO,default:{model:`Xenova/flan-t5-small`},type:`text`},"text-generation":{pipeline:Ek,model:XO,default:{model:`onnx-community/Qwen3-0.6B-ONNX`,dtype:`q4`},type:`text`},"zero-shot-classification":{pipeline:Dk,model:WO,default:{model:`Xenova/distilbert-base-uncased-mnli`},type:`text`},"audio-classification":{pipeline:Ok,model:sk,default:{model:`Xenova/wav2vec2-base-superb-ks`},type:`audio`},"zero-shot-audio-classification":{pipeline:kk,model:UO,default:{model:`Xenova/clap-htsat-unfused`},type:`multimodal`},"automatic-speech-recognition":{pipeline:Ak,model:[qO,ok],default:{model:`Xenova/whisper-tiny.en`},type:`multimodal`},"text-to-audio":{pipeline:jk,model:[YO,JO],default:{model:`onnx-community/Supertonic-TTS-ONNX`,dtype:`fp32`},type:`text`},"image-to-text":{pipeline:Mk,model:$O,default:{model:`Xenova/vit-gpt2-image-captioning`},type:`multimodal`},"image-classification":{pipeline:Nk,model:ek,default:{model:`Xenova/vit-base-patch16-224`},type:`multimodal`},"image-segmentation":{pipeline:Fk,model:[tk,nk,rk],default:{model:`Xenova/detr-resnet-50-panoptic`},type:`multimodal`},"background-removal":{pipeline:class extends Fk{async _call(e,t={}){let n=await fk(e),r=await super._call(e,t),i=n.map((e,t)=>{let n=e.clone();return n.putAlpha(r[t].mask),n});return Array.isArray(e)?i:i[0]}},model:[tk,nk,rk],default:{model:`Xenova/modnet`},type:`image`},"zero-shot-image-classification":{pipeline:class extends hk{async _call(e,t,{hypothesis_template:n=`This is a photo of {}`}={}){let r=Array.isArray(e),i=await fk(e),a=t.map(e=>n.replace(`{}`,e)),o=this.tokenizer(a,{padding:this.model.config.model_type!==`siglip`||`max_length`,truncation:!0}),{pixel_values:s}=await this.processor(i),c=await this.model({...o,pixel_values:s}),l=this.model.config.model_type===`siglip`?e=>e.sigmoid().data:e=>gc(e.data),u=[];for(let e of c.logits_per_image){let n=[...l(e)].map((e,n)=>({score:e,label:t[n]}));n.sort((e,t)=>t.score-e.score),u.push(n)}return r?u:u[0]}},model:UO,default:{model:`Xenova/clip-vit-base-patch32`},type:`multimodal`},"object-detection":{pipeline:class extends hk{async _call(e,{threshold:t=.9,percentage:n=!1}={}){let r=Array.isArray(e);if(r&&e.length!==1)throw Error(`Object detection pipeline currently only supports a batch size of 1.`);let i=await fk(e),a=n?null:i.map(e=>[e.height,e.width]),{pixel_values:o,pixel_mask:s}=await this.processor(i),c=await this.model({pixel_values:o,pixel_mask:s}),l=this.processor.image_processor.post_process_object_detection(c,t,a),{id2label:u}=this.model.config,d=l.map(e=>e.boxes.map((t,r)=>({score:e.scores[r],label:u[e.classes[r]],box:mk(t,!n)})));return r?d:d[0]}},model:ik,default:{model:`Xenova/detr-resnet-50`},type:`multimodal`},"zero-shot-object-detection":{pipeline:class extends hk{async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){let a=Array.isArray(e),o=await fk(e),s=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(o),l=[];for(let e=0;e<o.length;++e){let a=o[e],u=i?null:[[a.height,a.width]],d=c.pixel_values[e].unsqueeze_(0),f=await this.model({...s,pixel_values:d}),p;if(`post_process_grounded_object_detection`in this.processor){let e=this.processor.post_process_grounded_object_detection(f,s.input_ids,{box_threshold:n,text_threshold:n,target_sizes:u})[0];p=e.boxes.map((t,n)=>({score:e.scores[n],label:e.labels[n],box:mk(t,!i)}))}else{let e=this.processor.image_processor.post_process_object_detection(f,n,u,!0)[0];p=e.boxes.map((n,r)=>({score:e.scores[r],label:t[e.classes[r]],box:mk(n,!i)}))}p.sort((e,t)=>t.score-e.score),r!==null&&(p=p.slice(0,r)),l.push(p)}return a?l:l[0]}},model:ak,default:{model:`Xenova/owlvit-base-patch32`},type:`multimodal`},"document-question-answering":{pipeline:class extends hk{_default_generation_config={max_new_tokens:256};async _call(e,t,n={}){if(Array.isArray(e)){if(e.length!==1)throw Error(`Document Question Answering pipeline currently only supports a batch size of 1.`);e=e[0]}let r=(await fk(e))[0],{pixel_values:i}=await this.processor(r),a=`<s_docvqa><s_question>${t}</s_question><s_answer>`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,s=await this.model.generate({inputs:i,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...this._default_generation_config,...n}),c=this.tokenizer.batch_decode(s)[0].match(/<s_answer>(.*?)<\/s_answer>/),l=null;return c&&c.length>=2&&(l=c[1].trim()),[{answer:l}]}},model:ck,default:{model:`Xenova/donut-base-finetuned-docvqa`},type:`multimodal`},"image-to-image":{pipeline:class extends hk{async _call(e){let t=await fk(e),n=await this.processor(t),r=await this.model(n),i=[];for(let e of r.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to(`uint8`);i.push($d.fromTensor(t))}return Array.isArray(e)?i:i[0]}},model:lk,default:{model:`Xenova/swin2SR-classical-sr-x2-64`},type:`image`},"depth-estimation":{pipeline:class extends hk{async _call(e){let t=await fk(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;e<t.length;++e){let n=r[e],[a,o]=n.dims.slice(-2),[s,c]=t[e].size,l=(await pl(n.view(1,1,a,o),{size:[c,s],mode:`bilinear`})).view(c,s),u=l.min().item(),d=l.max().item(),f=l.sub(u).div_(d-u).mul_(255).to(`uint8`).unsqueeze(0),p=$d.fromTensor(f);i.push({predicted_depth:l,depth:p})}return Array.isArray(e)?i:i[0]}},model:uk,default:{model:`onnx-community/depth-anything-v2-small`},type:`image`},"feature-extraction":{pipeline:class extends hk{async _call(e,{pooling:t=`none`,normalize:n=!1,quantize:r=!1,precision:i=`binary`}={}){let a=this.tokenizer(e,{padding:!0,truncation:!0}),o=await this.model(a),s=o.last_hidden_state??o.logits??o.token_embeddings;switch(t){case`none`:break;case`mean`:s=vl(s,a.attention_mask);break;case`first_token`:case`cls`:s=s.slice(null,0);break;case`last_token`:case`eos`:s=s.slice(null,-1);break;default:throw Error(`Pooling method '${t}' not supported.`)}return n&&(s=s.normalize(2,-1)),r&&(s=Il(s,i)),s}},model:UO,default:{model:`onnx-community/all-MiniLM-L6-v2-ONNX`,dtype:`fp32`},type:`text`},"image-feature-extraction":{pipeline:class extends hk{async _call(e,{pool:t=null}={}){let n=await fk(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),a;if(t){if(!(`pooler_output`in i))throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`);a=i.pooler_output}else a=i.last_hidden_state??i.logits??i.image_embeds;return a}},model:[dk,UO],default:{model:`onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX`,dtype:`fp32`},type:`image`}}),Object.freeze({"sentiment-analysis":`text-classification`,ner:`token-classification`,asr:`automatic-speech-recognition`,"text-to-speech":`text-to-audio`,embeddings:`feature-extraction`});var Ik=e=>e>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,Lk=class{put(e){throw Error(`Not implemented`)}end(){throw Error(`Not implemented`)}},Rk=N.IS_PROCESS_AVAILABLE?e=>h.default.stdout.write(e):e=>console.log(e),zk=class extends Lk{constructor(e,{skip_prompt:t=!1,callback_function:n=null,token_callback_function:r=null,skip_special_tokens:i=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=n??Rk,this.token_callback_function=r,this.decode_kwargs={skip_special_tokens:i,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error(`TextStreamer only supports batch size of 1`);let t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let n=e[0];if(this.token_callback_function?.(n),n.length===1&&this.special_ids.has(n[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(e,!1),this.token_cache=[],this.print_len=0}let e=this.tokenizer.decode(n,this.decode_kwargs);this.on_finalized_text(e,!1);return}this.token_cache=vi(this.token_cache,n);let r=this.tokenizer.decode(this.token_cache,this.decode_kwargs),i;t||r.endsWith(`
|
|
53
53
|
`)?(i=r.slice(this.print_len),this.token_cache=[],this.print_len=0):r.length>0&&Ik(r.charCodeAt(r.length-1))?(i=r.slice(this.print_len),this.print_len+=i.length):(i=r.slice(this.print_len,r.lastIndexOf(` `)+1),this.print_len+=i.length),this.on_finalized_text(i,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e=``,this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===Rk&&N.IS_PROCESS_AVAILABLE&&this.callback_function?.(`
|
|
54
54
|
`)}};Object.keys(sl);const Bk=`shadow-claw-browser-models`;function Vk(){return typeof caches<`u`&&typeof caches.open==`function`}function Hk(e){return`${e}?__sc_meta=1`}function Uk(e,t){return`${e}?__sc_chunk=${t}`}async function Wk(e,t=Bk){if(!Vk())return null;try{let n=await(await caches.open(t)).match(Hk(e));if(!n?.body)return null;let r=await n.text();return JSON.parse(r)}catch{return null}}async function Gk(e,t,n=Bk){if(Vk())try{await(await caches.open(n)).put(Hk(e),new Response(JSON.stringify(t),{headers:{"Content-Type":`application/json`}}))}catch(e){console.error(`writePartialMeta error:`,e)}}async function Kk(e,t,n,r=Bk){if(Vk())try{await(await caches.open(r)).put(Uk(e,t),new Response(new Blob([n]),{headers:{"Content-Type":`application/octet-stream`,"Content-Length":String(n.byteLength)}}))}catch(e){console.error(`flushChunkToCache error:`,e)}}function qk(e,t,n=Bk){let r=0,i=null;return new ReadableStream({async pull(a){if(i){let{done:e,value:t}=await i.read();if(!e){a.enqueue(t);return}i=null,r++}if(r>=t.chunks){a.close();return}try{let t=await(await caches.open(n)).match(Uk(e,r));if(!t?.body){a.error(Error(`ModelCache: missing cache chunk ${r} for ${e}`));return}i=t.body.getReader();let{done:o,value:s}=await i.read();o?(i=null,r++):a.enqueue(s)}catch(e){a.error(e)}},cancel(){i&&=(i.cancel(),null)}})}function Jk(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(new DOMException(`Aborted`,`AbortError`))};t?.addEventListener(`abort`,a,{once:!0})})}function Yk(e){return Math.min(15e3,1e3*2**(Math.max(1,e)-1))}async function Xk(e,t,n,r,i=globalThis.fetch?globalThis.fetch.bind(globalThis):fetch){let a=r?.cacheName??`shadow-claw-browser-models`,o=r?.chunkSize??16777216,s=r?.maxAttempts??6,c=r?.headers??{},l=Vk(),u=0,d=0,f=null,p=!1,m=e;if(l){let t=await Wk(e,a);t&&!t.complete&&(u=t.chunks,d=t.received,f=t.total,p=t.acceptsRanges,t.resolvedUrl&&(m=t.resolvedUrl))}let h=null,g=null;for(let e=1;e<=s;e++){if(n?.aborted)throw new DOMException(`Aborted`,`AbortError`);let t={...c};d>0&&p&&(t.Range=`bytes=${d}-`);try{g=await i(m,{signal:n,headers:t})}catch(t){if(n?.aborted||t?.name===`AbortError`)throw t;if(h=t,e<s){await Jk(Yk(e),n);continue}break}if(g.url&&(m=g.url),t.Range&&g.status===200&&(u=0,d=0),g.status!==200&&g.status!==206){if(h=Error(`ModelCache: Failed to fetch model from '${m}': ${g.status} ${g.statusText}`),g.status>=500&&e<s){await Jk(Yk(e),n);continue}throw h}if(!g.body)throw Error(`ModelCache: Failed to fetch model from '${m}': No response body`);h=null;break}if(h||!g||!g.body)throw Error(`ModelCache: failed to download model from '${e}' after ${s} attempts: ${h?.message??String(h)}`);if(f==null)if(p=g.status===206||g.headers.get(`accept-ranges`)===`bytes`,g.status===206){let e=g.headers.get(`content-range`)?.match(/\/\s*(\d+)\s*$/);e&&(f=Number(e[1]))}else{let e=g.headers.get(`content-length`),t=e?Number(e):NaN;f=Number.isFinite(t)&&t>0?t:null}l&&await Gk(e,{chunks:u,received:d,total:f,acceptsRanges:p,complete:!1,resolvedUrl:m},a);let _=g.body;return new ReadableStream({async start(r){try{if(l&&u>0){let i=await caches.open(a),o=0;for(let a=0;a<u;a++){if(n?.aborted)throw new DOMException(`Aborted`,`AbortError`);let s=await i.match(Uk(e,a));if(s?.body){let e=s.body.getReader();for(;;){let{done:n,value:i}=await e.read();if(n)break;r.enqueue(i),o+=i.byteLength,t?.(o,f)}}else if(s&&typeof s.arrayBuffer==`function`){let e=await s.arrayBuffer(),n=new Uint8Array(e);r.enqueue(n),o+=n.byteLength,t?.(o,f)}}}let i=[],s=0,c=d;async function h(){if(s===0)return;let t=new Uint8Array(s),n=0;for(let e of i)t.set(e,n),n+=e.byteLength;i=[],s=0,l?(await Kk(e,u,t,a),u++,d+=t.byteLength,await Gk(e,{chunks:u,received:d,total:f,acceptsRanges:p,complete:!1,resolvedUrl:m},a)):(u++,d+=t.byteLength)}let g=_.getReader();try{for(;;){if(n?.aborted)throw await g.cancel(),new DOMException(`Aborted`,`AbortError`);let{done:e,value:a}=await g.read();if(e)break;r.enqueue(a),i.push(a),s+=a.byteLength,c+=a.byteLength,t?.(c,f),s>=o&&await h()}await h(),l&&await Gk(e,{chunks:u,received:d,total:f,acceptsRanges:p,complete:!0,resolvedUrl:m},a),t?.(c,f,!0),r.close()}catch(e){try{await g.cancel()}catch{}throw e}}catch(e){r.error(e)}}})}async function Zk(e,t,n,r,i=globalThis.fetch?globalThis.fetch.bind(globalThis):fetch){let a=r?.cacheName??`shadow-claw-browser-models`;try{let n=await Wk(e,a);if(n?.complete)return t?.(n.received,n.received,!0),qk(e,n,a)}catch(e){console.warn(`loadModelStream cache check failed, falling back to download:`,e)}return Xk(e,t,n,r,i)}function Qk(e=globalThis.fetch?globalThis.fetch.bind(globalThis):fetch,t,n){let r=t?.cacheName??`shadow-claw-browser-models`;return async function(i,a){let o=typeof i==`string`?i:i instanceof URL?i.toString():i.url,s=(a?.method||(typeof i==`object`&&`method`in i?i.method:`GET`)||`GET`).toUpperCase(),c=a?.headers||(typeof i==`object`&&`headers`in i?i.headers:void 0);if(c instanceof Headers?c.has(`Range`)||c.has(`range`):c&&typeof c==`object`&&(`Range`in c||`range`in c))return e(i,{...a||{},cache:`no-store`});if(s!==`GET`||!Vk())return e(i,a);try{let i=await Wk(o,r);if(i?.complete){n?.(o,i.received,i.received,!0);let e=qk(o,i,r);return new Response(e,{status:200,statusText:`OK`,headers:{"Content-Type":`application/octet-stream`,...i.total!=null&&i.total>0?{"Content-Length":String(i.total)}:{}}})}let s=await Zk(o,(e,t,r)=>{n?.(o,e,t,!!r)},a?.signal??void 0,{cacheName:r,...t||{}},e),c=(await Wk(o,r))?.total;return new Response(s,{status:200,statusText:`OK`,headers:{"Content-Type":`application/octet-stream`,...c!=null&&c>0?{"Content-Length":String(c)}:{}}})}catch(t){return console.warn(`[ModelCacheFetch] Cache stream failed for ${o}, falling back to native fetch:`,t),e(i,a)}}}var $k=Object.defineProperty,eA=(e,t,n)=>t in e?$k(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,tA=(e,t,n)=>(eA(e,typeof t==`symbol`?t:t+``,n),n),nA=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`});nA.OpenStatement,nA.CloseStatement,nA.OpenExpression,nA.CloseExpression,nA.OpenParen,nA.CloseParen,nA.OpenCurlyBracket,nA.CloseCurlyBracket,nA.OpenSquareBracket,nA.CloseSquareBracket,nA.Comma,nA.Dot,nA.Colon,nA.Pipe,nA.ComparisonBinaryOperator,nA.ComparisonBinaryOperator,nA.ComparisonBinaryOperator,nA.ComparisonBinaryOperator,nA.ComparisonBinaryOperator,nA.ComparisonBinaryOperator,nA.AdditiveBinaryOperator,nA.AdditiveBinaryOperator,nA.AdditiveBinaryOperator,nA.MultiplicativeBinaryOperator,nA.MultiplicativeBinaryOperator,nA.MultiplicativeBinaryOperator,nA.Equals;function rA(e){return e.replace(/\b\w/g,e=>e.toUpperCase())}function iA(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function aA(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?RegExp(`(?=)`,`gu`):new RegExp(iA(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var oA=new Map,sA=class{type=`RuntimeValue`;value;get builtins(){return oA}constructor(e=void 0){this.value=e}__bool__(){return new dA(!!this.value)}toString(){return String(this.value)}},cA=class extends sA{type=`IntegerValue`},lA=class extends sA{type=`FloatValue`;toString(){return this.value%1==0?this.value.toFixed(1):this.value.toString()}},uA=class extends sA{type=`StringValue`;_builtins;get builtins(){return this._builtins??=new Map([[`upper`,new vA(()=>new uA(this.value.toUpperCase()))],[`lower`,new vA(()=>new uA(this.value.toLowerCase()))],[`strip`,new vA(()=>new uA(this.value.trim()))],[`title`,new vA(()=>new uA(rA(this.value)))],[`capitalize`,new vA(()=>new uA(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new cA(this.value.length)],[`rstrip`,new vA(()=>new uA(this.value.trimEnd()))],[`lstrip`,new vA(()=>new uA(this.value.trimStart()))],[`startswith`,new vA(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof uA)return new dA(this.value.startsWith(t.value));if(t instanceof _A){for(let e of t.value){if(!(e instanceof uA))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new dA(!0)}return new dA(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new vA(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof uA)return new dA(this.value.endsWith(t.value));if(t instanceof _A){for(let e of t.value){if(!(e instanceof uA))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new dA(!0)}return new dA(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new vA(e=>{let t=e[0]??new yA;if(!(t instanceof uA||t instanceof yA))throw Error(`sep argument must be a string or null`);let n=e[1]??new cA(-1);if(!(n instanceof cA))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof yA){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new _A(r.map(e=>new uA(e)))})],[`replace`,new vA(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof uA&&n instanceof uA))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new yA:e[2]:new yA,!(r instanceof cA||r instanceof yA))throw Error(`replace() count argument must be a number or null`);return new uA(aA(this.value,t.value,n.value,r.value))})]])}},dA=class extends sA{type=`BooleanValue`},fA=/[\x7f-\uffff]/g;function pA(e){return e.replace(fA,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function mA(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=pA(t)),t}case`ArrayValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=`
|
|
55
|
-
`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>mA(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}else{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=pA(s));let c=`${s}${l}${mA(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var hA=class extends sA{type=`ObjectValue`;_builtins;__bool__(){return new dA(this.value.size>0)}get builtins(){return this._builtins??=new Map([[`get`,new vA(([e,t])=>{if(!(e instanceof uA))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new yA})],[`items`,new vA(()=>this.items())],[`keys`,new vA(()=>this.keys())],[`values`,new vA(()=>this.values())],[`dictsort`,new vA(e=>{let t=new Map,n=e.filter(e=>e instanceof gA?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new dA(!1);if(!(r instanceof dA))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new uA(`key`);if(!(i instanceof uA))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new dA(!1);if(!(a instanceof dA))throw Error(`reverse must be a boolean`);return new _A(Array.from(this.value.entries()).map(([e,t])=>new _A([new uA(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=SA(o,s,r.value);return a.value?-c:c}))})]])}items(){return new _A(Array.from(this.value.entries()).map(([e,t])=>new _A([new uA(e),t])))}keys(){return new _A(Array.from(this.value.keys()).map(e=>new uA(e)))}values(){return new _A(Array.from(this.value.values()))}toString(){return mA(this,{},0,!1)}},gA=class extends hA{type=`KeywordArgumentsValue`},_A=class extends sA{type=`ArrayValue`;_builtins;get builtins(){return this._builtins??=new Map([[`length`,new cA(this.value.length)]])}__bool__(){return new dA(this.value.length>0)}toString(){return mA(this,{},0,!1)}},vA=class extends sA{type=`FunctionValue`},yA=class extends sA{type=`NullValue`},bA=class extends sA{type=`UndefinedValue`},xA=class{constructor(e){this.parent=e}variables=new Map([[`namespace`,new vA(e=>{if(e.length===0)return new hA(new Map);if(e.length!==1||!(e[0]instanceof hA))throw Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=xA.TESTS;set(e,t){return this.declareVariable(e,CA(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new bA}catch{return new bA}}};tA(xA,`TESTS`,new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof vA],[`odd`,e=>{if(!(e instanceof cA))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof cA))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof cA||e instanceof lA],[`integer`,e=>e instanceof cA],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof hA],[`sequence`,e=>e instanceof _A||e instanceof hA||e instanceof uA],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]));function SA(e,t,n=!1){if(e instanceof yA&&t instanceof yA)return 0;if(e instanceof yA||t instanceof yA)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof bA&&t instanceof bA)return 0;if(e instanceof bA||t instanceof bA)throw Error(`Cannot compare ${e.type} with ${t.type}`);let r=e=>e instanceof cA||e instanceof lA||e instanceof dA,i=e=>e instanceof dA?+!!e.value:e.value;if(r(e)&&r(t)){let n=i(e),r=i(t);return n<r?-1:+(n>r)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),r<i?-1:+(r>i)}default:throw Error(`Cannot compare type: ${e.type}`)}}function CA(e){switch(typeof e){case`number`:return Number.isInteger(e)?new cA(e):new lA(e);case`string`:return new uA(e);case`boolean`:return new dA(e);case`undefined`:return new bA;case`object`:return e===null?new yA:Array.isArray(e)?new _A(e.map(CA)):new hA(new Map(Object.entries(e).map(([e,t])=>[e,CA(t)])));case`function`:return new vA((t,n)=>CA(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}new class{loading=!1;models=new Map;getModelInfo(e){return this.models.get(e.
|
|
55
|
+
`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>mA(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}else{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=pA(s));let c=`${s}${l}${mA(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var hA=class extends sA{type=`ObjectValue`;_builtins;__bool__(){return new dA(this.value.size>0)}get builtins(){return this._builtins??=new Map([[`get`,new vA(([e,t])=>{if(!(e instanceof uA))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new yA})],[`items`,new vA(()=>this.items())],[`keys`,new vA(()=>this.keys())],[`values`,new vA(()=>this.values())],[`dictsort`,new vA(e=>{let t=new Map,n=e.filter(e=>e instanceof gA?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new dA(!1);if(!(r instanceof dA))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new uA(`key`);if(!(i instanceof uA))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new dA(!1);if(!(a instanceof dA))throw Error(`reverse must be a boolean`);return new _A(Array.from(this.value.entries()).map(([e,t])=>new _A([new uA(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=SA(o,s,r.value);return a.value?-c:c}))})]])}items(){return new _A(Array.from(this.value.entries()).map(([e,t])=>new _A([new uA(e),t])))}keys(){return new _A(Array.from(this.value.keys()).map(e=>new uA(e)))}values(){return new _A(Array.from(this.value.values()))}toString(){return mA(this,{},0,!1)}},gA=class extends hA{type=`KeywordArgumentsValue`},_A=class extends sA{type=`ArrayValue`;_builtins;get builtins(){return this._builtins??=new Map([[`length`,new cA(this.value.length)]])}__bool__(){return new dA(this.value.length>0)}toString(){return mA(this,{},0,!1)}},vA=class extends sA{type=`FunctionValue`},yA=class extends sA{type=`NullValue`},bA=class extends sA{type=`UndefinedValue`},xA=class{constructor(e){this.parent=e}variables=new Map([[`namespace`,new vA(e=>{if(e.length===0)return new hA(new Map);if(e.length!==1||!(e[0]instanceof hA))throw Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=xA.TESTS;set(e,t){return this.declareVariable(e,CA(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new bA}catch{return new bA}}};tA(xA,`TESTS`,new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof vA],[`odd`,e=>{if(!(e instanceof cA))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof cA))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof cA||e instanceof lA],[`integer`,e=>e instanceof cA],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof hA],[`sequence`,e=>e instanceof _A||e instanceof hA||e instanceof uA],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]));function SA(e,t,n=!1){if(e instanceof yA&&t instanceof yA)return 0;if(e instanceof yA||t instanceof yA)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof bA&&t instanceof bA)return 0;if(e instanceof bA||t instanceof bA)throw Error(`Cannot compare ${e.type} with ${t.type}`);let r=e=>e instanceof cA||e instanceof lA||e instanceof dA,i=e=>e instanceof dA?+!!e.value:e.value;if(r(e)&&r(t)){let n=i(e),r=i(t);return n<r?-1:+(n>r)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),r<i?-1:+(r>i)}default:throw Error(`Cannot compare type: ${e.type}`)}}function CA(e){switch(typeof e){case`number`:return Number.isInteger(e)?new cA(e):new lA(e);case`string`:return new uA(e);case`boolean`:return new dA(e);case`undefined`:return new bA;case`object`:return e===null?new yA:Array.isArray(e)?new _A(e.map(CA)):new hA(new Map(Object.entries(e).map(([e,t])=>[e,CA(t)])));case`function`:return new vA((t,n)=>CA(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}new class{loading=!1;models=new Map;getModelInfo(e){if(!e||typeof e!=`string`)return null;let t=e.toLowerCase().trim(),n=this.models.get(t);if(n)return n;if(t.includes(`/`)){let e=t.split(`/`).pop();if(e&&this.models.has(e))return this.models.get(e)}else for(let[e,n]of this.models.entries())if(e.endsWith(`/${t}`))return n;if(t.includes(`:`)){let e=t.split(`:`)[0],n=this.getModelInfo(e);if(n)return n}return null}registerModelInfo(e,t){this.models.set(e.toLowerCase(),t)}clear(){this.models.clear()}async fetchModelInfo(e,t,n){if(e.modelsUrl){this.loading=!0;try{let r=new Headers;if(r.set(`Content-Type`,`application/json`),e.headers)for(let[t,n]of Object.entries(e.headers))r.set(t,n);if(n)for(let[e,t]of Object.entries(n))r.set(e,t);if(t&&e.apiKeyHeader){let n=e.apiKeyHeaderFormat;r.set(e.apiKeyHeader,n?n.replace(`{key}`,t):t)}let i=await fetch(e.modelsUrl,{headers:r});if(!i.ok)throw Error(`HTTP ${i.status} ${i.statusText}`);let a=await i.json(),o=Array.isArray(a.data)?a.data:Array.isArray(a.models)?a.models:[];for(let e of o){if(!e.id)continue;let t=e.context_length??e.context_window??0,n=e.max_completion_tokens||e.per_request_limits?.completion_tokens||e.top_provider?.max_completion_tokens||null,r=typeof e.supports_tools==`boolean`?e.supports_tools:typeof e.supportsTools==`boolean`?e.supportsTools:void 0,i=this.extractModalities(e,`input`),a=this.extractModalities(e,`output`),o=this.modalitiesInclude(i,`image`,`vision`),s=this.modalitiesInclude(i,`audio`,`voice`,`hearing`),c=this.modalitiesInclude(i,`video`),l=e.id===`openrouter/free`||this.supportedParametersInclude(e,`image`,`vision`,`audio`,`tool`,`structured`),u=this.extractReasoning(e),d=typeof e.supports_prompt_caching==`boolean`?e.supports_prompt_caching:typeof e.supportsPromptCaching==`boolean`?e.supportsPromptCaching:this.supportedParametersInclude(e,`cache_control`,`prompt_caching`)?!0:void 0;!t&&Array.isArray(e.providers)&&e.providers.length>0&&(t=e.providers[0]?.context_length||0),this.registerModelInfo(e.id,{contextWindow:t,maxOutput:n,...r!==void 0&&{supportsTools:r},...i.length>0&&{inputModalities:i},...a.length>0&&{outputModalities:a},...o!==void 0&&{supportsImageInput:o},...s!==void 0&&{supportsAudioInput:s},...c!==void 0&&{supportsVideoInput:c},...u&&{reasoning:u},...l&&{routesByRequestFeatures:l},...d!==void 0&&{supportsPromptCaching:d}})}o.length>0&&console.log(`[ModelRegistry] Registered ${o.length} models for provider "${e.id}"`)}catch(t){console.error(`[ModelRegistry] Error fetching models for ${e.id}:`,t)}finally{this.loading=!1}}}extractModalities(e,t){let n=t===`input`?e.input_modalities||e.inputModalities:e.output_modalities||e.outputModalities,r=e.architecture||{},i=t===`input`?r.input_modalities||r.inputModalities:r.output_modalities||r.outputModalities,a=typeof r.modality==`string`?r.modality:``,o=this.parseArchitectureModality(a,t),s=[...this.normalizeStringArray(n),...this.normalizeStringArray(i),...o];return Array.from(new Set(s))}extractReasoning(e){let t=e?.reasoning;if(!t||typeof t!=`object`)return;let n=this.normalizeStringArray(t.supported_efforts),r=typeof t.default_effort==`string`?t.default_effort.toLowerCase():void 0,i=typeof t.default_enabled==`boolean`?t.default_enabled:void 0,a=typeof t.supports_max_tokens==`boolean`?t.supports_max_tokens:void 0,o=typeof t.mandatory==`boolean`?t.mandatory:void 0;if(!(n.length===0&&r===void 0&&i===void 0&&a===void 0&&o===void 0))return{...n.length>0&&{supportedEfforts:n},...r!==void 0&&{defaultEffort:r},...i!==void 0&&{defaultEnabled:i},...a!==void 0&&{supportsMaxTokens:a},...o!==void 0&&{mandatory:o}}}modalitiesInclude(e,...t){if(e.length!==0)return t.some(t=>e.some(e=>e.includes(t)))}normalizeStringArray(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.toLowerCase()):[]}parseArchitectureModality(e,t){if(!e)return[];let[n=``,r=``]=e.toLowerCase().split(`->`).map(e=>e.trim());return(t===`input`?n:r).split(/[+,/\s]+/).map(e=>e.trim()).filter(Boolean)}supportedParametersInclude(e,...t){let n=this.normalizeStringArray(e.supported_parameters||e.supportedParameters);return t.some(e=>n.some(t=>t.includes(e)))}};function wA(e){return typeof e==`string`?e:e?Array.isArray(e)?e.map(e=>{if(!e)return``;if(typeof e==`string`)return e;if(e.type===`text`)return e.text||e.value||``;if(e.type===`tool_use`)return`[TOOL_CALL ${e.name}] ${JSON.stringify(e.input||{})}`;if(e.type===`tool_result`){let t=typeof e.content==`string`?e.content:JSON.stringify(e.content||``);return`[TOOL_RESULT ${e.tool_use_id||``}] ${t}`}return e.type===`attachment`?`[ATTACHMENT ${e.mediaType||`file`}] ${e.fileName||`attachment`}`:``}).filter(Boolean).join(`
|
|
56
56
|
`):typeof e==`object`?JSON.stringify(e):String(e):``}function TA(e){if(!(!e||!Array.isArray(e)||e.length===0))return e.map(e=>e.type===`function`&&e.function?e:{type:`function`,function:{name:e.name,description:e.description||``,parameters:e.input_schema||e.parameters||{type:`object`,properties:{}}}})}function EA(e,t){let n=String(t||``).trim(),r=[];for(let t of e){if(!t)continue;let e=String(t.role||`user`).toLowerCase(),i=wA(t.content);e===`system`?n=n?`${n}\n\n${i}`:i:e===`tool`?r.push({role:`tool`,content:i}):e===`assistant`||e===`model`?r.push({role:`assistant`,content:i,...t.tool_calls?{tool_calls:t.tool_calls}:{}}):r.push({role:`user`,content:i})}let i=[];for(let e of r)if(i.length>0&&i[i.length-1].role===e.role&&e.role!==`tool`){let t=i[i.length-1];t.content=t.content?`${t.content}\n\n${e.content}`:e.content,e.tool_calls&&(t.tool_calls=[...t.tool_calls||[],...e.tool_calls])}else i.push({...e});i.length>0&&i[0].role===`assistant`&&i.unshift({role:`user`,content:`Hello`}),i.length===0&&!n&&i.push({role:`user`,content:`Hello`});let a=[];return n&&a.push({role:`system`,content:n}),a.push(...i),a}function DA(e){let t=/(?:^|[-_\/.])(\d+(?:\.\d+)?)b(?:[-_\/.]|$)/i.exec(e);if(!t)return null;let n=Number(t[1]);return!Number.isFinite(n)||n<=0?null:n}function OA(e){return e===`q4f16`?`q4f16`:e===`q4`?`q4`:e===`q8`?`q8`:e===`fp16`?`fp16`:e===`fp32`?`fp32`:e===`memory`?`memory`:e===`balanced`?`balanced`:e===`quality`?`quality`:`auto`}function kA(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function AA(e,t,n,r=`auto`){let i=e===`webgpu`,a=e.startsWith(`webnn`);if(r===`q4f16`)return kA([`q4f16`,`q4`,`fp16`]);if(r===`q4`)return kA([`q4`,`q4f16`,`q8`,`fp16`]);if(r===`q8`)return kA([`q8`,`q4`,`fp16`]);if(r===`fp16`)return kA([`fp16`,`q4f16`,`q4`]);if(r===`fp32`)return kA([`fp32`,`fp16`,`q8`,`q4`]);if(i||a)return r===`quality`?[`fp16`,`q4f16`,`q4`]:r===`memory`?[`q4`,`q4f16`,`fp16`]:[`q4f16`,`q4`,`fp16`];if(r===`quality`)return[`fp32`,`fp16`,`q8`,`q4`];if(r===`balanced`)return[`q4f16`,`q4`,`q8`,`fp16`,`fp32`];if(r===`memory`)return[`q4`,`q8`,`fp16`];let o=[`q4f16`,`q4`,`q8`,`fp16`],s=DA(t);return s!==null&&s<=.6&&typeof n==`number`&&n>=16&&o.push(`fp32`),kA(o)}let jA=null;const MA=async()=>{if(jA)return jA;let e=`huggingface.co`,t=`hf-mirror.com`,n=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(),3e3);try{let r=await fetch(`https://${e}/webml/models-moved/resolve/main/01.onnx`,{method:`HEAD`,signal:t.signal,cache:`no-store`});return clearTimeout(n),r.ok}catch(t){return console.log(`Error reaching ${e}:`,t),clearTimeout(n),!1}};return await n(e)?(jA=e,e):await n(t)?(console.log(`Hugging Face main domain unreachable. Switching to mirror: ${t}`),jA=t,t):(jA=e,e)};function NA(){let e=typeof location<`u`?location.hostname:``;return e===`localhost`||e===`127.0.0.1`||e===`::1`||/^10\./.test(e)||/^172\.(1[6-9]|2\d|3[01])\./.test(e)||/^192\.168\./.test(e)||e.endsWith(`.local`)?!1:e.includes(`.`)}NA()?(P.allowLocalModels=!1,P.allowRemoteModels=!0,P.useBrowserCache=!1,P.useWasmCache=!0,P.fetch=Qk(self.fetch.bind(self))):(P.allowLocalModels=!0,P.allowRemoteModels=!0,P.useBrowserCache=!1,P.useWasmCache=!0,P.fetch=Qk(self.fetch.bind(self))),(async()=>{try{await MA()===`hf-mirror.com`&&(P.remoteHost=`https://hf-mirror.com`,console.log(`Transformers.js: Using Hugging Face mirror:`,P.remoteHost))}catch(e){console.error(`Transformers.js: Failed to initialize domain mirroring:`,e)}})();let PA=null,FA=null,IA=null,LA=null;async function RA(e,t,n,r){if(!(IA&&FA===e&&PA===t)){if(IA)try{await IA.dispose?.()}catch(e){console.warn(`Failed to dispose old model:`,e)}FA=e,PA=t,self.postMessage({payload:{groupId:n,message:`Loading ${e}...`,progress:0,status:`running`},type:`progress`});try{try{LA=await jm.from_pretrained(e,{progress_callback:e=>{e.status===`progress`&&self.postMessage({payload:{groupId:n,message:`Downloading processor... ${Math.round(e.progress)}%`,progress:e.progress/100,status:`running`},type:`progress`})}})}catch(t){console.warn(`AutoProcessor failed, falling back to AutoTokenizer:`,t),LA=await q.from_pretrained(e,{progress_callback:e=>{e.status===`progress`&&self.postMessage({payload:{groupId:n,message:`Downloading tokenizer... ${Math.round(e.progress)}%`,progress:e.progress/100,status:`running`},type:`progress`})}})}let i=t===`webgpu`,a=t.startsWith(`webnn`),o=navigator,s=typeof o.deviceMemory==`number`?o.deviceMemory:null,c=t;if(t===`auto`){let e=!1;if(typeof navigator<`u`&&`gpu`in navigator)try{let t=await navigator.gpu.requestAdapter({powerPreference:`high-performance`});if(t&&t.isFallbackAdapter!==!0&&(!t.features||t.features.has(`shader-f16`))){let n=t.info||(typeof t.requestAdapterInfo==`function`?await t.requestAdapterInfo():null),r=(n?.vendor||``).toLowerCase(),i=(n?.architecture||``).toLowerCase(),a=(n?.description||``).toLowerCase(),o=(n?.device||``).toLowerCase(),s=(n?.adapterType||n?.deviceType||n?.type||``).toLowerCase();s!==`cpu`&&s!==`software`&&i!==`swiftshader`&&i!==`llvmpipe`&&i!==`softpipe`&&i!==`lavapipe`&&i!==`cpu`&&!r.includes(`swiftshader`)&&!a.includes(`llvmpipe`)&&!a.includes(`softpipe`)&&!a.includes(`lavapipe`)&&!a.includes(`software`)&&!a.includes(`basic render`)&&!o.includes(`llvmpipe`)&&!o.includes(`softpipe`)&&!o.includes(`lavapipe`)&&!o.includes(`swiftshader`)&&!o.includes(`basic render`)&&(e=!0)}}catch{e=!1}c=e?`webgpu`:`wasm`}else c=a?`webnn`:i?`webgpu`:`wasm`;let l=OA(r),u=AA(c,e,s,l),d=null;for(let t of u)try{IA=await XO.from_pretrained(e,{device:c,dtype:t,progress_callback:e=>{e.status===`progress`&&self.postMessage({type:`progress`,payload:{groupId:n,status:`running`,progress:e.progress/100,message:`Downloading model weights (${t})... ${Math.round(e.progress)}%`}})},session_options:{logSeverityLevel:0}});break}catch(e){d=e,console.warn(`Model load failed for dtype '${t}', trying next candidate...`,e)}if(!IA&&(c===`webgpu`||c===`webnn`)){console.warn(`Hardware accelerated backend (${c}) failed. Retrying with CPU/WASM fallback (q4)...`),c=`wasm`;let t=AA(`wasm`,e,s,l);for(let r of t)try{IA=await XO.from_pretrained(e,{device:`wasm`,dtype:r,progress_callback:e=>{e.status===`progress`&&self.postMessage({type:`progress`,payload:{groupId:n,status:`running`,progress:e.progress/100,message:`Downloading model weights (${r})... ${Math.round(e.progress)}%`}})},session_options:{logSeverityLevel:0}});break}catch(e){d=e,console.warn(`WASM fallback load failed for dtype '${r}', trying next candidate...`,e)}}if(!IA){let t=d instanceof Error?d.message:String(d||`unknown error`);throw Error(`Failed to load model '${e}' with supported browser dtypes (${u.join(`, `)}). Last error: ${t}`)}self.postMessage({type:`progress`,payload:{groupId:n,message:`Model ready.`,progress:1,status:`done`}})}catch(e){console.error(`Failed to load model:`,e);let t=e.message||String(e);throw t.includes(`401`)&&(t=`HuggingFace returned 401 Unauthorized. This model might be gated (requires login) or the service worker proxy rules are interfering. Please ensure you are not using a gated model or hard-reload to update proxy rules.`),Error(t)}}}async function zA(e,t,n,r,i){if(!IA||!LA)throw Error(`Model not loaded`);let a=LA.tokenizer||LA,o=EA(e),s=TA(r),c=a.apply_chat_template(o,{add_generation_prompt:!0,return_dict:!0,...s?{tools:s}:{}}),l,u;try{let e=a.encode(`<think></think>`,{add_special_tokens:!1});e&&e.length===2&&(l=Number(e[0]),u=Number(e[1]))}catch{}let d=`answering`,f=e=>{if(!(l===void 0||!e?.length))switch(Number(e[0])){case l:d=`thinking`;break;case u:d=`answering`;break}},p=``,m=new zk(a,{callback_function:e=>{d===`thinking`?self.postMessage({payload:{groupId:n,text:e},type:`thinking-chunk`}):(p+=e,self.postMessage({payload:{groupId:n,text:e},type:`chunk`}))},skip_prompt:!0,skip_special_tokens:!0,token_callback_function:f});await IA.generate({...c,max_new_tokens:t,signal:i,streamer:m}),self.postMessage({payload:{groupId:n,text:p},type:`done`})}self.onmessage=async e=>{let{type:t,payload:n}=e.data;try{switch(t){case`load`:await RA(n.modelId,n.device,n.groupId,n.dtypeStrategy);break;case`generate`:await zA(n.messages,n.maxTokens,n.groupId,n.tools);break;case`dispose`:IA&&(await IA.dispose?.(),IA=null,LA=null,FA=null,PA=null);break}}catch(e){self.postMessage({type:`error`,payload:{error:e.message||String(e),groupId:n?.groupId}})}};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{o as t}from"./config-BqecTktB.js";import{t as n}from"./tools-CcgG5XuA.js";import"./tools-B-PzsLc2.js";const r=`Tool was executed but the invocation failed. For example, the script function threw an error`,i=/^[A-Za-z0-9_.-]{1,128}$/u;function a(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function o(e){if(typeof e==`symbol`)throw TypeError(`Symbol values cannot be converted to a DOMString`);return String(e)}function s(e){let t=Reflect.get(e,`name`),n=Reflect.get(e,`description`),r=Reflect.get(e,`title`);if(t===void 0)throw TypeError(`Tool "name" is required`);if(n===void 0)throw TypeError(`Tool "description" is required`);let i=Reflect.get(e,`annotations`),s=a(i)?i:{},c=Reflect.get(e,`inputSchema`),l=Reflect.get(e,`outputSchema`),u=Reflect.get(e,`execute`);return{name:o(t),...r===void 0?{}:{title:o(r).toWellFormed()},description:o(n),...c===void 0?{}:{inputSchema:c},...l===void 0?{}:{outputSchema:l},execute:u,...i===void 0?{}:{annotations:{...s.title===void 0?{}:{title:o(s.title).toWellFormed()},readOnlyHint:!!s.readOnlyHint,...s.destructiveHint===void 0?{}:{destructiveHint:!!s.destructiveHint},...s.idempotentHint===void 0?{}:{idempotentHint:!!s.idempotentHint},...s.openWorldHint===void 0?{}:{openWorldHint:!!s.openWorldHint},untrustedContentHint:!!s.untrustedContentHint}}}}function c(e){return new DOMException(e,`UnknownError`)}function l(e){return c(e instanceof Error?`${r}: ${e.message}`:r)}function u(e){return new DOMException(e,`InvalidStateError`)}function d(e){if(e.name===``)throw u(`Tool "name" must be a non-empty string`);if(typeof e.name!=`string`||!i.test(e.name))throw u(`Tool "name" must be 1–128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period`);if(typeof e.description!=`string`||e.description.length===0)throw u(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`)}function f(e){return{readOnlyHint:e.readOnlyHint??!1,untrustedContentHint:e.untrustedContentHint??!1}}function p(e){try{let t=JSON.parse(e);if(Array.isArray(t)||a(t))return t}catch{}throw c(`Failed to parse input arguments`)}function m(e){if(typeof e==`object`&&e||typeof e==`function`)try{let t=JSON.stringify(e);if(t)return t}catch{}return String(e)||`Operation succeeded`}function h(e,t,n=()=>t?.reason){return t?t.aborted?Promise.reject(n()):new Promise((r,i)=>{let a=()=>{o(),i(n())},o=()=>t.removeEventListener(`abort`,a);t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{o(),r(e)},e=>{o(),i(e)})}):e}function g(e){let t=e.origin===`null`?e:new URL(e.origin),n=t.protocol;if([`https:`,`wss:`,`file:`,`chrome-extension:`,`moz-extension:`].includes(n))return!0;let r=t.hostname.toLowerCase(),i=r.split(`.`),a=i.length===4&&i.every(e=>/^\d{1,3}$/u.test(e)&&Number(e)<=255)&&Number(i[0])===127;return r===`::1`||r===`[::1]`||r===`localhost`||r===`localhost.`||r.endsWith(`.localhost`)||r.endsWith(`.localhost.`)||a}function ee(e){for(let t of e??[]){let e;try{e=new URL(t)}catch{throw new DOMException(`Invalid or untrustworthy origin: ${String(t)}`,`SecurityError`)}if(!g(e))throw new DOMException(`Invalid or untrustworthy origin: ${t}`,`SecurityError`)}}function _(e){if(te(),!e)return;let t=e.defaultView?.DOMException??DOMException,n=!1;try{let t=e.defaultView;n=!!(t&&t.document===e)}catch{}if(!n)throw new t(`The associated document is not fully active`,`InvalidStateError`);let r=Reflect.get(e,`permissionsPolicy`)??Reflect.get(e,`featurePolicy`);if(r&&typeof r==`object`){let e=Reflect.get(r,`features`),n=Reflect.get(r,`allowsFeature`);if(typeof e==`function`&&typeof n==`function`){let i=Reflect.apply(e,r,[]);if(Array.isArray(i)&&i.includes(`tools`)){if(Reflect.apply(n,r,[`tools`])===!0)return;throw new t(`WebMCP is disabled by Permissions Policy`,`NotAllowedError`)}}}let i=e.defaultView;if(!(!i||i.parent===i)){try{i.parent.document;return}catch{}throw new t(`WebMCP in cross-origin frames requires native Permissions Policy support`,`NotAllowedError`)}}function te(){if(globalThis.originAgentCluster===!1&&globalThis.location?.protocol!==`file:`)throw new DOMException(``,`SecurityError`)}function ne(e){try{if(new URL(String(e)).origin!==`null`)return}catch{}throw new DOMException(`Unsupported tool origin: ${String(e)}`,`NotSupportedError`)}function re(e){if(e===null||typeof e!=`object`&&typeof e!=`function`)throw TypeError(`inputSchema must be an object`);let t=JSON.stringify(e);if(t===void 0)throw TypeError(`inputSchema must be JSON-serializable`);return t}const v=new WeakSet,y=new WeakMap,b=new WeakMap;function x(e){return e.isTrusted&&(v.has(e)||e.eventPhase!==Event.NONE&&e.target instanceof HTMLFormElement&&b.has(e.target))}function ie(e,t){if(!x(e))throw new DOMException(`respondWith() is only available during an agent-invoked submit event`,`InvalidStateError`);if(!e.defaultPrevented)throw new DOMException(`respondWith() requires preventDefault() during an agent-invoked submit event`,`InvalidStateError`);if(e.eventPhase===Event.NONE)throw new DOMException(`respondWith() is only available while the submit event is being dispatched`,`InvalidStateError`);v.add(e);let n=Promise.resolve(t);y.set(e,n),e.target instanceof HTMLFormElement&&b.get(e.target)?.respond(e)}const S=new Set([`email`,`password`,`search`,`tel`,`text`,`url`]),ae=new Set([...S,`date`,`datetime-local`,`month`,`number`,`time`,`week`]);function C(e){return e instanceof HTMLInputElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement}function w(e){return Reflect.get(HTMLFormElement.prototype,`elements`,e)}function T(e,t){return Reflect.apply(Element.prototype.getAttribute,e,[t])}function E(e,t){return Reflect.apply(Element.prototype.hasAttribute,e,[t])}function oe(e){return Reflect.get(Node.prototype,`isConnected`,e)}function se(e){return Reflect.get(Element.prototype,`shadowRoot`,e)}function ce(e){return Reflect.apply(HTMLFormElement.prototype.checkValidity,e,[])}function le(e,t){Reflect.apply(HTMLFormElement.prototype.requestSubmit,e,t?[t]:[])}function ue(e){return[...w(e)].filter(e=>C(e)&&!e.matches(`:disabled`)&&!(`readOnly`in e&&e.readOnly&&(e instanceof HTMLTextAreaElement||ae.has(e.type))))}function de(e){let t=new Map;for(let n of ue(e)){let e=n.name.trim(),r=t.get(e);r?r.push(n):t.set(e,[n])}return t}function fe(e){return[...e.labels??[]].map(e=>{let t=e.cloneNode(!0);return t instanceof HTMLElement?(t.querySelectorAll(`button, input, meter, output, progress, select, textarea`).forEach(e=>e.remove()),t.textContent?.trim()??``):``}).filter(Boolean).join(`; `)}function pe(e,t){for(let n=t[0]?.parentElement;n&&n!==e;n=n.parentElement)if(n instanceof HTMLFieldSetElement&&t.every(e=>n.contains(e)))return n}function me(e,t){if(t.length===1){let e=t[0];return e&&(e.getAttribute(`toolparamdescription`)||fe(e)||e.getAttribute(`aria-description`))||void 0}return pe(e,t)?.getAttribute(`toolparamdescription`)||void 0}function D(e,t,n,r){let i=me(t,n),a=i&&r?`${i} (${r})`:i||r;return a?{...e,description:a}:e}function he(e,t){let n=e.getAttribute(t);if(n===null||n.trim()===``)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function ge(e,t){let n=e/t;return Math.abs(n-Math.round(n))<2**-52*16}function O(e){let t=e.getAttribute(`pattern`);if(t!==null)try{return new RegExp(t,`v`),t}catch{return}}function k(e,t=!0){let n={type:`number`},r=he(e,`min`),i=he(e,`max`);r!==void 0&&(n.minimum=r),i!==void 0&&(n.maximum=i);let a=e.getAttribute(`step`);if(a!==`any`){let t=a===null||a===``?1:Number(a),i=Number.isFinite(t)&&t>0?t:1,o=Number(e.getAttribute(`value`));ge(r??(Number.isFinite(o)?o:0),i)&&(n.multipleOf=i)}let o=t?O(e):void 0;return o!==void 0&&(n.pattern=o),n}function A(e,t){let n=e.getAttribute(`step`),r=n===null||n===``?60:Number(n),i=Number.isFinite(r)&&r>0?r:60;return i<1?`${t}(:[0-5][0-9](\\.[0-9]{1,3})?)?$`:i<60?`${t}(:[0-5][0-9])?$`:`${t}$`}function _e(e){return{anyOf:e.map(e=>({type:`string`,const:e.value,title:e.textContent??``})),enum:e.map(e=>e.value)}}function j(e){return{anyOf:e.map(e=>{let t=fe(e);return{type:`string`,const:e.value,...t?{title:t}:{}}}),enum:e.map(e=>e.value)}}function M(e,t){let n=t[0];if(n){if(t.length>1)return t.every(e=>e instanceof HTMLInputElement)?t.every(e=>e.type===`checkbox`)?D({type:`array`,items:{type:`string`,...j(t)},uniqueItems:!0},e,t):t.every(e=>e.type===`radio`)?D({type:`string`,...j(t)},e,t):void 0:void 0;if(n instanceof HTMLTextAreaElement)return D({type:`string`},e,t);if(n instanceof HTMLSelectElement){let r=_e([...n.options]);return D(n.multiple?{type:`array`,items:{type:`string`,...r},uniqueItems:!0}:{type:`string`,...r},e,t)}if(S.has(n.type)){let r={type:`string`},i=O(n);return i!==void 0&&(r.pattern=i),D(r,e,t)}if(n.type===`hidden`)return n.getAttribute(`toolparamdescription`)?D({type:`string`},e,t):void 0;if(n.type===`number`)return D(k(n),e,t);if(n.type===`range`){let r=k(n,!1);return r.minimum??=0,r.maximum??=100,D(r,e,t)}if(n.type===`checkbox`)return D({type:`boolean`},e,t);if(n.type===`radio`)return D({type:`string`,...j([n])},e,t);if(n.type===`date`)return D({type:`string`,format:`date`},e,t,`Dates MUST be provided in 'YYYY-MM-DD' format.`);if(n.type===`month`)return D({type:`string`,format:`^[0-9]{4}-(0[1-9]|1[0-2])$`},e,t);if(n.type===`week`)return D({type:`string`,format:`^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$`},e,t);if(n.type===`time`)return D({type:`string`,format:A(n,`^([01][0-9]|2[0-3]):[0-5][0-9]`)},e,t);if(n.type===`datetime-local`)return D({type:`string`,format:A(n,`^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]`)},e,t);if(n.type===`color`)return D({type:`string`,format:`^#[0-9a-zA-Z]{6}$`},e,t)}}function ve(e){let t={},n=[];for(let[r,i]of de(e)){if(!r)continue;let a=M(e,i);a&&(Object.defineProperty(t,r,{configurable:!0,enumerable:!0,value:a,writable:!0}),i.some(e=>e.required)&&n.push(r))}return{type:`object`,properties:t,required:n}}function ye(e){return{name:T(e,`toolname`)??``,title:T(e,`tooltitle`)??``,description:T(e,`tooldescription`)??``,inputSchema:ve(e),autosubmit:E(e,`toolautosubmit`)}}function N(e){if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return String(e)}function P(e){if(typeof e==`boolean`)return e;if(typeof e==`number`&&Number.isInteger(e))return e!==0;if(typeof e==`string`){if(e===`1`||e.toLowerCase()===`true`)return!0;if(e===`0`||e.toLowerCase()===`false`)return!1}}function F(e,t){if(!Array.isArray(e))return!1;let n=new Set(t);for(let t of e){let e=N(t);if(e===void 0||!n.delete(e))return!1}return!0}function be(e,t){if(t===``)return e.type!==`number`&&e.type!==`range`;let n=e.ownerDocument.createElement(`input`);return n.type=e.type,n.value=t,n.value!==``}function xe(e,t,n){let r=t[0];if(!r||!M(e,t))return!1;if(t.length>1){if(!t.every(e=>e instanceof HTMLInputElement))return!1;if(t.every(e=>e.type===`checkbox`))return F(n,new Set(t.map(e=>e.value)));if(t.every(e=>e.type===`radio`)){let e=N(n);return e!==void 0&&t.some(t=>t.value===e)}return!1}if(r instanceof HTMLSelectElement){let e=new Set([...r.options].map(e=>e.value));if(r.multiple)return F(n,e);let t=N(n);return t!==void 0&&e.has(t)}if(r instanceof HTMLTextAreaElement)return N(n)!==void 0;if(r.type===`checkbox`)return P(n)!==void 0;if(r.type===`radio`){let e=N(n);return e!==void 0&&r.value===e}let i=N(n);return i!==void 0&&be(r,i)}function I(e){e.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),e.dispatchEvent(new Event(`change`,{bubbles:!0}))}function Se(e,t){let n=e instanceof HTMLInputElement?HTMLInputElement.prototype:HTMLTextAreaElement.prototype;Object.getOwnPropertyDescriptor(n,`value`)?.set?.call(e,t)}function L(e,t){Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,`checked`)?.set?.call(e,t)}function Ce(e,t){let n=e[0];if(!n)return;if(e.length>1&&e.every(e=>e instanceof HTMLInputElement)){if(e.every(e=>e.type===`checkbox`)&&Array.isArray(t)){let n=new Set(t.map(N));for(let t of e){let e=n.has(t.value);t.checked!==e&&(L(t,e),I(t))}return}let n=N(t),r=e.find(e=>e.value===n);r&&!r.checked&&(L(r,!0),I(r));return}if(n instanceof HTMLSelectElement){if(n.multiple&&Array.isArray(t)){let e=new Set(t.map(N)),r=!1;for(let t of n.options){let n=e.has(t.value);t.selected!==n&&(t.selected=n,r=!0)}r&&I(n);return}let e=N(t);e!==void 0&&n.value!==e&&(n.value=e,I(n));return}if(n instanceof HTMLInputElement&&n.type===`checkbox`){let e=P(t);e!==void 0&&n.checked!==e&&(L(n,e),I(n));return}if(n instanceof HTMLInputElement&&n.type===`radio`){N(t)===n.value&&!n.checked&&(L(n,!0),I(n));return}let r=N(t);r!==void 0&&n.value!==r&&(Se(n,r),I(n))}function we(e,t){if(Array.isArray(t))throw TypeError(`Declarative tool input must be an object`);let n=de(e);for(let[r,i]of Object.entries(t)){let t=n.get(r);if(!t||!xe(e,t,i))throw TypeError(`Invalid value for declarative form parameter "${r}"`)}for(let[e,r]of Object.entries(t))Ce(n.get(e)??[],r)}function Te(e){return[...w(e)].find(e=>!e.matches(`:disabled`)&&(e instanceof HTMLButtonElement&&e.type===`submit`||e instanceof HTMLInputElement&&[`image`,`submit`].includes(e.type)))}function Ee(e){let t=[...w(e)].filter(e=>C(e)&&e.willValidate&&!e.validity.valid).map(e=>`${e.name.trim()||`{unknown}`}: ${e.validationMessage}`).join(`. `);return new DOMException(`Form validation failed: ${t}`,`UnknownError`)}function R(e){let t=new Event(`toolactivated`);return Object.defineProperty(t,"toolName",{enumerable:!0,value:e}),t}function De(e,t,n,r){let{form:i}=e;return e.cancelPending?.(new DOMException(`Tool execution cancelled`,`UnknownError`)),new Promise((a,o)=>{let s=!1,c=()=>{Reflect.apply(EventTarget.prototype.removeEventListener,i,[`invalid`,f,!0]),b.delete(i),e.cancelPending===u&&delete e.cancelPending},l=e=>{s||(s=!0,c(),e())},u=e=>l(()=>o(e)),d=e=>{e.then(e=>l(()=>a(e)),e=>l(()=>o(e)))},f=e=>{e.isTrusted&&queueMicrotask(()=>{ce(i)||u(Ee(i))})};if(b.set(i,{complete(e){queueMicrotask(()=>{let t=y.get(e);t?d(t):e.defaultPrevented?u(new DOMException(`preventDefault() requires respondWith()`,`UnknownError`)):l(()=>a(void 0))})},direct(){l(()=>a(void 0))},respond(e){queueMicrotask(()=>{let t=y.get(e);t&&d(t)})}}),e.cancelPending=u,Reflect.apply(EventTarget.prototype.addEventListener,i,[`invalid`,f,!0]),!n){r?.focus(),window.dispatchEvent(R(t));return}try{le(i,r),window.dispatchEvent(R(t))}catch(e){u(e)}})}function Oe(e,t){let n=!0,r=new Map,i=new Map,a=new Map,o=e=>{if(!(e instanceof SubmitEvent)||!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=b.get(e.target);t&&(v.add(e),t.complete(e))},s=e=>{if(!e.isTrusted||!(e.target instanceof HTMLFormElement))return;let t=e.target;queueMicrotask(()=>{e.defaultPrevented||r.get(t)?.cancelPending?.(new DOMException(`Tool execution cancelled by form reset`,`UnknownError`))})};function c(e){a.get(e)?.disconnect(),a.delete(e),e.removeEventListener(`reset`,s,!0),e.removeEventListener(`submit`,o,!0)}function l(e){if(a.has(e))return;let t=new MutationObserver(u);a.set(e,t),t.observe(e,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),e.addEventListener(`reset`,s,!0),e.addEventListener(`submit`,o,!0)}function u(){l(e);for(let e of a.keys())e instanceof ShadowRoot&&!Reflect.get(Node.prototype,`isConnected`,e.host)&&c(e);let n=new Set,o=new Map,s=new Map;for(let e of a.keys())for(let t of e.querySelectorAll(`*`)){let e=se(t);if(e&&l(e),!(t instanceof HTMLFormElement)||!E(t,`toolname`)||!E(t,`tooldescription`)||!oe(t))continue;let r=t;n.add(r);let a=ye(r),c=JSON.stringify(a),u=i.get(r);if(u===c)continue;let d=u!==void 0;i.delete(r);let f=s.get(a.name);if(f&&!d){i.set(r,c);continue}if(f){let e=o.get(f);e&&(i.set(f,e.fingerprint),o.delete(f))}s.set(a.name,r),o.set(r,{definition:a,fingerprint:c})}for(let e of i.keys())n.has(e)||i.delete(e);for(let[e,t]of r)o.get(e)?.fingerprint!==t.fingerprint&&(t.cancelPending?.(new DOMException(`Tool execution cancelled because its form changed`,`UnknownError`)),t.controller.abort(),r.delete(e));for(let[e,{definition:n,fingerprint:i}]of o){if(r.has(e))continue;let a=new AbortController,o={controller:a,fingerprint:i,form:e};r.set(e,o),t.registerTool({name:n.name,title:n.title,description:n.description,inputSchema:n.inputSchema,execute(t){let r=Te(e);if(!n.autosubmit&&!r)throw new DOMException(`A declarative form without toolautosubmit requires a submit button`,`UnknownError`);return we(e,t),De(o,n.name,n.autosubmit,r)}},{signal:a.signal}).catch(e=>{a.abort(),e?.name!==`AbortError`&&console.error(`[webmcp] declarative form tool "${n.name}" was not registered:`,e)})}}let d=()=>{},f=e.defaultView?.Element.prototype,p=f?Object.getOwnPropertyDescriptor(f,`attachShadow`):void 0;if(f&&p?.configurable){let t=f.attachShadow,r=function(r){let i=t.call(this,r);return n&&i.mode===`open`&&Reflect.get(Node.prototype,`ownerDocument`,this)===e&&Reflect.get(Node.prototype,`isConnected`,this)&&l(i),i};Object.defineProperty(f,"attachShadow",{...p,value:r}),d=()=>{f.attachShadow===r&&Object.defineProperty(f,"attachShadow",p)}}let m=()=>{},h=e.defaultView?.HTMLFormElement.prototype,g=h?Object.getOwnPropertyDescriptor(h,`submit`):void 0;if(h&&g?.configurable){let e=h.submit,t=function(){e.call(this),n&&b.get(this)?.direct()};Object.defineProperty(h,"submit",{...g,value:t}),m=()=>{h.submit===t&&Object.defineProperty(h,"submit",g)}}return u(),()=>{n=!1,m(),d();for(let e of a.keys())c(e);i.clear();for(let e of r.values())e.cancelPending?.(new DOMException(`Tool execution cancelled`,`UnknownError`)),e.controller.abort();r.clear()}}const z=Symbol(`registeredInputSchema`),B=Symbol(`registrationSignal`),ke=Symbol(`registrationAbort`),V=[];let H=null,U=null;function Ae(){return typeof globalThis.origin==`string`?globalThis.origin:globalThis.location?.origin??``}function W(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);try{Object.defineProperty(e,t,n)}catch(e){throw ze(),e}V.push({target:e,key:t,previous:r})}var G=class extends EventTarget{#e=new Map;#t=null;#n=null;#r=e=>{this.#n?.call(this,e)};#i;#a;constructor(e){super(),this.#a=e,this.#i=e?.defaultView?.DOMException??DOMException,Object.defineProperty(this,"__isWebMCPPolyfill",{value:!0,enumerable:!1,writable:!1,configurable:!1})}get ontoolchange(){return this.#n}set ontoolchange(e){let t=typeof e==`function`?e:null;if(t===null){this.#n=null,super.removeEventListener(`toolchange`,this.#r);return}this.#n===null&&super.addEventListener(`toolchange`,this.#r),this.#n=t}async registerTool(e,t={}){_(this.#a);let n=t?.signal,r=Me(e,this.#e);if(n?.throwIfAborted(),ee(t?.exposedTo),n?.throwIfAborted(),t?.exposedTo?.length)throw new this.#i(`Cross-document tool exposure requires native WebMCP`,`NotSupportedError`);if(this.#e.set(r.name,r),n){let e=()=>{this.#o(r.name,r)&&this.#c()};r[B]=n,r[ke]=e,n.addEventListener(`abort`,e,{once:!0})}if(await this.#c(),n?.aborted)throw n.reason}async getTools(e={}){if(_(this.#a),ee(e?.fromOrigins),e?.fromOrigins?.length)throw new this.#i(`Cross-document tool discovery requires native WebMCP`,`NotSupportedError`);let t=[...this.#e.values()].map(e=>{let t=e[z],n=t===void 0?void 0:JSON.parse(t);return{name:e.name,title:e.title??``,description:e.description,...a(n)?{inputSchema:n}:{},origin:Ae(),window:globalThis.window,...e.annotations?{annotations:f(e.annotations)}:{}}}).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));return await new Promise(e=>setTimeout(e,0)),t}async executeTool(e,t,n={}){if(_(this.#a),typeof e!=`object`||!e)throw TypeError(`RegisteredTool must be an object`);for(let t of[`name`,`description`,`window`,`origin`])if(!(t in e))throw TypeError(`RegisteredTool.${t} is required`);if(ne(e.origin),e.window!==globalThis.window||e.origin!==Ae())throw c(`Tool not found: ${e.name}`);return this.#s(e.name,t,n)}static getTestingShim(e){return e.#t??=new je(e),e.#t}static getToolInfos(e){return[...e.#e.values()].map(e=>({name:e.name,description:e.description,...e[z]===void 0?{}:{inputSchema:e[z]}}))}static executeToolForTesting(e,t,n,r){return _(e.#a),e.#s(t,n,r)}static dispose(e){for(let t of e.#e.keys())e.#o(t);e.ontoolchange=null,e.#t?.dispose()}#o(e,t){let n=this.#e.get(e);if(!n||t&&n!==t)return!1;let r=n[B],i=n[ke];return r&&i&&r.removeEventListener(`abort`,i),this.#e.delete(e)}async#s(e,t,n){n?.signal?.throwIfAborted();let r=this.#e.get(e);if(!r)throw c(`Tool not found: ${e}`);let i=p(t);if(n?.signal?.throwIfAborted(),r[B]?.aborted)throw c(`Tool unregistered`);let a;try{let e=r[B];a=await h(h(Promise.resolve(r.execute(i)),e,()=>c(`Tool unregistered`)),n?.signal)}catch(e){throw n?.signal?.aborted&&e===n.signal.reason||r[B]?.aborted?e:l(e)}return m(a)}async#c(){await new Promise(e=>setTimeout(e,0)),this.dispatchEvent(new Event(`toolchange`)),this.#t?.dispatchToolChange()}};const K=function(){throw TypeError(`Illegal constructor`)};Object.defineProperty(K,"name",{value:`ModelContext`}),Object.defineProperty(K,"prototype",{value:G.prototype,writable:!1}),Object.setPrototypeOf(K,EventTarget),Object.defineProperty(G.prototype,"constructor",{configurable:!0,writable:!0,value:K}),Object.defineProperty(G.prototype,Symbol.toStringTag,{configurable:!0,value:`ModelContext`});for(let e of[`registerTool`,`getTools`,`executeTool`,`ontoolchange`]){let t=Object.getOwnPropertyDescriptor(G.prototype,e);t&&Object.defineProperty(G.prototype,e,{...t,enumerable:!0})}var je=class extends EventTarget{_ontoolchange=null;ontoolchangeListener=e=>{this._ontoolchange?.call(this,e)};#e;constructor(e){super(),this.#e=e}listTools(){return G.getToolInfos(this.#e)}executeTool(e,t,n){return G.executeToolForTesting(this.#e,e,t,n)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){let t=typeof e==`function`?e:null;if(t===null){this._ontoolchange=null,super.removeEventListener(`toolchange`,this.ontoolchangeListener);return}this._ontoolchange===null&&super.addEventListener(`toolchange`,this.ontoolchangeListener),this._ontoolchange=t}dispatchToolChange(){this.dispatchEvent(new Event(`toolchange`))}dispose(){this.ontoolchange=null}};function Me(e,t){if(!e||typeof e!=`object`)throw TypeError(`registerTool(tool) requires a tool object`);let n=s(e);if(d(n),t.has(n.name))throw u(`Tool already registered: ${n.name}`);let r=n.inputSchema===void 0?void 0:re(n.inputSchema);return{name:n.name,...n.title===void 0?{}:{title:n.title},description:n.description,...n.inputSchema===void 0?{}:{inputSchema:n.inputSchema},...n.annotations===void 0?{}:{annotations:n.annotations},execute:e=>Reflect.apply(n.execute,void 0,[e]),...r===void 0?{}:{[z]:r}}}let q=!1;const Ne=new WeakMap,{modelContext:Pe}={modelContext(){if(!(this instanceof Document))throw TypeError(`Illegal invocation`);return Ne.get(this)}};Object.defineProperty(Pe,"name",{value:`get modelContext`});function Fe(e,t){Ne.set(e,t),!Object.hasOwn(Document.prototype,`modelContext`)&&W(Document.prototype,`modelContext`,{configurable:!0,enumerable:!0,get:Pe})}function Ie(e,t){W(e,`modelContext`,{configurable:!0,enumerable:!0,get(){return q||(q=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.`)),t}})}function Le(){let e=SubmitEvent.prototype;`agentInvoked`in e||W(e,`agentInvoked`,{configurable:!0,enumerable:!0,get(){return x(this)}}),`respondWith`in e||W(e,`respondWith`,{configurable:!0,enumerable:!0,writable:!0,value(e){ie(this,e)}})}function Re(e){if(globalThis.isSecureContext===!1)return;let t=typeof navigator>`u`?null:navigator,n=typeof document>`u`?null:document;if(!t||!n||typeof window>`u`||n.modelContext)return;let r=t.modelContext;if(V.length>0&&ze(),r){Fe(n,r);return}let i=Object.getOwnPropertyDescriptor(window,`ModelContext`);if(i&&!i.configurable){if(!Object.is(Reflect.get(window,`ModelContext`),K))throw TypeError(`Cannot install ModelContext over a non-configurable globalThis`)}else W(window,`ModelContext`,{configurable:!0,enumerable:!1,writable:!0,value:K});let a=new G(n);H=a,Fe(n,a),q=!1,Ie(t,a),Le(),e?.installTestingShim&&!t.modelContextTesting&&W(t,`modelContextTesting`,{configurable:!0,enumerable:!0,writable:!1,value:G.getTestingShim(a)}),U=Oe(n,a)}function ze(){U?.(),U=null,H&&G.dispose(H),H=null;for(let{target:e,key:t,previous:n}of[...V].reverse())n?Object.defineProperty(e,t,n):Reflect.deleteProperty(e,t);V.length=0,q=!1}var Be=e({CONSEQUENTIAL_TOOL_NAMES:()=>qe,READ_ONLY_TOOL_NAMES:()=>Je,executeWebMcpTool:()=>Ke,extractAbortSignal:()=>We,getWebMcpMode:()=>He,getWebMcpTools:()=>Ge,parseWebMcpInputSchema:()=>Q,registerWebMcpTools:()=>Xe,resolveWebMcpToolAnnotations:()=>Ye,setWebMcpMode:()=>Ve,unregisterWebMcpTools:()=>$});const J=new Map,Y=new Set;let X=`polyfill`;function Ve(e){X=e}function He(){return X}function Ue(){try{Re()}catch(e){console.warn(`WebMCP polyfill initialization failed:`,e)}}function Z(){if(typeof document>`u`&&typeof navigator>`u`)return null;X===`polyfill`&&Ue();try{let e=typeof document<`u`&&document.modelContext!==void 0?Reflect.get(document,`modelContext`):typeof navigator<`u`&&navigator.modelContext!==void 0?Reflect.get(navigator,`modelContext`):void 0;if(!e||typeof e!=`object`)return null;let t=e;return typeof t.registerTool==`function`?t:null}catch(e){return console.warn(`WebMCP modelContext access failed:`,e),null}}function Q(e){if(typeof e==`string`){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}return{type:`object`,properties:{}}}return e&&typeof e==`object`&&!Array.isArray(e)?e:{type:`object`,properties:{}}}function We(e){if(e){if(typeof AbortSignal<`u`&&e instanceof AbortSignal)return e;if(typeof e==`object`&&`signal`in e&&typeof AbortSignal<`u`&&e.signal instanceof AbortSignal)return e.signal}}async function Ge(){let e=Z();if(!e||typeof e.getTools!=`function`)return[];try{let t=await e.getTools();return Array.isArray(t)?t.map(e=>({name:e.name,...e.description?{description:e.description}:{},inputSchema:Q(e.inputSchema),...e.annotations?{annotations:e.annotations}:{},...e.execute?{execute:e.execute}:{}})):[]}catch(e){return console.warn(`Failed to retrieve WebMCP tools via getTools():`,e),[]}}async function Ke(e,t,n,r){if(!e||typeof e.executeTool!=`function`)throw Error(`ModelContext executeTool is not available`);let i,a;if(typeof n==`string`){a=n;try{let e=JSON.parse(n);i=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch{i={}}}else if(n&&typeof n==`object`&&!Array.isArray(n)){i=n;try{a=JSON.stringify(n)}catch{a=`{}`}}else i={},a=`{}`;try{return await e.executeTool(t,i,r)}catch(n){let i=typeof n?.message==`string`&&n.message.startsWith(`Failed to parse input`),o=n instanceof TypeError;if(i||o)return await e.executeTool(t,a,r);throw n}}const qe=new Set([`bash`,`clear_chat`,`delete_file`,`delete_task`,`email_send_message`,`git_delete_branch`,`git_delete_repo`,`git_push`,`git_reset`]),Je=new Set(`ask_user.detect_language.diff_files.email_read_messages.fetch_url.get_current_time.git_branches.git_diff.git_list_repos.git_log.git_read_file_at_ref.git_show.git_status.list_components.list_files.list_room_members.list_tasks.list_tool_profiles.proofread_text.read_file.remote_mcp_list_tools.rewrite_text.search_files.summarize_text.translate_text.web_search.write_text`.split(`.`));function Ye(e,t){let n=qe.has(e);return{readOnlyHint:!n&&Je.has(e),consequentialHint:n,untrustedContentHint:!0,...t||{}}}async function Xe(e,r,i=t,a){let o=Array.isArray(a)?a:n;if(o.length===0)return!0;let s=Z();if(!s)return!1;for(let t of o){if(Y.has(t.name))continue;let n=new AbortController;J.set(t.name,n),Y.add(t.name);try{let r={name:t.name,description:t.description,inputSchema:Q(t.input_schema),annotations:Ye(t.name,t.annotations),execute:(n,r)=>{if(!e)throw Error(`Cannot execute tool: agent worker is not ready`);let a=We(r);return a?.aborted?Promise.reject(Error(`Tool execution aborted`)):new Promise((r,o)=>{let s=Date.now().toString(36)+Math.random().toString(36).slice(2),c=null,l=()=>{c!==null&&(clearTimeout(c),c=null),e?.removeEventListener(`message`,d),a&&u&&a.removeEventListener(`abort`,u)},u=()=>{l(),o(Error(`Tool execution aborted`))};a&&a.addEventListener(`abort`,u,{once:!0}),c=setTimeout(()=>{l(),o(Error(`Timeout waiting for tool execution`))},6e5);let d=e=>{let t=e.data;t&&t.type===`execute-tool-result`&&t.callId===s&&(l(),t.error?o(Error(t.error)):r(t.result))};e.addEventListener(`message`,d),e.postMessage({type:`execute-tool`,callId:s,payload:{name:t.name,input:n||{},groupId:i}})})}};await s.registerTool(r,{signal:n.signal}),await new Promise(e=>setTimeout(e,0))}catch(e){if(J.delete(t.name),Y.delete(t.name),!(e instanceof Error&&(e.message.includes(`already registered`)||e.message.includes(`Duplicate tool name`))))throw console.error(`Failed to register tool ${t.name}:`,e),e}}return!0}function $(){for(let e of J.values())try{e.abort()}catch{}J.clear(),Y.clear()}export{Be as a,$ as i,Xe as n,Ve as r,He as t};
|