shadow-claw 1.54.0 → 1.55.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/README.md +1 -1
- package/dist/cli/build/build.js +1 -1
- package/dist/cli/{chunk-DO2t9bUI.js → chunk--IuVyWfT.js} +24 -23
- package/dist/cli/{chunk-2ZYd9gYC.js → chunk--JpdI-Ht.js} +1 -1
- package/dist/cli/{chunk-m4Ineemy.js → chunk-4O8yrQuN.js} +1 -1
- package/dist/cli/{chunk-BiH9IXnQ.js → chunk-7S9Ywlfy.js} +1 -1
- package/dist/cli/{chunk-BmMOdYvk.js → chunk-B0SqqDSK.js} +1 -1
- package/dist/cli/chunk-BNaWaEm-.js +1 -0
- package/dist/cli/chunk-BXCsxO9e.js +1 -0
- package/dist/cli/chunk-Bq37qDoZ.js +18 -0
- package/dist/cli/{chunk-C1htf-nO.js → chunk-BrEeCKIo.js} +2 -2
- package/dist/cli/{chunk-BI1SOTM1.js → chunk-Bu3ylrhT.js} +8 -8
- package/dist/cli/{chunk-3smiGQoQ.js → chunk-C1v_s0Kb.js} +1 -1
- package/dist/cli/{chunk-DGeysxz3.js → chunk-C44G533y.js} +1 -1
- package/dist/cli/{chunk-9KiBalKu.js → chunk-C7hJLmsL.js} +1 -1
- package/dist/cli/{chunk-BFv9XSNd.js → chunk-CAaQWd6t.js} +1 -1
- package/dist/cli/chunk-CIkgn5Fh.js +1 -0
- package/dist/cli/chunk-CWEIN2kc.js +1 -0
- package/dist/cli/{chunk-BDeDZ-0L.js → chunk-CYg1lO1a.js} +1 -1
- package/dist/cli/{chunk-DXLmEQ3i.js → chunk-Ce09lwXT.js} +1 -1
- package/dist/cli/{chunk-XsfHeN4m.js → chunk-CpdqRSO-.js} +1 -1
- package/dist/cli/chunk-DB4x5L-B.js +1 -0
- package/dist/cli/{chunk-DaNyMqrk.js → chunk-DBvObsBQ.js} +1 -1
- package/dist/cli/chunk-DGPpt7Ka.js +1 -0
- package/dist/cli/chunk-DGagHluH.js +1 -0
- package/dist/cli/chunk-DUIs23D9.js +1 -0
- package/dist/cli/{chunk-CyvfQV16.js → chunk-DaurYOqg.js} +1 -1
- package/dist/cli/{chunk-DSFrcSyA.js → chunk-DfwRL0Ue.js} +1 -1
- package/dist/cli/{chunk-M2tZrzY5.js → chunk-DudYQk0p.js} +1 -1
- package/dist/cli/chunk-DvKo50Tp.js +2 -0
- package/dist/cli/{chunk-H_Mw5ypp.js → chunk-Dvrqte5Q.js} +2 -2
- package/dist/cli/{chunk-BtNO-m9T.js → chunk-DzhSExU0.js} +1 -1
- package/dist/cli/{chunk-IOMO88kZ.js → chunk-ENKlt3i9.js} +1 -1
- package/dist/cli/{chunk-Bspgzwsm.js → chunk-FWRwAX75.js} +8 -8
- package/dist/cli/chunk-Lf-Z-h48.js +32 -0
- package/dist/cli/{chunk-BucXnZ4Z.js → chunk-VRfkSLrD.js} +1 -1
- package/dist/cli/chunk-uaTxD024.js +1 -0
- package/dist/cli/cli.js +1 -1
- package/dist/cli/prerender/dsd-shell/prerender-dsd-shell.js +1 -1
- package/dist/headless-agent.js +2 -2
- package/dist/lib/components/index.js +25 -25
- 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/utils/get-route.d.ts +3 -0
- package/dist/lib/components/shadow-claw/utils/sync-slotted-sidebar-active-links.d.ts +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/{configure-peer-js-D5jDCtLx.js → configure-peer-js-C9554Slv.js} +2 -2
- package/dist/lib/{configure-peer-js-D5jDCtLx.js.map → configure-peer-js-C9554Slv.js.map} +1 -1
- package/dist/lib/{file-viewer-B4CL4e0i.js → file-viewer-DBc5dxNy.js} +2 -2
- package/dist/lib/{file-viewer-B4CL4e0i.js.map → file-viewer-DBc5dxNy.js.map} +1 -1
- package/dist/lib/index.js +28 -27
- package/dist/lib/{init-control-plane-l2uFnhGV.js → init-control-plane-D-41Fm5q.js} +12 -12
- package/dist/lib/{init-control-plane-l2uFnhGV.js.map → init-control-plane-D-41Fm5q.js.map} +1 -1
- package/dist/lib/{markdown-0_p_zfxL.js → markdown-KnDWzWJJ.js} +2 -2
- package/dist/lib/{markdown-0_p_zfxL.js.map → markdown-KnDWzWJJ.js.map} +1 -1
- package/dist/lib/{orchestrator-D6wm8Sec.js → orchestrator-BEZcqgR5.js} +9 -9
- package/dist/lib/{orchestrator-D6wm8Sec.js.map → orchestrator-BEZcqgR5.js.map} +1 -1
- package/dist/lib/{orchestrator-Dh-hnIpK.js → orchestrator-Cda13e5U.js} +4 -4
- package/dist/lib/{orchestrator-Dh-hnIpK.js.map → orchestrator-Cda13e5U.js.map} +1 -1
- package/dist/lib/{peerjs-BWZnsD0B.js → peerjs-DYkUTcee.js} +5 -5
- package/dist/lib/{peerjs-BWZnsD0B.js.map → peerjs-DYkUTcee.js.map} +1 -1
- package/dist/lib/{push-client-MybDfOdi.js → push-client-CQtCFDaD.js} +3 -3
- package/dist/lib/{push-client-MybDfOdi.js.map → push-client-CQtCFDaD.js.map} +1 -1
- package/dist/lib/security/custom-element-security.d.ts +8 -4
- package/dist/lib/{shadow-claw-PdOpgTxH.js → shadow-claw-DYe9u6Tp.js} +142 -33
- package/dist/lib/shadow-claw-DYe9u6Tp.js.map +1 -0
- package/dist/lib/{shadow-claw-accounts-3bR76EOb.js → shadow-claw-accounts-D2URoHys.js} +2 -2
- package/dist/lib/{shadow-claw-accounts-3bR76EOb.js.map → shadow-claw-accounts-D2URoHys.js.map} +1 -1
- package/dist/lib/{shadow-claw-channel-config-ChdZ1iB8.js → shadow-claw-channel-config-buXoz2xv.js} +3 -3
- package/dist/lib/{shadow-claw-channel-config-ChdZ1iB8.js.map → shadow-claw-channel-config-buXoz2xv.js.map} +1 -1
- package/dist/lib/{shadow-claw-channels-CK9sc7h_.js → shadow-claw-channels-5yVJ1gLk.js} +3 -3
- package/dist/lib/{shadow-claw-channels-CK9sc7h_.js.map → shadow-claw-channels-5yVJ1gLk.js.map} +1 -1
- package/dist/lib/{shadow-claw-chat-B6uuZnJ7.js → shadow-claw-chat-CVc-7ycM.js} +7 -7
- package/dist/lib/{shadow-claw-chat-B6uuZnJ7.js.map → shadow-claw-chat-CVc-7ycM.js.map} +1 -1
- package/dist/lib/{shadow-claw-control-plane-BpRcl312.js → shadow-claw-control-plane-B5vsF91B.js} +6 -6
- package/dist/lib/{shadow-claw-control-plane-BpRcl312.js.map → shadow-claw-control-plane-B5vsF91B.js.map} +1 -1
- package/dist/lib/{shadow-claw-conversations-Dc_Xk2mB.js → shadow-claw-conversations-PGK5zqn3.js} +54 -12
- package/dist/lib/{shadow-claw-conversations-Dc_Xk2mB.js.map → shadow-claw-conversations-PGK5zqn3.js.map} +1 -1
- package/dist/lib/{shadow-claw-file-viewer-C4x1PtB2.js → shadow-claw-file-viewer-DSqn0hgx.js} +6 -6
- package/dist/lib/{shadow-claw-file-viewer-C4x1PtB2.js.map → shadow-claw-file-viewer-DSqn0hgx.js.map} +1 -1
- package/dist/lib/{shadow-claw-files-DhnHbXKf.js → shadow-claw-files-vOa9ZWbr.js} +6 -6
- package/dist/lib/{shadow-claw-files-DhnHbXKf.js.map → shadow-claw-files-vOa9ZWbr.js.map} +1 -1
- package/dist/lib/{shadow-claw-git-BeQ1ElUd.js → shadow-claw-git-D54Z85Bj.js} +4 -4
- package/dist/lib/{shadow-claw-git-BeQ1ElUd.js.map → shadow-claw-git-D54Z85Bj.js.map} +1 -1
- package/dist/lib/{shadow-claw-integrations-Bbdolk3w.js → shadow-claw-integrations-BTubMH9d.js} +2 -2
- package/dist/lib/{shadow-claw-integrations-Bbdolk3w.js.map → shadow-claw-integrations-BTubMH9d.js.map} +1 -1
- package/dist/lib/{shadow-claw-llm-DPda4L3C.js → shadow-claw-llm-8koGTNYs.js} +3 -3
- package/dist/lib/{shadow-claw-llm-DPda4L3C.js.map → shadow-claw-llm-8koGTNYs.js.map} +1 -1
- package/dist/lib/{shadow-claw-mcp-remote-Dn9c30WI.js → shadow-claw-mcp-remote-C2jwBsQt.js} +2 -2
- package/dist/lib/{shadow-claw-mcp-remote-Dn9c30WI.js.map → shadow-claw-mcp-remote-C2jwBsQt.js.map} +1 -1
- package/dist/lib/{shadow-claw-networking-zqNuyn3-.js → shadow-claw-networking-BV-rna16.js} +2 -2
- package/dist/lib/{shadow-claw-networking-zqNuyn3-.js.map → shadow-claw-networking-BV-rna16.js.map} +1 -1
- package/dist/lib/{shadow-claw-notifications-DFgdo33v.js → shadow-claw-notifications-Dku7VBLk.js} +2 -2
- package/dist/lib/{shadow-claw-notifications-DFgdo33v.js.map → shadow-claw-notifications-Dku7VBLk.js.map} +1 -1
- package/dist/lib/{shadow-claw-page-header-B7LFGQRf.js → shadow-claw-page-header-VPjYWfsT.js} +2 -2
- package/dist/lib/{shadow-claw-page-header-B7LFGQRf.js.map → shadow-claw-page-header-VPjYWfsT.js.map} +1 -1
- package/dist/lib/{shadow-claw-pages-DLspFqdK.js → shadow-claw-pages-DXrM6hgZ.js} +29 -19
- package/dist/lib/shadow-claw-pages-DXrM6hgZ.js.map +1 -0
- package/dist/lib/{shadow-claw-peerjs-D8xWwuWR.js → shadow-claw-peerjs-D3xonez5.js} +3 -3
- package/dist/lib/{shadow-claw-peerjs-D8xWwuWR.js.map → shadow-claw-peerjs-D3xonez5.js.map} +1 -1
- package/dist/lib/{shadow-claw-settings-NbvzXASD.js → shadow-claw-settings-DMTx6OS9.js} +5 -5
- package/dist/lib/{shadow-claw-settings-NbvzXASD.js.map → shadow-claw-settings-DMTx6OS9.js.map} +1 -1
- package/dist/lib/{shadow-claw-storage-B_NAoZmd.js → shadow-claw-storage-BJLnukxa.js} +3 -3
- package/dist/lib/{shadow-claw-storage-B_NAoZmd.js.map → shadow-claw-storage-BJLnukxa.js.map} +1 -1
- package/dist/lib/{shadow-claw-task-server-BaQJXhYJ.js → shadow-claw-task-server-DcMj20hD.js} +2 -2
- package/dist/lib/{shadow-claw-task-server-BaQJXhYJ.js.map → shadow-claw-task-server-DcMj20hD.js.map} +1 -1
- package/dist/lib/{shadow-claw-tasks-CAZua0-j.js → shadow-claw-tasks-BQBe4lVi.js} +7 -7
- package/dist/lib/{shadow-claw-tasks-CAZua0-j.js.map → shadow-claw-tasks-BQBe4lVi.js.map} +1 -1
- package/dist/lib/{shadow-claw-terminal-B2YJhkJL.js → shadow-claw-terminal-DPEzTxXv.js} +2 -2
- package/dist/lib/{shadow-claw-terminal-B2YJhkJL.js.map → shadow-claw-terminal-DPEzTxXv.js.map} +1 -1
- package/dist/lib/{shadow-claw-tools-CkZWxxTm.js → shadow-claw-tools-BCnU8FaK.js} +6 -6
- package/dist/lib/{shadow-claw-tools-CkZWxxTm.js.map → shadow-claw-tools-BCnU8FaK.js.map} +1 -1
- package/dist/lib/{shadow-claw-webvm-BL9cgrP9.js → shadow-claw-webvm-CnW-hoJ8.js} +2 -2
- package/dist/lib/{shadow-claw-webvm-BL9cgrP9.js.map → shadow-claw-webvm-CnW-hoJ8.js.map} +1 -1
- package/dist/lib/subsystems/mcp/webmcp.d.ts +15 -2
- package/dist/lib/{sync-web-mcp-registration-dW2MVCj4.js → sync-web-mcp-registration-DwpGjVdo.js} +10 -4
- package/dist/lib/sync-web-mcp-registration-DwpGjVdo.js.map +1 -0
- package/dist/lib/{tools-D7whby3H.js → tools-CP6G0HF7.js} +5 -6
- package/dist/lib/tools-CP6G0HF7.js.map +1 -0
- package/dist/lib/{trusted-types-d0cdkut_.js → trusted-types-0cu5Dm6M.js} +29 -4
- package/dist/lib/{trusted-types-d0cdkut_.js.map → trusted-types-0cu5Dm6M.js.map} +1 -1
- package/dist/lib/utils/index.d.ts +1 -0
- package/dist/lib/utils/index.js +4 -2
- package/dist/lib/utils/index.js.map +1 -1
- package/dist/lib/utils/resolve-page-script-dependencies.d.ts +19 -0
- package/dist/lib/utils/resolve-page-script-dependencies.js +98 -0
- package/dist/lib/utils/resolve-page-script-dependencies.js.map +1 -0
- package/dist/lib/utils/utils.js +1 -1
- package/dist/lib/webmcp-Bf9rT7uu.js +2001 -0
- package/dist/lib/webmcp-Bf9rT7uu.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/AGENTS.md +3 -3
- package/dist/public/README.md +1 -1
- package/dist/public/agent.worker.js +2 -2
- package/dist/public/components/shadow-claw/shadow-claw.css +1 -1
- package/dist/public/components/shadow-claw/shadow-claw.html +1 -1
- package/dist/public/components/shadow-claw-conversations/shadow-claw-conversations.css +1 -1
- package/dist/public/components/shadow-claw-conversations/shadow-claw-conversations.html +1 -1
- package/dist/public/{configure-peer-js-WLRM7Qa7.js → configure-peer-js-OYl3V8sW.js} +1 -1
- package/dist/public/{custom-element-security-Cl991z-x.js → custom-element-security-BR4V40j4.js} +1 -1
- package/dist/public/docs/example/article/index.html +3 -3
- package/dist/public/docs/example/article.html +3 -3
- package/dist/public/docs/publishing/index.html +3 -3
- package/dist/public/docs/publishing.html +3 -3
- package/dist/public/docs/skill-creator/index.html +3 -3
- package/dist/public/docs/skill-creator.html +3 -3
- package/dist/public/docs/subsystems/custom-element-security.md +19 -5
- package/dist/public/docs/subsystems/pages.md +10 -2
- package/dist/public/docs/subsystems/tools.md +1 -2
- package/dist/public/docs/subsystems/webmcp.md +41 -6
- package/dist/public/{download-group-file-fFjoIIp4.js → download-group-file-BNmK8wac.js} +1 -1
- package/dist/public/e2e/README.md +2 -2
- package/dist/public/{e2e-bridge-CiSfBRT4.js → e2e-bridge-4phD1JUQ.js} +1 -1
- package/dist/public/{file-viewer-DFC3kfeO.js → file-viewer-Dbh3K9nL.js} +1 -1
- package/dist/public/index.html +3 -3
- package/dist/public/index.js +1 -1
- package/dist/public/{init-control-plane-BEbcwmmv.js → init-control-plane-DGOY_RNS.js} +1 -1
- package/dist/public/llms.txt +1 -1
- package/dist/public/main/index.html +3 -3
- package/dist/public/main/memory/index.html +3 -3
- package/dist/public/main/memory.html +3 -3
- package/dist/public/main.html +3 -3
- package/dist/public/{markdown-BeglYzw9.js → markdown-BPZYpfGm.js} +1 -1
- package/dist/public/{orchestrator-BlvEG3PO.js → orchestrator-OoUK7CF9.js} +1 -1
- package/dist/public/{orchestrator-DTNrntd4.js → orchestrator-a9047bGu.js} +1 -1
- package/dist/public/{peerjs-CnBdK94R.js → peerjs-Cbn310Tz.js} +1 -1
- package/dist/public/{push-client-DOHbdCyj.js → push-client-Dy4LGJy9.js} +1 -1
- package/dist/public/service-worker.js +1 -1
- package/dist/public/shadow-claw-B-HWC1uN.js +1180 -0
- package/dist/public/{shadow-claw-accounts-C6FXVw2K.js → shadow-claw-accounts-Di-anCZ1.js} +1 -1
- package/dist/public/{shadow-claw-channels-tr_r60Kq.js → shadow-claw-channels-RVwCE8pE.js} +1 -1
- package/dist/public/{shadow-claw-chat-BAAPhAOs.js → shadow-claw-chat-DI1q8UnX.js} +1 -1
- package/dist/public/{shadow-claw-control-plane-C_5VIx8E.js → shadow-claw-control-plane-KXEdLOGl.js} +2 -2
- package/dist/public/{shadow-claw-conversations-DGYZdDa3.js → shadow-claw-conversations-BCBGtS30.js} +40 -6
- package/dist/public/{shadow-claw-file-viewer-5j2-Z3fN.js → shadow-claw-file-viewer-CW3t6j-w.js} +1 -1
- package/dist/public/{shadow-claw-files-DKF4Yy0m.js → shadow-claw-files-JQ-o0ImX.js} +1 -1
- package/dist/public/{shadow-claw-git-CtUTJXKT.js → shadow-claw-git-D2M8VixW.js} +2 -2
- package/dist/public/{shadow-claw-integrations-CuBy9D3z.js → shadow-claw-integrations-Cgw6v9_1.js} +1 -1
- package/dist/public/{shadow-claw-llm-BIfNNjGL.js → shadow-claw-llm-74ieXp7i.js} +1 -1
- package/dist/public/{shadow-claw-mcp-remote-C17FXvrb.js → shadow-claw-mcp-remote-BX0BkSmy.js} +1 -1
- package/dist/public/{shadow-claw-networking-CjxQ1CLI.js → shadow-claw-networking-DNX8vaIQ.js} +1 -1
- package/dist/public/{shadow-claw-notifications-Brn2O3Ps.js → shadow-claw-notifications-BLTaGAny.js} +1 -1
- package/dist/public/{shadow-claw-page-header-Bn1P7Cxb.js → shadow-claw-page-header-CjFOdo9v.js} +1 -1
- package/dist/public/shadow-claw-pages-DOQqMm0_.js +645 -0
- package/dist/public/{shadow-claw-settings-CfDm0hVA.js → shadow-claw-settings-DFtl0Fy8.js} +2 -2
- package/dist/public/{shadow-claw-storage-DOOesRzw.js → shadow-claw-storage-gQGExZRq.js} +1 -1
- package/dist/public/{shadow-claw-task-server-H36iDDp2.js → shadow-claw-task-server-Ca45uY7S.js} +1 -1
- package/dist/public/{shadow-claw-tasks-4JsjSGkN.js → shadow-claw-tasks-CCTaaSdi.js} +1 -1
- package/dist/public/{shadow-claw-terminal-CTRTcYz-.js → shadow-claw-terminal-BfgulLkl.js} +1 -1
- package/dist/public/{shadow-claw-tools-Dm1LxNf4.js → shadow-claw-tools-V8NA4n18.js} +1 -1
- package/dist/public/{shadow-claw-webvm-JzuPe9Nr.js → shadow-claw-webvm-CxxI2bnC.js} +1 -1
- package/dist/public/sync-web-mcp-registration-CkCA8UFm.js +1 -0
- package/dist/public/{tools-FiTtOlIt.js → tools-CwQq5tJH.js} +2 -2
- package/dist/public/webmcp-CmtWOAFm.js +6 -0
- package/dist/server.js +2 -2
- package/package.json +3 -3
- package/src/cli/prerender/dsd-shell/prerender-dsd-shell.test.ts +16 -0
- package/src/cli/prerender/dsd-shell/prerender-dsd-shell.ts +62 -1
- package/src/cli/prerender/pretty-paths/prerender-pretty-paths.test.ts +277 -0
- package/src/cli/prerender/pretty-paths/prerender-pretty-paths.ts +28 -1
- package/src/cli/site-config/custom-elements/build-custom-element-script-tags.ts +13 -1
- package/src/components/shadow-claw/shadow-claw.css +12 -0
- package/src/components/shadow-claw/shadow-claw.html +12 -2
- package/src/components/shadow-claw/utils/bind-event-listeners.test.ts +18 -0
- package/src/components/shadow-claw/utils/bind-event-listeners.ts +14 -0
- package/src/components/shadow-claw/utils/get-route.test.ts +35 -0
- package/src/components/shadow-claw/utils/get-route.ts +18 -0
- package/src/components/shadow-claw/utils/sync-slotted-sidebar-active-links.test.ts +152 -1
- package/src/components/shadow-claw/utils/sync-slotted-sidebar-active-links.ts +139 -8
- package/src/components/shadow-claw-conversations/shadow-claw-conversations.css +11 -0
- package/src/components/shadow-claw-conversations/shadow-claw-conversations.html +27 -4
- package/src/components/shadow-claw-conversations/shadow-claw-conversations.ts +32 -4
- package/src/components/shadow-claw-pages/shadow-claw-pages-scripts.test.ts +266 -0
- package/src/components/shadow-claw-pages/shadow-claw-pages.ts +41 -17
- package/src/core/orchestrator/utils/sync-web-mcp-registration.test.ts +18 -1
- package/src/core/orchestrator/utils/sync-web-mcp-registration.ts +8 -0
- package/src/core/utils/init-control-plane.test.ts +9 -4
- package/src/security/custom-element-security.test.ts +65 -0
- package/src/security/custom-element-security.ts +67 -4
- package/src/stores/tools.test.ts +5 -3
- package/src/stores/tools.ts +5 -10
- package/src/subsystems/mcp/webmcp.test.ts +84 -13
- package/src/subsystems/mcp/webmcp.ts +73 -10
- package/src/utils/index.ts +1 -0
- package/src/utils/resolve-page-script-dependencies.test.ts +245 -0
- package/src/utils/resolve-page-script-dependencies.ts +198 -0
- package/dist/cli/chunk-B1hufJeO.js +0 -1
- package/dist/cli/chunk-BZpn8npn.js +0 -1
- package/dist/cli/chunk-Bw5aOTFr.js +0 -1
- package/dist/cli/chunk-C8nH01Gw.js +0 -32
- package/dist/cli/chunk-CK1ZoyoE.js +0 -17
- package/dist/cli/chunk-CVkhDr-7.js +0 -1
- package/dist/cli/chunk-Cum07Vlh.js +0 -1
- package/dist/cli/chunk-D3UhDDmV.js +0 -2
- package/dist/cli/chunk-D8GI6qj6.js +0 -1
- package/dist/cli/chunk-DEH-FvmP.js +0 -1
- package/dist/cli/chunk-DksvJ_kf.js +0 -1
- package/dist/cli/chunk-RGb9wM4R.js +0 -1
- package/dist/lib/shadow-claw-PdOpgTxH.js.map +0 -1
- package/dist/lib/shadow-claw-pages-DLspFqdK.js.map +0 -1
- package/dist/lib/sync-web-mcp-registration-dW2MVCj4.js.map +0 -1
- package/dist/lib/tools-D7whby3H.js.map +0 -1
- package/dist/lib/webmcp-CYTNZfkn.js +0 -1687
- package/dist/lib/webmcp-CYTNZfkn.js.map +0 -1
- package/dist/public/shadow-claw-CnNX-WCh.js +0 -1158
- package/dist/public/shadow-claw-pages-BwOOqRWW.js +0 -645
- package/dist/public/sync-web-mcp-registration-BnHVUjat.js +0 -1
- package/dist/public/webmcp-_TBqXlVW.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"./rolldown-runtime-DBVvNlSN.js";import{b as i,l as a,t as o,x as s}from"./custom-element-security-
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./rolldown-runtime-DBVvNlSN.js";import{b as i,l as a,t as o,x as s}from"./custom-element-security-BR4V40j4.js";import{t as c}from"./browser-B1SoUj6D.js";import{C as l,F as u,I as d,O as f,P as p,R as m,c as h,m as g,n as _,o as v,r as y,u as b,y as x}from"./config-y_2Fg77m.js";import{a as S,m as C,n as w,o as T}from"./app-routes-H23VN-4O.js";import{n as E}from"./db-BUuJo1Gf.js";import{n as ee,t as D}from"./tx-promise-DNVEN3Wa.js";import{t as O}from"./get-config-Bkvl__ZS.js";import{n as te}from"./html-BwtE_7wp.js";import{t as k}from"./dist-CeFyqf9k.js";import{n as ne,r as re,t as ie}from"./headless-D6caaop6.js";import{a as ae,o as oe,r as se,s as ce,t as le}from"./get-group-dir-CffDzUlA.js";import{a as ue,c as de,d as fe,f as pe,i as me,o as he,r as ge,s as _e,t as ve,u as ye}from"./tools-CwQq5tJH.js";import{t as A}from"./set-config-DSiuMe0k.js";import{t as be}from"./ulid-BSJxYh6W.js";import{i as xe,r as Se,t as Ce}from"./tools-CHxUdGxZ.js";import"./tools-C4xNCwrc.js";import{t as we}from"./buffer-B98mcmH0.js";import{n as Te,r as Ee}from"./crypto-4ETeplbS.js";import{c as De,d as Oe,i as ke,l as Ae,m as je,n as Me,p as Ne,r as Pe,t as Fe}from"./mcp-reconnect-RRTXE25_.js";import{t as Ie}from"./stream-browserify-D3GBRf4E.js";import{a as Le,c as Re,d as ze,f as Be,h as Ve,i as He,l as Ue,m as We,n as Ge,o as Ke,p as qe,r as Je,s as Ye,t as Xe,u as Ze}from"./is-typed-array-BGsHBea7.js";import{n as Qe,o as $e,r as et,t as tt}from"./constants-DySRhLEI.js";import{n as nt}from"./parse-boolean-config-BigJ9U46.js";import{a as rt,i as it,n as at,o as ot,r as st,s as ct,t as lt}from"./connections-CggE17Ms.js";import{t as ut}from"./get-all-tasks-C5vFq6fC.js";import{r as dt,s as ft}from"./push-client-Dy4LGJy9.js";import{a as pt,o as mt,r as ht}from"./toast-CtIuHprH.js";function gt(e,t,n,r){let i=t*2**e,a=Math.min(i,n),o=a*r*Math.random();return Math.max(0,a-o)}function _t(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new DOMException(`Aborted`,`AbortError`));return}let i=setTimeout(n,e);if(t){let e=()=>{clearTimeout(i),r(t.reason??new DOMException(`Aborted`,`AbortError`))};t.addEventListener(`abort`,e,{once:!0});let a=n;n=(n=>{t.removeEventListener(`abort`,e),a(n)})}})}async function vt(){let e=typeof globalThis<`u`?globalThis:void 0;e?.scheduler&&typeof e.scheduler.yield==`function`?await e.scheduler.yield():await new Promise(e=>setTimeout(e,0))}const yt={openrouter:{label:`OpenRouter API Keys`,href:`https://openrouter.ai/keys`},huggingface:{label:`HuggingFace Access Tokens`,href:`https://huggingface.co/settings/tokens`},bedrock_proxy:{label:`AWS Bedrock Setup`,href:`https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html`},ollama:{label:`Install Ollama`,href:`https://ollama.com/download`},prompt_api:{label:`Prompt API Docs`,href:`https://developer.chrome.com/docs/ai/built-in`}},bt=/* @__PURE__ */ new Set([`ollama`,`bedrock_proxy`,`llamafile`,`transformers_js_local`]);function xt(e){return u(e)?.name||e}function St(e,t,n){let r=(t||``).toLowerCase();return r?n&&(r.includes(`api key not configured`)||r.includes(`go to settings to add your api key`)||r.includes(`missing api key`)||r.includes(`no api key`))?`api-key-missing`:n&&(r.includes(`invalid api key`)||r.includes(`incorrect api key`)||r.includes(`authentication failed`)||r.includes(`401`)||r.includes(`403`)||r.includes(`unauthorized`)||r.includes(`forbidden`))?`api-key-invalid`:r.includes(`429`)||r.includes(`rate limit`)||r.includes(`too many requests`)?`rate-limited`:r.includes(`failed to fetch`)||r.includes(`networkerror`)||r.includes(`network error`)||r.includes(`econnrefused`)||r.includes(`connection refused`)||r.includes(`enotfound`)||r.includes(`timed out`)||r.includes(`timeout`)||r.includes(`503`)||r.includes(`502`)?`provider-unreachable`:null:null}function Ct(e,t,n){let r=xt(e),i=yt[e]?[yt[e]]:[],a=[],o=`${r} Issue`,s=`ShadowClaw hit a ${r} provider error.`;return t===`api-key-missing`?(o=`${r} API Key Required`,s=`${r} needs an API key before requests can run.`,a.push(`Open Settings > AI > Model Provider and enter an API key as required.`),a.push(`Click Save Provider, then retry your message.`)):t===`api-key-invalid`?(o=`${r} Authentication Failed`,s=`${r} rejected the current API key.`,a.push(`Generate or copy a fresh API key for this provider.`),a.push(`Open Settings > AI > Model Provider, replace the key, click Save Provider, then retry.`)):t===`provider-unreachable`?(o=`${r} Not Reachable`,s=`ShadowClaw could not reach ${r}.`,bt.has(e)?(a.push(`Make sure the local ShadowClaw server is running (npm start) and the proxy URL in Settings is correct.`),a.push(`If this provider depends on another local runtime, verify it is running too.`)):(a.push(`Check internet connectivity and confirm the provider service is available.`),a.push(`If you are using a proxy or VPN, ensure requests to the provider are allowed.`))):t===`rate-limited`&&(o=`${r} Rate Limited`,s=`${r} is throttling requests right now.`,a.push(`Wait a moment and retry the request.`),a.push(`If this keeps happening, switch to a lower-traffic model or reduce request frequency.`)),n&&n.trim()&&a.push(`Details: ${n.trim()}`),{mode:`info`,title:o,message:s,details:a,links:i,confirmLabel:`OK`,autoCloseSeconds:30}}function wt(e){if(typeof e.size==`number`&&e.size>0)return e.size;if(typeof e.data==`string`&&e.data.length>0){let t=e.data.endsWith(`==`)?2:+!!e.data.endsWith(`=`);return Math.max(0,Math.floor(e.data.length*3/4)-t)}return 0}function Tt(e){return e?e.startsWith(`text/`)||e===`json`||e===`xml`||e===`javascript`||e===`csv`||e===`markdown`:!1}function Et(e){let t=wt(e);if(t===0)return 0;switch(e.mediaType){case`image`:return 1500;case`audio`:return 1500;case`video`:return 2500;default:return Tt(e.mimeType)?Math.ceil(t/4):Math.ceil(t/16)}}function Dt(e){return e?Math.ceil(e.length/4):0}function Ot(e){let t=0;if(typeof e.content==`string`)t=Dt(e.content);else if(Array.isArray(e.content))for(let n of e.content)if(n.type===`text`&&n.text)t+=Dt(n.text);else if(n.type===`tool_use`)t+=Dt(n.name),t+=Dt(JSON.stringify(n.input));else if(n.type===`tool_result`){let e=n.content;t+=Dt(typeof e==`string`?e:JSON.stringify(e))}else n.type===`attachment`&&(t+=Dt(n.fileName),t+=Dt(n.mimeType),t+=Dt(n.path),t+=Et(n));return t+4}function kt(e,t){if(!e)return``;if(e.length<=t)return e;let n=e.slice(0,t).lastIndexOf(`
|
|
2
2
|
`),r=n>t*.5?n:t;return`${e.slice(0,r)}\n[...truncated ${e.length-r} chars]`}function At(e,t){let{contextLimit:n,systemPromptTokens:r,maxOutputTokens:i,skimTop:a=!1}=t;if(e.length===0)return{messages:[],estimatedTokens:0,truncatedCount:0,contextLimit:n,usagePercent:0};let o=Math.max(0,n-r-i),s=Math.min(25e3,Math.max(1e3,Math.floor(o*.6*4))),c=e.map(e=>jt(e,s)),l=0,u=c.length,d=null,f=0;if(a&&c.length>0){let e=c[0];(e.role===`user`||e.role===`system`)&&(f=Ot(e),f<=o&&(d=e))}let p=o-f;for(let e=c.length-1;e>=+!!d;e--){let t=Ot(c[e]),n=c[e],r=!1;if(n.role===`user`&&Array.isArray(n.content)&&n.content.some(e=>e.type===`tool_result`)){let n=c[e-1];n&&n.role===`assistant`&&Array.isArray(n.content)&&n.content.some(e=>e.type===`tool_use`)&&(r=!0,t+=Ot(n))}if(l+t>p&&e<c.length-1)break;l+=t,r?(u=e-1,e--):u=e}let m=c.slice(u),h=u;d&&u>0&&(m=[d,...m],h=Math.max(0,u-1));let g=l+f,_=g+r,v=n>0?Math.round(_/n*100*10)/10:0;return{messages:m,estimatedTokens:g,truncatedCount:h,contextLimit:n,usagePercent:v}}function jt(e,t){if(!Array.isArray(e.content))return e;let n=e.content.map(e=>e.type===`tool_result`&&typeof e.content==`string`?{...e,content:kt(e.content,t)}:e);return{...e,content:n}}function Mt(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n){let i=e.subarray(r,r+n);t+=String.fromCharCode(...i)}return btoa(t)}function Nt(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}const Pt={apng:`image/apng`,avif:`image/avif`,bmp:`image/bmp`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,ico:`image/x-icon`,jpeg:`image/jpeg`,jpg:`image/jpeg`,png:`image/png`,svg:`image/svg+xml`,tif:`image/tiff`,tiff:`image/tiff`,webp:`image/webp`},Ft={...Pt,"3gp":`video/3gpp`,aac:`audio/aac`,avi:`video/x-msvideo`,bin:`application/octet-stream`,css:`text/css`,csv:`text/csv`,db:`application/vnd.sqlite3`,dll:`application/octet-stream`,dmg:`application/octet-stream`,dylib:`application/octet-stream`,exe:`application/vnd.microsoft.portable-executable`,flac:`audio/flac`,flv:`video/x-flv`,gz:`application/gzip`,htm:`text/html`,html:`text/html`,iso:`application/octet-stream`,js:`text/javascript`,json:`application/json`,m4a:`audio/mp4`,m4v:`video/mp4`,markdown:`text/markdown`,md:`text/markdown`,mjs:`text/javascript`,mkv:`video/x-matroska`,mov:`video/mp4`,mp3:`audio/mpeg`,mp4:`video/mp4`,oga:`audio/ogg`,ogg:`audio/ogg`,ogv:`video/ogg`,pdf:`application/pdf`,rar:`application/vnd.rar`,so:`application/octet-stream`,sqlite:`application/vnd.sqlite3`,sqlite3:`application/vnd.sqlite3`,tar:`application/x-tar`,ts:`text/typescript`,tsx:`text/typescript`,txt:`text/plain`,wasm:`application/wasm`,wav:`audio/wav`,weba:`audio/webm`,webm:`video/webm`,wmv:`video/x-ms-wmv`,xml:`application/xml`,yaml:`text/yaml`,yml:`text/yaml`,zip:`application/zip`};function It(e){return e&&(e.split(/[?#]/,1)[0].replace(/\\/g,`/`).split(`/`).pop()||``).toLowerCase().split(`.`).pop()||``}function Lt(e,t){let n=It(e);return Ft[n]??t}function Rt(e){let t=It(e);return Pt[t]||null}function zt(e){return Rt(e)!==null}function Bt(e){let t=It(e);if(t===`md`||t===`markdown`||t===`txt`)return`text/plain`;if(t===`pdf`)return`application/pdf`;if(Pt[t])return Pt[t]}function Vt(e,t=``){return t||Lt(e,`application/octet-stream`)}function Ht(e=``,t=``){let n=(e&&e!==`application/octet-stream`?e:Lt(t)||e).toLowerCase(),r=t.toLowerCase();return n.startsWith(`text/`)||n.includes(`json`)||n.includes(`xml`)||r.endsWith(`.md`)||r.endsWith(`.txt`)?`text`:n.startsWith(`image/`)?`image`:n.startsWith(`audio/`)?`audio`:n.startsWith(`video/`)?`video`:n===`application/pdf`||r.endsWith(`.pdf`)?`document`:`file`}function Ut(e){let t=(e||``).toLowerCase(),n=m.getModelInfo(t);if(n){let e=n.supportsImageInput===!0||n.routesByRequestFeatures===!0,t=n.supportsAudioInput===!0||n.routesByRequestFeatures===!0,r=n.supportsVideoInput===!0||n.routesByRequestFeatures===!0,i=n.supportsDocumentInput===!0||n.routesByRequestFeatures===!0;if(n.supportsImageInput!==void 0||n.supportsAudioInput!==void 0||n.supportsVideoInput!==void 0||n.supportsDocumentInput!==void 0||n.routesByRequestFeatures)return{images:e,audio:t,video:r,documents:i,routerByFeatures:!!n.routesByRequestFeatures,source:`metadata`}}let r=t.includes(`no-vision`)||t.includes(`non-vision`)||t.includes(`text-only`),i=t===`openrouter/free`||t===`openrouter/auto`,a=!r&&[`gpt-4o`,`gpt-4.1`,`gpt-5`,`gpt-6`,`astra`,`claude-3`,`claude-4`,`claude-5`,`claude-sonnet`,`claude-haiku`,`claude-opus`,`claude-fable`,`claude-mythos`,`gemini`,`omni`,`llava`,`qwen-vl`,`-vl`,`vision`,`pixtral`].some(e=>t.includes(e)),o=!r&&(t.includes(`claude-3-5`)||t.includes(`claude-3.5`)||t.includes(`claude-3-7`)||t.includes(`claude-3.7`)||t.includes(`claude-4`)||t.includes(`claude-5`)||t.includes(`claude-fable`)||t.includes(`claude-mythos`)||t.includes(`gemini`)||t.includes(`gpt-4.1`)||t.includes(`gpt-5`)||t.includes(`gpt-6`)||t.includes(`astra`)||/claude-(?:sonnet|haiku|opus|fable|mythos)-\d/.test(t));return a?{images:!0,audio:t.includes(`omni`)||t.includes(`audio`),video:t.includes(`omni`)||t.includes(`video`)||t.includes(`gemini`),documents:o,routerByFeatures:i,source:`heuristic`}:{images:!1,audio:!1,video:!1,documents:!1,routerByFeatures:i,source:`unknown`}}function Wt(e){let t=Ut(e),n=[t.images?`images native`:`images fallback`,t.audio?`audio native`:`audio fallback`,t.video?`video native`:`video fallback`,t.documents?`PDFs native`:`PDFs fallback`];return t.routerByFeatures&&n.push(`router can adapt by request features`),n.join(` · `)}async function Gt(e=[],t,n={}){let r=n.maxInlineTextBytes??102400,i=[];for(let n of e){let e=n.mimeType||`application/octet-stream`,a=Ht(e,n.fileName),o=a===`text`?`file`:a===`document`?`document`:a,s=null;try{s=await t(n)}catch{s=null}let c=s?.length??(typeof n.size==`number`?n.size:0);if(a===`text`&&s&&c<=r)try{let e=new TextDecoder(`utf-8`).decode(s),t=e.includes("```")?`~~~~`:"```";i.push({type:`text`,text:`Attachment: ${n.fileName}\n${t}\n${e}\n${t}`});continue}catch{}let l={type:`attachment`,mediaType:o,fileName:n.fileName,mimeType:e,size:n.size,path:n.path};s&&(o===`image`&&c<=3145728||o===`audio`&&c<=5242880||o===`document`&&c<=20971520)&&(l.data=Mt(s)),i.push(l)}return i}async function Kt(e,t,n){let r=await le(e,t),{dirs:i,filename:a}=pe(n),o=r;for(let e of i)o=await o.getDirectoryHandle(e);let s=await o.getFileHandle(a);try{let e=await s.createSyncAccessHandle(),t=e.getSize(),n=new Uint8Array(t);return e.read(n,{at:0}),e.close(),n}catch{let e=await(await s.getFile()).arrayBuffer();return new Uint8Array(e)}}function qt(e,t,n){let r=null,i,a;return typeof e==`string`?(i=e,a=t):(r=e,i=t,a=n??50),r&&ee(r)?Promise.resolve().then(()=>(r.db.prepare(`SELECT * FROM messages WHERE groupId = ? ORDER BY timestamp DESC LIMIT ?`).all(i,a)??[]).reverse().map(Jt)):new Promise(async(e,t)=>{try{let n=r??await E();if(!n)return t(/* @__PURE__ */ Error(`failed to get transaction, cannot get recent messages.`));let o=n.transaction(`messages`,`readonly`);if(!o)return t(/* @__PURE__ */ Error(`failed to get transaction`));let s=o.objectStore(`messages`).index(`by-group-time`),c=IDBKeyRange.bound([i,0],[i,1/0]),l=s.openCursor(c,`prev`),u=[];l.onsuccess=()=>{let t=l.result;t&&u.length<a?(u.push(t.value),t.continue()):e(u.reverse())},l.onerror=()=>t(l.error)}catch(e){t(e)}})}function Jt(e){return{...e,isFromMe:!!e.isFromMe,isTrigger:!!e.isTrigger,attachments:e.attachments?JSON.parse(e.attachments):void 0,a2uiAction:e.a2uiAction?JSON.parse(e.a2uiAction):void 0,a2uiEnvelopes:e.a2uiEnvelopes?JSON.parse(e.a2uiEnvelopes):void 0}}async function Yt(e,t){let n=await qt(e,t),r=await E();return await Promise.all(n.map(async t=>{if(t.isFromMe)return{role:`assistant`,content:t.content};let n=`${t.sender}: ${t.content}`,i=t.attachments||[];if(i.length===0)return{role:`user`,content:n};let a=await Gt(i,async t=>!r||!t.path?null:Kt(r,e,t.path));return a.length===0?{role:`user`,content:n}:{role:`user`,content:[{type:`text`,text:n},...a]}}))}const Xt=`group_metadata`;async function Zt(e){let t=await O(e,Xt);if(!t)return[];try{return JSON.parse(t)}catch{return[]}}async function Qt(e,t){await A(e,Xt,JSON.stringify(t))}async function $t(e,t,n=`br:`,r){let i=await Zt(e),a={groupId:`${n}${r??be()}`,name:t,createdAt:Date.now()};return i.push(a),await Qt(e,i),a}async function en(e,t,n){let r=await Zt(e),i=r.find(e=>e.groupId===t);i&&(i.name=n),await Qt(e,r)}async function tn(e,t,n){let r=await Zt(e),i=r.find(e=>e.groupId===t);i&&(n&&n.length>0?i.toolTags=n:delete i.toolTags),await Qt(e,r)}async function nn(e,t){await Qt(e,(await Zt(e)).filter(e=>e.groupId!==t))}async function rn(e){let t=await Zt(e);if(t.length===0){let t={groupId:v,name:`Main`,createdAt:0};return await Qt(e,[t]),[t]}return t}async function an(e,t){let n=await Zt(e),r=new Map(n.map(e=>[e.groupId,e])),i=[];for(let e of t){let t=r.get(e);t&&(i.push(t),r.delete(e))}for(let e of n)r.has(e.groupId)&&i.push(e);await Qt(e,i)}async function on(e,t){let n=await Zt(e),r=n.find(e=>e.groupId===t);if(!r)return null;let i=t.indexOf(`:`),a={groupId:`${i>=0?t.slice(0,i+1):`br:`}${be()}`,name:`${r.name} (copy)`,createdAt:Date.now(),pinnedMaxTokens:r.pinnedMaxTokens,providerRuntimeOverrides:r.providerRuntimeOverrides?JSON.parse(JSON.stringify(r.providerRuntimeOverrides)):void 0,subagentModelSelectionMode:r.subagentModelSelectionMode,subagentMaxTokens:r.subagentMaxTokens,subagentPinnedProvider:r.subagentPinnedProvider,subagentPinnedModel:r.subagentPinnedModel,subagentFastProvider:r.subagentFastProvider,subagentFastModel:r.subagentFastModel,subagentSmartProvider:r.subagentSmartProvider,subagentSmartModel:r.subagentSmartModel,subagentPowerfulProvider:r.subagentPowerfulProvider,subagentPowerfulModel:r.subagentPowerfulModel,toolTags:r.toolTags?[...r.toolTags]:void 0};return n.push(a),await Qt(e,n),a}async function sn(e,t,n,r,i){let a=await Zt(e),o=a.find(e=>e.groupId===t);o&&(n?o.pinnedProvider=n:delete o.pinnedProvider,r?o.pinnedModel=r:delete o.pinnedModel,typeof i==`number`&&Number.isFinite(i)&&i>0?o.pinnedMaxTokens=Math.floor(i):delete o.pinnedMaxTokens),await Qt(e,a)}async function cn(e,t,n,r,i,a){let o=await Zt(e),s=o.find(e=>e.groupId===t);s&&(s.subagentModelSelectionMode=n,n===`manual`?(r?s.subagentPinnedProvider=r:delete s.subagentPinnedProvider,i?s.subagentPinnedModel=i:delete s.subagentPinnedModel):(delete s.subagentPinnedProvider,delete s.subagentPinnedModel),typeof a==`number`&&Number.isFinite(a)&&a>0?s.subagentMaxTokens=Math.floor(a):delete s.subagentMaxTokens),await Qt(e,o)}async function ln(e,t,n){let r=await Zt(e),i=r.find(e=>e.groupId===t);i&&(n&&Object.keys(n).length>0?i.providerRuntimeOverrides=JSON.parse(JSON.stringify(n)):delete i.providerRuntimeOverrides),await Qt(e,r)}const un=[/<\|start_header_id\|>\s*(?:system|user|assistant|tool)\s*<\|end_header_id\|>/gi,/<\|(?:begin_of_text|end_of_text|eot_id|im_start|im_end|end_of_message)\|>/gi,/<\|(?:startofturn|endofturn|start_of_turn|end_of_turn)\|>/gi,/<\|(?:image|audio|video|tool_call|tool_response|tool_result|function_call)\|>|<\|\/function_call\|>/gi,/<|(?:system|user|assistant|im_start|im_end)|>/g,/\[\s*INST\s*\]|\[\s*\/INST\s*\]|<<\s*SYS\s*>>|<<\s*\/SYS\s*>>/gi,/<\/?s>|<\/?bos>|<\/?eos>|<\|(?:bos|eos|pad|unk)\|>/gi,/<\|(?:START_OF_TURN_TOKEN|END_OF_TURN_TOKEN|CHATBOT_TOKEN|USER_TOKEN|SYSTEM_TOKEN)\|>/gi,/<\|(?:system|user|assistant|end|endoftext|placeholder\d*)\|>/gi,/<|(?:begin▁of▁sentence|end▁of▁sentence)|>/g,/<\|start\|>\s*(?:system|user|assistant|tool)\s*<\|message\|>/gi];function dn(e){for(let t of un)if(t.test(e))return!0;return!1}function fn(e){let t=String(e||``),n=t;for(let e of un)t=t.replace(e,``);return t!==n&&(t=t.replace(/^[ \t]+$/gm,``),t=t.replace(/\n{3,}/g,`
|
|
3
3
|
|
|
4
4
|
`)),t}function pn(e,t){let n=fn(e);return n!==e&&dn(e)&&console.info(`[ShadowClaw] Chat-template control token(s) detected and stripped from "${t}" output. The provider or model may not be applying its chat template correctly. Original length: ${e.length}, cleaned length: ${n.length}.`),n}function mn(e,t,n,r){return{type:`thinking-log`,payload:{groupId:e,level:t,timestamp:Date.now(),label:n,message:r||``}}}function hn(e,t,n){return{type:`tool-activity`,payload:{groupId:e,tool:t,status:n}}}async function gn(e,t,n,r){let{dirs:i,filename:a}=pe(n);for(let n=0;n<2;n++)try{let n=await le(e,t);for(let e of i)n=await n.getDirectoryHandle(e,{create:!0});let o=await n.getFileHandle(a,{create:!0});try{await he(o,r);return}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await ae(e)).type===`opfs`))throw t}let s=t.replace(/:/g,`-`);await _e([se(),`groups`,s,...i,a],r);return}catch(e){if(n===0&&ce(e)){oe();continue}throw e}}let _n=null;function vn(e){_n=e}const yn=/* @__PURE__ */ new Map;function bn(e,t){yn.set(e,t)}function xn(e){yn.delete(e)}function Sn(e){let t=e?.payload?.groupId;t&&yn.has(t)?yn.get(t).push(e):_n?_n(e):typeof self<`u`&&typeof self.postMessage==`function`&&self.postMessage(e)}const Cn=/* @__PURE__ */ new Set;async function wn(){kn()}async function Tn(e,t=900,n=null){{let e=Dn();return`Error: WebVM is not available. The VM requires local assets served at /assets/ (alpine-fs.json, libv86.mjs, etc). Use the "javascript" tool for code execution, or the "fetch_url" tool for HTTP requests.`+(e.error?`\nReason: ${e.error}`:e.booting?`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{m as e}from"./custom-element-security-Cl991z-x.js";import{D as t,E as n,F as r,I as i,M as a,O as o,P as s,R as c,T as l,_ as u,g as d,j as f,l as p,o as m,r as h,s as g,t as _,v,w as y}from"./config-y_2Fg77m.js";import"./app-routes-H23VN-4O.js";import{n as b,r as x}from"./db-BUuJo1Gf.js";import{n as S}from"./tx-promise-DNVEN3Wa.js";import{t as C}from"./get-config-Bkvl__ZS.js";import{t as w}from"./dist-CeFyqf9k.js";import{$ as ee,At as te,Bt as T,Cn as ne,Ct as E,Dn as D,E as O,En as k,F as re,Ft as A,G as j,Gt as M,I as N,It as ie,J as ae,Jt as oe,K as P,Kt as se,L as F,Lt as ce,Mt as le,Nt as I,Ot as ue,P as de,Pt as L,Q as R,Qt as fe,Rt as z,Tt as pe,Vt as me,W as he,Xt as ge,Yt as _e,Zt as ve,cn as ye,ct as be,dn as B,f as xe,fn as Se,gn as Ce,hn as we,ht as Te,jt as V,kt as Ee,ln as De,lt as Oe,mn as ke,mt as Ae,on as H,p as je,pn as U,pt as Me,q as Ne,qt as Pe,r as Fe,sn as Ie,t as W,wn as Le,xn as Re,yt as ze,z as Be,zt as Ve}from"./orchestrator-BlvEG3PO.js";import{n as He,r as Ue}from"./headless-D6caaop6.js";import{l as We,r as Ge}from"./get-group-dir-CffDzUlA.js";import{d as Ke,l as qe,o as Je,s as Ye,t as G}from"./tools-FiTtOlIt.js";import{t as K}from"./set-config-DSiuMe0k.js";import{t as q}from"./ulid-BSJxYh6W.js";import{t as Xe}from"./tools-CHxUdGxZ.js";import{i as Ze,r as Qe}from"./sync-web-mcp-registration-BnHVUjat.js";import"./tools-C4xNCwrc.js";import{n as $e,r as et}from"./crypto-4ETeplbS.js";import{a as tt,s as nt}from"./push-client-DOHbdCyj.js";import{i as rt,r as J,t as it}from"./peerjs-CnBdK94R.js";import{a as at,o as ot}from"./webmcp-_TBqXlVW.js";import{ensureControlPlaneConnected as st}from"./init-control-plane-BEbcwmmv.js";async function ct(e){if(e&&e.name!==`shadowclaw`){try{if(await C(e,h.DB_MIGRATED_FROM_LEGACY)===`true`)return}catch{}try{let t=await new Promise(e=>{let t=indexedDB.open(u);t.onsuccess=()=>{let n=t.result;!n.objectStoreNames||n.objectStoreNames.length===0?(n.close(),e(null)):e(n)},t.onerror=()=>e(null)});if(t){let n=Array.from(t.objectStoreNames).filter(t=>e.objectStoreNames.contains(t));for(let r of n)await new Promise(n=>{try{let i=t.transaction(r,`readonly`).objectStore(r).getAll();i.onsuccess=()=>{let t=i.result||[];if(t.length>0)try{let i=e.transaction(r,`readwrite`),a=i.objectStore(r);for(let e of t)a.put(e);i.oncomplete=()=>n(),i.onerror=()=>n(),i.onabort=()=>n()}catch{n()}else n()},i.onerror=()=>n()}catch{n()}});t.close()}}catch(e){console.warn(`Legacy IndexedDB migration warning:`,e)}finally{try{await K(e,h.DB_MIGRATED_FROM_LEGACY,`true`)}catch{}}}}async function lt(e,t,n){for await(let[r,i]of e.entries())if(i.kind===`directory`)await lt(i,await t.getDirectoryHandle(r,{create:!0}),[...n,r]);else if(i.kind===`file`){let e=await i.getFile(),a=await t.getFileHandle(r,{create:!0});try{await Je(a,e)}catch(t){if(!(t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`))throw t;await Ye([...n,r],e)}}}async function ut(e){if(!e)return;try{if(await C(e,h.OPFS_MIGRATED_FROM_LEGACY)===`true`)return}catch{}let t=Ge();if(t!==`shadowclaw`&&typeof navigator<`u`&&navigator.storage&&typeof navigator.storage.getDirectory==`function`)try{let n=await navigator.storage.getDirectory(),r;try{r=await n.getDirectoryHandle(v)}catch{try{await K(e,h.OPFS_MIGRATED_FROM_LEGACY,`true`)}catch{}return}let i=await n.getDirectoryHandle(t,{create:!0});await lt(r,i,[t])}catch(e){console.warn(`Legacy OPFS migration warning:`,e)}finally{try{await K(e,h.OPFS_MIGRATED_FROM_LEGACY,`true`)}catch{}}}function dt(){return new Promise(async(e,t)=>{let n,r=f(),i=indexedDB.open(r,2);i.onupgradeneeded=()=>{let e=i.result;if(!e.objectStoreNames.contains(`messages`)){let t=e.createObjectStore(`messages`,{keyPath:`id`});t.createIndex(`by-group-time`,[`groupId`,`timestamp`]),t.createIndex(`by-group`,`groupId`)}if(e.objectStoreNames.contains(`sessions`)||e.createObjectStore(`sessions`,{keyPath:`groupId`}),!e.objectStoreNames.contains(`tasks`)){let t=e.createObjectStore(`tasks`,{keyPath:`id`});t.createIndex(`by-group`,`groupId`),t.createIndex(`by-enabled`,`enabled`)}e.objectStoreNames.contains(`config`)||e.createObjectStore(`config`,{keyPath:`key`}),e.objectStoreNames.contains(`pendingShares`)||e.createObjectStore(`pendingShares`,{keyPath:`id`}).createIndex(`by-createdAt`,`createdAt`)},i.onsuccess=async()=>{n=i.result,x(n);try{await ct(n),await ut(n)}catch(e){console.warn(`Error running legacy migration:`,e)}e(n)},i.onerror=()=>{t(/* @__PURE__ */ Error(`Failed to open IndexedDB: ${i.error?.message}`))}})}var ft=class{activeGroupId;displayCallback;messageCallback;type;typingCallback;constructor(){this.type=`browser`,this.messageCallback=null,this.typingCallback=null,this.displayCallback=null,this.activeGroupId=m}getActiveGroup(){return this.activeGroupId}onDisplay(e){this.displayCallback=e}onMessage(e){this.messageCallback=e}onTyping(e){this.typingCallback=e}setActiveGroup(e){this.activeGroupId=e}setTyping(e,t){this.typingCallback?.(e,t)}start(){}stop(){}submit(e,t,n=[],r,i,a){let o=t||this.activeGroupId,s={id:q(),groupId:o,sender:`You`,content:e,timestamp:Date.now(),channel:`browser`,attachments:n,a2uiAction:r,freshContext:i,subagent:a};this.messageCallback?.(s)}async send(e,t,n){this.displayCallback?.(e,t,!0)}},pt=class{_entries;constructor(){this._entries=[]}find(e){return this.resolve(e)?.channel??null}get(e){return this._entries.find(t=>t.prefix===e)?.channel}getBadge(e){return this.resolve(e)?.badge??``}getChannelType(e){return this.resolve(e)?.channel.type??null}onMessage(e){for(let t of this._entries)t.channel.onMessage(e)}onTyping(e){for(let t of this._entries)t.channel.onTyping&&t.channel.onTyping(e)}prefixes(){return this._entries.map(e=>e.prefix)}register(e,t,n){let r=typeof n==`string`?{badge:n}:n??{};this._entries.push({prefix:e,channel:t,badge:r.badge??e.replace(/:$/,``),autoTrigger:r.autoTrigger??!1}),this._entries.sort((e,t)=>t.prefix.length-e.prefix.length)}resolve(e){for(let t of this._entries)if(e.startsWith(t.prefix))return t;return null}shouldAutoTrigger(e){return this.resolve(e)?.autoTrigger??!1}startAll(){for(let e of this._entries)e.channel.start()}stopAll(){for(let e of this._entries)e.channel.stop()}},mt=class{abortController=null;apiKey=``;apiMode=`unknown`;cursor=null;fileReader=null;messageCallback=null;reconnectDelayMs=1e3;registeredChatIds=/* @__PURE__ */ new Set;running=!1;seenMessageIds=/* @__PURE__ */ new Map;serverUrl=``;type=`imessage`;configure(e,t,n){this.serverUrl=ht(e),this.apiKey=t.trim(),this.registeredChatIds=new Set(n.map(e=>e.trim()).filter(Boolean)),this.cursor=null,this.apiMode=`unknown`}handleIncomingMessage(e){this.pruneSeenMessageIds();let t=String(e.chatId||e.conversationId||``).trim();if(!t||this.registeredChatIds.size>0&&!this.registeredChatIds.has(t))return;let n=`${e.text||e.body||``}`.trim();if(!n)return;let r=`${e.id||e.guid||`${t}:${e.timestamp||e.createdAt||n}`}`;if(this.seenMessageIds.has(r))return;this.seenMessageIds.set(r,Date.now());let i={id:r,groupId:`im:${t}`,sender:`${e.sender||e.handle||e.from||`iMessage`}`,content:n,timestamp:gt(e.timestamp||e.createdAt),channel:`imessage`};this.messageCallback?.(i)}handlePollResponse(e){e.nextCursor!==void 0&&e.nextCursor!==null?this.cursor=String(e.nextCursor):e.cursor!==void 0&&e.cursor!==null&&(this.cursor=String(e.cursor));let t=Array.isArray(e.messages)?e.messages:[];for(let e of t)this.handleIncomingMessage(e)}isConfigured(){return this.serverUrl.length>0}onMessage(e){this.messageCallback=e}pruneSeenMessageIds(){let e=Date.now();for(let[t,n]of this.seenMessageIds.entries())e-n>6e4&&this.seenMessageIds.delete(t)}setTyping(e,t){if(!t)return;let n=e.replace(/^im:/,``);this.requestJson(`/messages/typing`,{method:`POST`,body:JSON.stringify({chatId:n,typing:!0})}).catch(()=>{})}start(){this.isConfigured()&&!this.running&&(this.running=!0,this.abortController=new AbortController,this.poll())}ensureConnected(){this.isConfigured()&&this.running&&(this.reconnectDelayMs=1e3,this.abortController?.abort(),this.abortController=new AbortController,this.poll())}stop(){this.running=!1,this.abortController?.abort(),this.abortController=null}async ensureApiMode(){if(this.apiMode!==`unknown`)return this.apiMode;try{await this.requestJson(`/v1/info`,{method:`GET`}),this.apiMode=`beeper-desktop`}catch{this.apiMode=`legacy`}return this.apiMode}async poll(){for(;this.running&&this.abortController&&!this.abortController.signal.aborted;)try{let e=new URLSearchParams({timeout:`25`});this.cursor&&e.set(`cursor`,this.cursor);let t=await this.requestJson(`/messages?${e.toString()}`,{method:`GET`},d+5e3,this.abortController.signal);this.reconnectDelayMs=1e3,this.handlePollResponse(t)}catch(e){if(e instanceof Error&&e.name===`AbortError`)break;console.error(`iMessage bridge poll error:`,e),await _t(this.reconnectDelayMs),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,3e4)}}async requestJson(e,t,n=d,r){let i=new AbortController,a=setTimeout(()=>i.abort(),n),o=()=>i.abort();r?.addEventListener(`abort`,o,{once:!0});try{let n=new Headers(t.headers);n.set(`Accept`,`application/json`),!n.has(`Content-Type`)&&t.body&&!(t.body instanceof FormData)&&n.set(`Content-Type`,`application/json`),this.apiKey&&(n.set(`Authorization`,`Bearer ${this.apiKey}`),n.set(`X-API-Key`,this.apiKey));let r=await fetch(`${this.serverUrl}${e}`,{...t,headers:n,signal:i.signal});if(!r.ok){let e=await r.text();throw Error(`iMessage bridge request failed: ${r.status} ${e}`)}return r.status===204?{messages:[]}:await r.json()}finally{clearTimeout(a),r?.removeEventListener(`abort`,o)}}async send(e,t,n){let r=e.replace(/^im:/,``),{remainingText:i,attachments:a}=vt(t);for(let t of a)if(!this.fileReader)await this.sendText(r,`[${t.alt}] (file: ${t.path})`);else try{let n=await this.fileReader(e,t.path);if(!n||n.size===0)throw Error(`Attachment file is empty or unavailable.`);await this.sendAttachment(r,n,t)}catch(e){console.warn(`iMessage attachment send failed for ${t.path}:`,e),await this.sendText(r,`[${t.alt}] (file: ${t.path})`)}let o=i.trim();o&&await this.sendText(r,o)}async sendAttachment(e,t,n){await this.ensureApiMode()===`beeper-desktop`?await this.sendAttachmentViaBeeperDesktop(e,t,n):await this.sendAttachmentViaLegacyBridge(e,t,n)}async sendAttachmentViaBeeperDesktop(e,t,n){let r=n.path.split(`/`).pop()||`attachment.bin`,i=new FormData;i.append(`file`,t,r),i.append(`fileName`,r),t.type&&i.append(`mimeType`,t.type);let a=`${(await this.requestJson(`/v1/assets/upload`,{method:`POST`,body:i})).uploadID||``}`.trim();if(!a)throw Error(`Beeper asset upload failed: missing uploadID`);await this.requestJson(`/v1/chats/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify({text:n.alt||void 0,attachment:{uploadID:a,fileName:r,mimeType:t.type||void 0}})})}async sendAttachmentViaLegacyBridge(e,t,n){let r=n.path.split(`/`).pop()||`attachment.bin`,i=new FormData;i.append(`chatId`,e),n.alt&&i.append(`text`,n.alt),i.append(`file`,t,r),await this.requestJson(`/messages/send`,{method:`POST`,body:i})}async sendText(e,t){await this.ensureApiMode()===`beeper-desktop`?await this.requestJson(`/v1/chats/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify({text:t})}):await this.requestJson(`/messages/send`,{method:`POST`,body:JSON.stringify({chatId:e,text:t})})}};function ht(e){return e.trim().replace(/\/+$/,``)}function gt(e){if(typeof e==`number`&&Number.isFinite(e))return e>0xe8d4a51000?e:e*1e3;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return gt(t);let n=Date.parse(e);if(Number.isFinite(n))return n}return Date.now()}function _t(e){return new Promise(t=>setTimeout(t,e))}function vt(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r=null,i=e;for(;(r=n.exec(e))!==null;){let e=r[1]||``,n=yt((r[2]||``).trim());n&&(t.push({alt:e,path:n}),i=i.replace(r[0],``))}return{remainingText:i,attachments:t}}function yt(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}var bt=class{messageCallback=null;running=!1;type=`room`;typingCallback=null;_manager=null;_peerjs=null;deliverInbound(e){this.messageCallback?.(e)}onMessage(e){this.messageCallback=e}onTyping(e){this.typingCallback=e}setManager(e){this._manager=e}setPeerJs(e){this._peerjs=e}setTyping(e,t){}start(){this.running=!0}stop(){this.running=!1}async send(e,t,n){if(!this._manager)return;let r=ve(e);if(n&&n.length>0&&this._peerjs){let t=this._manager.get(r);t&&await this._peerjs.sendAttachmentsToRoom(t,e,n)}this._manager.broadcast(r,t,n)}};const xt=1e3;var St=class{abortController=null;fileReader=null;messageCallback=null;offset=0;pollRetryDelayMs=xt;pollSessionId=0;registeredChatIds=/* @__PURE__ */ new Set;running=!1;token=``;type=`telegram`;useProxy=!1;buildFileUrl(e){let t=e.split(`/`).filter(Boolean).map(e=>encodeURIComponent(e)).join(`/`);return`${this.useProxy?`/telegram/file/bot`:`https://api.telegram.org/file/bot`}${this.token}/${t}`}buildMethodUrl(e){let n=e.replace(/^\/+/,``);return`${this.useProxy?t:l}${this.token}/${n}`}configure(e,t,n=!1){this.token=e.trim(),this.registeredChatIds=new Set(t.map(e=>e.trim()).filter(Boolean)),this.useProxy=!!n}isConfigured(){return this.token.length>0}nextPollRetryDelay(){let e=this.pollRetryDelayMs;return this.pollRetryDelayMs=Math.min(this.pollRetryDelayMs*2,6e4),e}onMessage(e){this.messageCallback=e}registerChatId(e){let t=e.trim();t&&this.registeredChatIds.add(t)}resetPollBackoff(){this.pollRetryDelayMs=xt}setTyping(e,t){if(!t)return;let n=e.replace(/^tg:/,``);this.apiCall(`sendChatAction`,{chat_id:n,action:`typing`}).catch(()=>{})}start(){if(!this.token||this.running)return;this.running=!0,this.resetPollBackoff();let e=++this.pollSessionId,t=new AbortController;this.abortController=t,this.poll(e,t)}ensureConnected(){if(!this.token||!this.running)return;this.resetPollBackoff(),this.abortController?.abort();let e=++this.pollSessionId,t=new AbortController;this.abortController=t,this.poll(e,t)}stop(){this.running=!1,this.resetPollBackoff(),this.pollSessionId+=1,this.abortController?.abort(),this.abortController=null}async apiCall(e,t){let n=await fetch(this.buildMethodUrl(e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let t=await n.text();throw Error(`Telegram API ${e} failed: ${n.status} ${t}`)}return await n.json()}async extractAttachments(e){let t=[],n=Array.isArray(e.photo)?e.photo.at(-1):null;n?.file_id&&t.push({id:n.file_id,fileName:`photo-${e.message_id}.png`,mimeType:`image/png`,previewDisposition:`inline`}),e.document?.file_id&&t.push({id:e.document.file_id,fileName:e.document.file_name||`document-${e.message_id}`,mimeType:e.document.mime_type}),e.video?.file_id&&t.push({id:e.video.file_id,fileName:e.video.file_name||`video-${e.message_id}.mp4`,mimeType:e.video.mime_type||`video/mp4`}),e.audio?.file_id&&t.push({id:e.audio.file_id,fileName:e.audio.file_name||`audio-${e.message_id}.mp3`,mimeType:e.audio.mime_type||`audio/mpeg`}),e.voice?.file_id&&t.push({id:e.voice.file_id,fileName:`voice-${e.message_id}.ogg`,mimeType:e.voice.mime_type||`audio/ogg`}),e.animation?.file_id&&t.push({id:e.animation.file_id,fileName:e.animation.file_name||`animation-${e.message_id}.mp4`,mimeType:e.animation.mime_type||`video/mp4`}),e.sticker?.file_id&&t.push({id:e.sticker.file_id,fileName:`sticker-${e.message_id}.${Tt(e.sticker)}`,mimeType:e.sticker.is_animated?`application/x-tgsticker`:e.sticker.is_video?`video/webm`:`image/webp`});let r=[];for(let e of t){let t=await this.fetchTelegramFileInfo(e.id);r.push({id:e.id,fileName:e.fileName,mimeType:e.mimeType,size:t.file_size,previewDisposition:e.previewDisposition,source:{kind:`remote-url`,url:this.buildFileUrl(t.file_path)}})}return r}async fetchTelegramFileInfo(e){let t=await this.apiCall(`getFile`,{file_id:e});if(!t.ok||!t.result?.file_path)throw Error(`Telegram getFile failed for attachment ${e}`);return t.result}async handleUpdate(e){let t=e.message;if(!t)return;let n=String(t.chat.id);if(t.text===`/chatid`){this.apiCall(`sendMessage`,{chat_id:n,text:`Chat ID: ${n}\nRegister this ID in ShadowClaw settings.`}).catch(console.error);return}if(t.text===`/ping`){this.apiCall(`sendMessage`,{chat_id:n,text:`Pong! ShadowClaw is running.`}).catch(console.error);return}if(!this.registeredChatIds.has(n))return;let r=await this.extractAttachments(t),i=`${t.text||t.caption||``}`.trim()||(t.photo?.length?`[Photo]`:null)||(t.voice?`[Voice message]`:null)||(t.video?`[Video]`:null)||(t.audio?`[Audio]`:null)||(t.animation?`[Animation]`:null)||(t.document?`[Document: ${t.document.file_name||`unnamed`}]`:null)||(t.sticker?`[Sticker: ${t.sticker.emoji||``}]`:null)||(t.location?`[Location: ${t.location.latitude}, ${t.location.longitude}]`:null)||(t.contact?`[Contact: ${t.contact.first_name}]`:null)||`[Unsupported message type]`,a=t.from?.first_name||t.from?.username||String(t.from?.id||`Unknown`),o={id:String(t.message_id),groupId:`tg:${n}`,sender:a,content:i,timestamp:t.date*1e3,channel:`telegram`,attachments:r};this.messageCallback?.(o)}async poll(e,t){for(;this.running&&this.pollSessionId===e&&!t.signal.aborted;)try{let e=await fetch(this.buildMethodUrl(`getUpdates?offset=${this.offset}&timeout=30`),{signal:t.signal});if(!e.ok){console.error(`Telegram poll error: HTTP ${e.status}`),await this.waitForRetry(this.nextPollRetryDelay());continue}let n=await e.json();if(!n.ok||!Array.isArray(n.result)){await this.waitForRetry(this.nextPollRetryDelay());continue}this.resetPollBackoff();for(let e of n.result)this.offset=e.update_id+1,await this.handleUpdate(e)}catch(e){if(e instanceof Error&&e.name===`AbortError`)break;console.error(`Telegram poll error:`,e),await this.waitForRetry(this.nextPollRetryDelay())}}async send(e,t,r){let i=e.replace(/^tg:/,``),{remainingText:a,attachments:o}=Et(t);for(let t of o){if(this.fileReader)try{let n=await this.fileReader(e,t.path);if(n&&n.size>0){let e=t.path.toLowerCase();e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.gif`)||e.endsWith(`.webp`)?await this.sendPhoto(i,n,t.alt,t.path):await this.sendDocument(i,n,t.alt,t.path);continue}}catch(e){console.warn(`TelegramChannel: failed to read file ${t.path}:`,e)}await this.apiCall(`sendMessage`,{chat_id:i,text:`[${t.alt}] (file: ${t.path})`})}let s=a.trim();if(s){let e=Ct(s,n);for(let t of e)await this.apiCall(`sendMessage`,{chat_id:i,text:t})}}async sendDocument(e,t,n,r){let i=r.split(`/`).pop()||`document.file`,a=new FormData;a.append(`chat_id`,e),a.append(`document`,t,i),n&&a.append(`caption`,n);let o=await fetch(this.buildMethodUrl(`sendDocument`),{method:`POST`,body:a});if(!o.ok){let e=await o.text();throw Error(`Telegram sendDocument failed: ${o.status} ${e}`)}}async sendPhoto(e,t,n,r){let i=r.split(`/`).pop()||`image.png`,a=new FormData;a.append(`chat_id`,e),a.append(`photo`,t,i),n&&a.append(`caption`,n);let o=await fetch(this.buildMethodUrl(`sendPhoto`),{method:`POST`,body:a});if(!o.ok){let e=await o.text();throw Error(`Telegram sendPhoto failed: ${o.status} ${e}`)}}async waitForRetry(e){await wt(e)}};function Ct(e,t){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let e=t,i=r.lastIndexOf(`
|
|
1
|
+
import{m as e}from"./custom-element-security-BR4V40j4.js";import{D as t,E as n,F as r,I as i,M as a,O as o,P as s,R as c,T as l,_ as u,g as d,j as f,l as p,o as m,r as h,s as g,t as _,v,w as y}from"./config-y_2Fg77m.js";import"./app-routes-H23VN-4O.js";import{n as b,r as x}from"./db-BUuJo1Gf.js";import{n as S}from"./tx-promise-DNVEN3Wa.js";import{t as C}from"./get-config-Bkvl__ZS.js";import{t as w}from"./dist-CeFyqf9k.js";import{$ as ee,At as te,Bt as T,Cn as ne,Ct as E,Dn as D,E as O,En as k,F as re,Ft as A,G as j,Gt as M,I as N,It as ie,J as ae,Jt as oe,K as P,Kt as se,L as F,Lt as ce,Mt as le,Nt as I,Ot as ue,P as de,Pt as L,Q as R,Qt as fe,Rt as z,Tt as pe,Vt as me,W as he,Xt as ge,Yt as _e,Zt as ve,cn as ye,ct as be,dn as B,f as xe,fn as Se,gn as Ce,hn as we,ht as Te,jt as V,kt as Ee,ln as De,lt as Oe,mn as ke,mt as Ae,on as H,p as je,pn as U,pt as Me,q as Ne,qt as Pe,r as Fe,sn as Ie,t as W,wn as Le,xn as Re,yt as ze,z as Be,zt as Ve}from"./orchestrator-OoUK7CF9.js";import{n as He,r as Ue}from"./headless-D6caaop6.js";import{l as We,r as Ge}from"./get-group-dir-CffDzUlA.js";import{d as Ke,l as qe,o as Je,s as Ye,t as G}from"./tools-CwQq5tJH.js";import{t as K}from"./set-config-DSiuMe0k.js";import{t as q}from"./ulid-BSJxYh6W.js";import{t as Xe}from"./tools-CHxUdGxZ.js";import{i as Ze,r as Qe}from"./sync-web-mcp-registration-CkCA8UFm.js";import"./tools-C4xNCwrc.js";import{n as $e,r as et}from"./crypto-4ETeplbS.js";import{a as tt,s as nt}from"./push-client-Dy4LGJy9.js";import{i as rt,r as J,t as it}from"./peerjs-Cbn310Tz.js";import{o as at,s as ot}from"./webmcp-CmtWOAFm.js";import{ensureControlPlaneConnected as st}from"./init-control-plane-DGOY_RNS.js";async function ct(e){if(e&&e.name!==`shadowclaw`){try{if(await C(e,h.DB_MIGRATED_FROM_LEGACY)===`true`)return}catch{}try{let t=await new Promise(e=>{let t=indexedDB.open(u);t.onsuccess=()=>{let n=t.result;!n.objectStoreNames||n.objectStoreNames.length===0?(n.close(),e(null)):e(n)},t.onerror=()=>e(null)});if(t){let n=Array.from(t.objectStoreNames).filter(t=>e.objectStoreNames.contains(t));for(let r of n)await new Promise(n=>{try{let i=t.transaction(r,`readonly`).objectStore(r).getAll();i.onsuccess=()=>{let t=i.result||[];if(t.length>0)try{let i=e.transaction(r,`readwrite`),a=i.objectStore(r);for(let e of t)a.put(e);i.oncomplete=()=>n(),i.onerror=()=>n(),i.onabort=()=>n()}catch{n()}else n()},i.onerror=()=>n()}catch{n()}});t.close()}}catch(e){console.warn(`Legacy IndexedDB migration warning:`,e)}finally{try{await K(e,h.DB_MIGRATED_FROM_LEGACY,`true`)}catch{}}}}async function lt(e,t,n){for await(let[r,i]of e.entries())if(i.kind===`directory`)await lt(i,await t.getDirectoryHandle(r,{create:!0}),[...n,r]);else if(i.kind===`file`){let e=await i.getFile(),a=await t.getFileHandle(r,{create:!0});try{await Je(a,e)}catch(t){if(!(t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`))throw t;await Ye([...n,r],e)}}}async function ut(e){if(!e)return;try{if(await C(e,h.OPFS_MIGRATED_FROM_LEGACY)===`true`)return}catch{}let t=Ge();if(t!==`shadowclaw`&&typeof navigator<`u`&&navigator.storage&&typeof navigator.storage.getDirectory==`function`)try{let n=await navigator.storage.getDirectory(),r;try{r=await n.getDirectoryHandle(v)}catch{try{await K(e,h.OPFS_MIGRATED_FROM_LEGACY,`true`)}catch{}return}let i=await n.getDirectoryHandle(t,{create:!0});await lt(r,i,[t])}catch(e){console.warn(`Legacy OPFS migration warning:`,e)}finally{try{await K(e,h.OPFS_MIGRATED_FROM_LEGACY,`true`)}catch{}}}function dt(){return new Promise(async(e,t)=>{let n,r=f(),i=indexedDB.open(r,2);i.onupgradeneeded=()=>{let e=i.result;if(!e.objectStoreNames.contains(`messages`)){let t=e.createObjectStore(`messages`,{keyPath:`id`});t.createIndex(`by-group-time`,[`groupId`,`timestamp`]),t.createIndex(`by-group`,`groupId`)}if(e.objectStoreNames.contains(`sessions`)||e.createObjectStore(`sessions`,{keyPath:`groupId`}),!e.objectStoreNames.contains(`tasks`)){let t=e.createObjectStore(`tasks`,{keyPath:`id`});t.createIndex(`by-group`,`groupId`),t.createIndex(`by-enabled`,`enabled`)}e.objectStoreNames.contains(`config`)||e.createObjectStore(`config`,{keyPath:`key`}),e.objectStoreNames.contains(`pendingShares`)||e.createObjectStore(`pendingShares`,{keyPath:`id`}).createIndex(`by-createdAt`,`createdAt`)},i.onsuccess=async()=>{n=i.result,x(n);try{await ct(n),await ut(n)}catch(e){console.warn(`Error running legacy migration:`,e)}e(n)},i.onerror=()=>{t(/* @__PURE__ */ Error(`Failed to open IndexedDB: ${i.error?.message}`))}})}var ft=class{activeGroupId;displayCallback;messageCallback;type;typingCallback;constructor(){this.type=`browser`,this.messageCallback=null,this.typingCallback=null,this.displayCallback=null,this.activeGroupId=m}getActiveGroup(){return this.activeGroupId}onDisplay(e){this.displayCallback=e}onMessage(e){this.messageCallback=e}onTyping(e){this.typingCallback=e}setActiveGroup(e){this.activeGroupId=e}setTyping(e,t){this.typingCallback?.(e,t)}start(){}stop(){}submit(e,t,n=[],r,i,a){let o=t||this.activeGroupId,s={id:q(),groupId:o,sender:`You`,content:e,timestamp:Date.now(),channel:`browser`,attachments:n,a2uiAction:r,freshContext:i,subagent:a};this.messageCallback?.(s)}async send(e,t,n){this.displayCallback?.(e,t,!0)}},pt=class{_entries;constructor(){this._entries=[]}find(e){return this.resolve(e)?.channel??null}get(e){return this._entries.find(t=>t.prefix===e)?.channel}getBadge(e){return this.resolve(e)?.badge??``}getChannelType(e){return this.resolve(e)?.channel.type??null}onMessage(e){for(let t of this._entries)t.channel.onMessage(e)}onTyping(e){for(let t of this._entries)t.channel.onTyping&&t.channel.onTyping(e)}prefixes(){return this._entries.map(e=>e.prefix)}register(e,t,n){let r=typeof n==`string`?{badge:n}:n??{};this._entries.push({prefix:e,channel:t,badge:r.badge??e.replace(/:$/,``),autoTrigger:r.autoTrigger??!1}),this._entries.sort((e,t)=>t.prefix.length-e.prefix.length)}resolve(e){for(let t of this._entries)if(e.startsWith(t.prefix))return t;return null}shouldAutoTrigger(e){return this.resolve(e)?.autoTrigger??!1}startAll(){for(let e of this._entries)e.channel.start()}stopAll(){for(let e of this._entries)e.channel.stop()}},mt=class{abortController=null;apiKey=``;apiMode=`unknown`;cursor=null;fileReader=null;messageCallback=null;reconnectDelayMs=1e3;registeredChatIds=/* @__PURE__ */ new Set;running=!1;seenMessageIds=/* @__PURE__ */ new Map;serverUrl=``;type=`imessage`;configure(e,t,n){this.serverUrl=ht(e),this.apiKey=t.trim(),this.registeredChatIds=new Set(n.map(e=>e.trim()).filter(Boolean)),this.cursor=null,this.apiMode=`unknown`}handleIncomingMessage(e){this.pruneSeenMessageIds();let t=String(e.chatId||e.conversationId||``).trim();if(!t||this.registeredChatIds.size>0&&!this.registeredChatIds.has(t))return;let n=`${e.text||e.body||``}`.trim();if(!n)return;let r=`${e.id||e.guid||`${t}:${e.timestamp||e.createdAt||n}`}`;if(this.seenMessageIds.has(r))return;this.seenMessageIds.set(r,Date.now());let i={id:r,groupId:`im:${t}`,sender:`${e.sender||e.handle||e.from||`iMessage`}`,content:n,timestamp:gt(e.timestamp||e.createdAt),channel:`imessage`};this.messageCallback?.(i)}handlePollResponse(e){e.nextCursor!==void 0&&e.nextCursor!==null?this.cursor=String(e.nextCursor):e.cursor!==void 0&&e.cursor!==null&&(this.cursor=String(e.cursor));let t=Array.isArray(e.messages)?e.messages:[];for(let e of t)this.handleIncomingMessage(e)}isConfigured(){return this.serverUrl.length>0}onMessage(e){this.messageCallback=e}pruneSeenMessageIds(){let e=Date.now();for(let[t,n]of this.seenMessageIds.entries())e-n>6e4&&this.seenMessageIds.delete(t)}setTyping(e,t){if(!t)return;let n=e.replace(/^im:/,``);this.requestJson(`/messages/typing`,{method:`POST`,body:JSON.stringify({chatId:n,typing:!0})}).catch(()=>{})}start(){this.isConfigured()&&!this.running&&(this.running=!0,this.abortController=new AbortController,this.poll())}ensureConnected(){this.isConfigured()&&this.running&&(this.reconnectDelayMs=1e3,this.abortController?.abort(),this.abortController=new AbortController,this.poll())}stop(){this.running=!1,this.abortController?.abort(),this.abortController=null}async ensureApiMode(){if(this.apiMode!==`unknown`)return this.apiMode;try{await this.requestJson(`/v1/info`,{method:`GET`}),this.apiMode=`beeper-desktop`}catch{this.apiMode=`legacy`}return this.apiMode}async poll(){for(;this.running&&this.abortController&&!this.abortController.signal.aborted;)try{let e=new URLSearchParams({timeout:`25`});this.cursor&&e.set(`cursor`,this.cursor);let t=await this.requestJson(`/messages?${e.toString()}`,{method:`GET`},d+5e3,this.abortController.signal);this.reconnectDelayMs=1e3,this.handlePollResponse(t)}catch(e){if(e instanceof Error&&e.name===`AbortError`)break;console.error(`iMessage bridge poll error:`,e),await _t(this.reconnectDelayMs),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,3e4)}}async requestJson(e,t,n=d,r){let i=new AbortController,a=setTimeout(()=>i.abort(),n),o=()=>i.abort();r?.addEventListener(`abort`,o,{once:!0});try{let n=new Headers(t.headers);n.set(`Accept`,`application/json`),!n.has(`Content-Type`)&&t.body&&!(t.body instanceof FormData)&&n.set(`Content-Type`,`application/json`),this.apiKey&&(n.set(`Authorization`,`Bearer ${this.apiKey}`),n.set(`X-API-Key`,this.apiKey));let r=await fetch(`${this.serverUrl}${e}`,{...t,headers:n,signal:i.signal});if(!r.ok){let e=await r.text();throw Error(`iMessage bridge request failed: ${r.status} ${e}`)}return r.status===204?{messages:[]}:await r.json()}finally{clearTimeout(a),r?.removeEventListener(`abort`,o)}}async send(e,t,n){let r=e.replace(/^im:/,``),{remainingText:i,attachments:a}=vt(t);for(let t of a)if(!this.fileReader)await this.sendText(r,`[${t.alt}] (file: ${t.path})`);else try{let n=await this.fileReader(e,t.path);if(!n||n.size===0)throw Error(`Attachment file is empty or unavailable.`);await this.sendAttachment(r,n,t)}catch(e){console.warn(`iMessage attachment send failed for ${t.path}:`,e),await this.sendText(r,`[${t.alt}] (file: ${t.path})`)}let o=i.trim();o&&await this.sendText(r,o)}async sendAttachment(e,t,n){await this.ensureApiMode()===`beeper-desktop`?await this.sendAttachmentViaBeeperDesktop(e,t,n):await this.sendAttachmentViaLegacyBridge(e,t,n)}async sendAttachmentViaBeeperDesktop(e,t,n){let r=n.path.split(`/`).pop()||`attachment.bin`,i=new FormData;i.append(`file`,t,r),i.append(`fileName`,r),t.type&&i.append(`mimeType`,t.type);let a=`${(await this.requestJson(`/v1/assets/upload`,{method:`POST`,body:i})).uploadID||``}`.trim();if(!a)throw Error(`Beeper asset upload failed: missing uploadID`);await this.requestJson(`/v1/chats/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify({text:n.alt||void 0,attachment:{uploadID:a,fileName:r,mimeType:t.type||void 0}})})}async sendAttachmentViaLegacyBridge(e,t,n){let r=n.path.split(`/`).pop()||`attachment.bin`,i=new FormData;i.append(`chatId`,e),n.alt&&i.append(`text`,n.alt),i.append(`file`,t,r),await this.requestJson(`/messages/send`,{method:`POST`,body:i})}async sendText(e,t){await this.ensureApiMode()===`beeper-desktop`?await this.requestJson(`/v1/chats/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify({text:t})}):await this.requestJson(`/messages/send`,{method:`POST`,body:JSON.stringify({chatId:e,text:t})})}};function ht(e){return e.trim().replace(/\/+$/,``)}function gt(e){if(typeof e==`number`&&Number.isFinite(e))return e>0xe8d4a51000?e:e*1e3;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return gt(t);let n=Date.parse(e);if(Number.isFinite(n))return n}return Date.now()}function _t(e){return new Promise(t=>setTimeout(t,e))}function vt(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r=null,i=e;for(;(r=n.exec(e))!==null;){let e=r[1]||``,n=yt((r[2]||``).trim());n&&(t.push({alt:e,path:n}),i=i.replace(r[0],``))}return{remainingText:i,attachments:t}}function yt(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}var bt=class{messageCallback=null;running=!1;type=`room`;typingCallback=null;_manager=null;_peerjs=null;deliverInbound(e){this.messageCallback?.(e)}onMessage(e){this.messageCallback=e}onTyping(e){this.typingCallback=e}setManager(e){this._manager=e}setPeerJs(e){this._peerjs=e}setTyping(e,t){}start(){this.running=!0}stop(){this.running=!1}async send(e,t,n){if(!this._manager)return;let r=ve(e);if(n&&n.length>0&&this._peerjs){let t=this._manager.get(r);t&&await this._peerjs.sendAttachmentsToRoom(t,e,n)}this._manager.broadcast(r,t,n)}};const xt=1e3;var St=class{abortController=null;fileReader=null;messageCallback=null;offset=0;pollRetryDelayMs=xt;pollSessionId=0;registeredChatIds=/* @__PURE__ */ new Set;running=!1;token=``;type=`telegram`;useProxy=!1;buildFileUrl(e){let t=e.split(`/`).filter(Boolean).map(e=>encodeURIComponent(e)).join(`/`);return`${this.useProxy?`/telegram/file/bot`:`https://api.telegram.org/file/bot`}${this.token}/${t}`}buildMethodUrl(e){let n=e.replace(/^\/+/,``);return`${this.useProxy?t:l}${this.token}/${n}`}configure(e,t,n=!1){this.token=e.trim(),this.registeredChatIds=new Set(t.map(e=>e.trim()).filter(Boolean)),this.useProxy=!!n}isConfigured(){return this.token.length>0}nextPollRetryDelay(){let e=this.pollRetryDelayMs;return this.pollRetryDelayMs=Math.min(this.pollRetryDelayMs*2,6e4),e}onMessage(e){this.messageCallback=e}registerChatId(e){let t=e.trim();t&&this.registeredChatIds.add(t)}resetPollBackoff(){this.pollRetryDelayMs=xt}setTyping(e,t){if(!t)return;let n=e.replace(/^tg:/,``);this.apiCall(`sendChatAction`,{chat_id:n,action:`typing`}).catch(()=>{})}start(){if(!this.token||this.running)return;this.running=!0,this.resetPollBackoff();let e=++this.pollSessionId,t=new AbortController;this.abortController=t,this.poll(e,t)}ensureConnected(){if(!this.token||!this.running)return;this.resetPollBackoff(),this.abortController?.abort();let e=++this.pollSessionId,t=new AbortController;this.abortController=t,this.poll(e,t)}stop(){this.running=!1,this.resetPollBackoff(),this.pollSessionId+=1,this.abortController?.abort(),this.abortController=null}async apiCall(e,t){let n=await fetch(this.buildMethodUrl(e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let t=await n.text();throw Error(`Telegram API ${e} failed: ${n.status} ${t}`)}return await n.json()}async extractAttachments(e){let t=[],n=Array.isArray(e.photo)?e.photo.at(-1):null;n?.file_id&&t.push({id:n.file_id,fileName:`photo-${e.message_id}.png`,mimeType:`image/png`,previewDisposition:`inline`}),e.document?.file_id&&t.push({id:e.document.file_id,fileName:e.document.file_name||`document-${e.message_id}`,mimeType:e.document.mime_type}),e.video?.file_id&&t.push({id:e.video.file_id,fileName:e.video.file_name||`video-${e.message_id}.mp4`,mimeType:e.video.mime_type||`video/mp4`}),e.audio?.file_id&&t.push({id:e.audio.file_id,fileName:e.audio.file_name||`audio-${e.message_id}.mp3`,mimeType:e.audio.mime_type||`audio/mpeg`}),e.voice?.file_id&&t.push({id:e.voice.file_id,fileName:`voice-${e.message_id}.ogg`,mimeType:e.voice.mime_type||`audio/ogg`}),e.animation?.file_id&&t.push({id:e.animation.file_id,fileName:e.animation.file_name||`animation-${e.message_id}.mp4`,mimeType:e.animation.mime_type||`video/mp4`}),e.sticker?.file_id&&t.push({id:e.sticker.file_id,fileName:`sticker-${e.message_id}.${Tt(e.sticker)}`,mimeType:e.sticker.is_animated?`application/x-tgsticker`:e.sticker.is_video?`video/webm`:`image/webp`});let r=[];for(let e of t){let t=await this.fetchTelegramFileInfo(e.id);r.push({id:e.id,fileName:e.fileName,mimeType:e.mimeType,size:t.file_size,previewDisposition:e.previewDisposition,source:{kind:`remote-url`,url:this.buildFileUrl(t.file_path)}})}return r}async fetchTelegramFileInfo(e){let t=await this.apiCall(`getFile`,{file_id:e});if(!t.ok||!t.result?.file_path)throw Error(`Telegram getFile failed for attachment ${e}`);return t.result}async handleUpdate(e){let t=e.message;if(!t)return;let n=String(t.chat.id);if(t.text===`/chatid`){this.apiCall(`sendMessage`,{chat_id:n,text:`Chat ID: ${n}\nRegister this ID in ShadowClaw settings.`}).catch(console.error);return}if(t.text===`/ping`){this.apiCall(`sendMessage`,{chat_id:n,text:`Pong! ShadowClaw is running.`}).catch(console.error);return}if(!this.registeredChatIds.has(n))return;let r=await this.extractAttachments(t),i=`${t.text||t.caption||``}`.trim()||(t.photo?.length?`[Photo]`:null)||(t.voice?`[Voice message]`:null)||(t.video?`[Video]`:null)||(t.audio?`[Audio]`:null)||(t.animation?`[Animation]`:null)||(t.document?`[Document: ${t.document.file_name||`unnamed`}]`:null)||(t.sticker?`[Sticker: ${t.sticker.emoji||``}]`:null)||(t.location?`[Location: ${t.location.latitude}, ${t.location.longitude}]`:null)||(t.contact?`[Contact: ${t.contact.first_name}]`:null)||`[Unsupported message type]`,a=t.from?.first_name||t.from?.username||String(t.from?.id||`Unknown`),o={id:String(t.message_id),groupId:`tg:${n}`,sender:a,content:i,timestamp:t.date*1e3,channel:`telegram`,attachments:r};this.messageCallback?.(o)}async poll(e,t){for(;this.running&&this.pollSessionId===e&&!t.signal.aborted;)try{let e=await fetch(this.buildMethodUrl(`getUpdates?offset=${this.offset}&timeout=30`),{signal:t.signal});if(!e.ok){console.error(`Telegram poll error: HTTP ${e.status}`),await this.waitForRetry(this.nextPollRetryDelay());continue}let n=await e.json();if(!n.ok||!Array.isArray(n.result)){await this.waitForRetry(this.nextPollRetryDelay());continue}this.resetPollBackoff();for(let e of n.result)this.offset=e.update_id+1,await this.handleUpdate(e)}catch(e){if(e instanceof Error&&e.name===`AbortError`)break;console.error(`Telegram poll error:`,e),await this.waitForRetry(this.nextPollRetryDelay())}}async send(e,t,r){let i=e.replace(/^tg:/,``),{remainingText:a,attachments:o}=Et(t);for(let t of o){if(this.fileReader)try{let n=await this.fileReader(e,t.path);if(n&&n.size>0){let e=t.path.toLowerCase();e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.gif`)||e.endsWith(`.webp`)?await this.sendPhoto(i,n,t.alt,t.path):await this.sendDocument(i,n,t.alt,t.path);continue}}catch(e){console.warn(`TelegramChannel: failed to read file ${t.path}:`,e)}await this.apiCall(`sendMessage`,{chat_id:i,text:`[${t.alt}] (file: ${t.path})`})}let s=a.trim();if(s){let e=Ct(s,n);for(let t of e)await this.apiCall(`sendMessage`,{chat_id:i,text:t})}}async sendDocument(e,t,n,r){let i=r.split(`/`).pop()||`document.file`,a=new FormData;a.append(`chat_id`,e),a.append(`document`,t,i),n&&a.append(`caption`,n);let o=await fetch(this.buildMethodUrl(`sendDocument`),{method:`POST`,body:a});if(!o.ok){let e=await o.text();throw Error(`Telegram sendDocument failed: ${o.status} ${e}`)}}async sendPhoto(e,t,n,r){let i=r.split(`/`).pop()||`image.png`,a=new FormData;a.append(`chat_id`,e),a.append(`photo`,t,i),n&&a.append(`caption`,n);let o=await fetch(this.buildMethodUrl(`sendPhoto`),{method:`POST`,body:a});if(!o.ok){let e=await o.text();throw Error(`Telegram sendPhoto failed: ${o.status} ${e}`)}}async waitForRetry(e){await wt(e)}};function Ct(e,t){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let e=t,i=r.lastIndexOf(`
|
|
2
2
|
`,t);i>t*.5&&(e=i),n.push(r.slice(0,e)),r=r.slice(e)}return n}function wt(e){return new Promise(t=>setTimeout(t,e))}function Tt(e){return e?.is_animated?`tgs`:e?.is_video?`webm`:`webp`}function Et(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r,i=e;for(;(r=n.exec(e))!==null;){let e=r[1],n=Dt((r[2]||``).trim());n&&(t.push({alt:e,path:n}),i=i.replace(r[0],``))}return{remainingText:i,attachments:t}}function Dt(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}function Ot(e,t){let n=JSON.stringify(e.dataModel??{},null,2),r=t?`${t}`:`The user`;return`[A2UI ACTION]\nsurfaceId: "${e.surfaceId}"\nactionId: "${e.actionId}"\n`+(t?`firedBy: "${t}"\n`:``)+`dataModel:\n${n}\n\nInstructions: ${r} triggered the "${e.actionId}" action on surface "${e.surfaceId}". The dataModel above contains the current form values. Use the appropriate tool(s) to fulfill the action based on the actionId and dataModel values. After you have a result, call render_component with action "updateDataModel" on surfaceId "${e.surfaceId}" to update the surface (e.g. set path "/result" to the output value). Do NOT respond with plain text only — always update the surface via render_component.`}var kt=class{static formatMessagesXml(e){let t=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`);return`<messages>\n${e.map(e=>`<message sender="${t(e.sender)}" time="${new Date(e.timestamp).toISOString()}">${t(e.content)}</message>`).join(`
|
|
3
3
|
`)}\n</messages>`}static formatOutbound(e){return e.replace(/<internal>[\s\S]*?<\/internal>/g,``).trim()}registry;constructor(e){this.registry=e}findChannel(e){return this.registry.find(e)}setTyping(e,t){this.findChannel(e)?.setTyping(e,t)}async send(e,t,n){let r=this.findChannel(e);r?await r.send(e,t,n):console.warn(`No channel for groupId: ${e}`)}};const At={"litert-community/gemma-4-E2B-it-litert-lm":`https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it-web.litertlm`,"litert-community/gemma-4-E4B-it-litert-lm":`https://huggingface.co/litert-community/gemma-4-E4B-it-litert-lm/resolve/main/gemma-4-E4B-it-web.litertlm`},jt=Object.keys(At);function Mt(){return typeof navigator<`u`&&`gpu`in navigator&&typeof WebAssembly<`u`&&`Suspending`in WebAssembly}let Y=null,Nt=null,Pt=null,Ft=null;const It=Pe;async function Lt(e,t,n){return se(e,t,n,{cacheName:`shadow-claw-litertlm-models`,chunkSize:It})}async function Rt(e,t,n){if(Nt===e&&Y)return Y;if(Pt&&Ft===e)return Pt;Ft=e,Pt=(async()=>{if(Y){try{await Y.delete?.()}catch{}Y=null,Nt=null}let r=At[e];if(!r)throw Error(`LiteRT-LM: Model '${e} is not supported. Supported models: ${jt.join(`, `)}`);let i=await import(`./dist-DUCZvcI2.js`).catch(()=>{throw Error(`LiteRT-LM: The @litert-lm/core package is not installed. Run: npm install @litert-lm/core`)}),a=i.Engine??i.default?.Engine;if(typeof a?.create!=`function`)throw Error(`LiteRT-LM: Could not locate Engine.create in @litert-lm/core. Ensure you have the latest version installed.`);let o=await Lt(r,t??(()=>{}),n),s=await a.create({model:o,mainExecutorSettings:{maxNumTokens:8192}});return Y=s,Nt=e,s})();try{return await Pt}finally{Pt=null,Ft=null}}function zt(e){if(!e)return null;let t=e.match(/<\|tool_call>call:([A-Za-z0-9_]+)(\{[\s\S]*?)(?:<tool_call\|>|$)/);if(!t)return null;let n=t[1],r=t[2];r=r.replace(/<\|"\|>/g,`"`);function i(e){return e.replace(/([{,]\s*)([A-Za-z_$][A-Za-z0-9_$]*)(\s*:)/g,`$1"$2"$3`)}let a={},o=[r,i(r)];for(let e of o)try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t)){a=t;break}}catch{}if(Object.keys(a).length===0){let e=r.indexOf(`{`),t=r.lastIndexOf(`}`);if(e>=0&&t>e){let n=r.slice(e,t+1);for(let e of[n,i(n)])try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t)){a=t;break}}catch{}}}return{name:n,input:a}}function Bt(e){let t=U(String(e||``),`litert_lm`).trim();if(!t)return null;let n=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&(t.type===`tool_use`||t.type===`response`))return t.tools_calls&&!t.tool_calls&&(t.tool_calls=t.tools_calls),{...t,format:`json`}}catch{}return null},r=n(t);if(r)return r;let i=t.indexOf(`{`),a=t.lastIndexOf(`}`);if(i>=0&&a>i&&(r=n(t.slice(i,a+1)),r))return r;if(t.includes(`"tool_use"`)){let e=/"name"\s*:\s*"([^"]+)"/.exec(t);if(e){let n={},r=/"input"\s*:\s*(\{.*?\})\s*(?:]|\}|"|$)/s.exec(t);if(r)try{n=JSON.parse(r[1])}catch{}return{type:`tool_use`,format:`json`,tool_calls:[{id:`litert_${Date.now()}`,name:e[1],input:n}]}}}let o=zt(t);return o?{type:`tool_use`,format:`model_specific`,tool_calls:[{id:`litert_${Date.now()}`,name:o.name,input:o.input}]}:null}function Vt(e,t,n){let r=[],i=e||``;if(n.length>0){let e=[``,`TOOL CALLING INSTRUCTIONS:`,`Return ONLY valid JSON (no markdown fences).`,`To call a tool: {"type":"tool_use","tool_calls":[{"name":"<tool>","input":{...}}]}`,`To reply: {"type":"response","response":"<your answer>"}`,`IMPORTANT: When you need to use a tool, output ONLY the JSON above — do NOT describe the call as text.`,``,`Available tools:`,n.map(e=>{let t=Object.keys(e.input_schema.properties||{}).join(`, `),n=e.description.split(`. `)[0];return`${e.name}(${t}): ${n}`}).join(`
|
|
4
4
|
`)].join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./config-y_2Fg77m.js";import{n as e}from"./db-BUuJo1Gf.js";import{t}from"./dist-CeFyqf9k.js";import{$t as n,gn as r,tn as i,un as a,xn as o}from"./orchestrator-BlvEG3PO.js";import{i as s}from"./tools-FiTtOlIt.js";import{t as c}from"./ulid-BSJxYh6W.js";function l(e){return n(e,{replacement:`-`,fallback:`attachment`,stripLeadingDots:!0,collapseReplacement:!0,stripControlChars:!0})}function u(e){return e.previewDisposition===`inline`||o(e.fileName,e.mimeType||``)===`image/png`}function d(e,t=``,n=Date.now()){let r=l(e),i=t.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``);return`attachments/${n}-${i?`${i}-`:``}${r}`}async function f(e,t,n=[]){let r=[];for(let i of n){let n=l(i.fileName||``),s=i.path||d(n,i.id),c=i.source,u=o(n,i.mimeType||``),f=i.size;if(c){let r=await p(c);u=o(n,i.mimeType||r.type),f=typeof f==`number`?f:r.size,await a(e,t,s,r)}r.push(m({...i,fileName:n,mimeType:u,size:f,path:s,previewDisposition:i.previewDisposition||(u===`image/png`?`inline`:`file`)}))}return r}async function p(e){if(e.kind===`local-file`)return e.file;if(e.kind===`inline-text`)return new Blob([e.text],{type:e.mimeType||`text/plain`});let t=await fetch(e.url,{headers:e.headers});if(!t.ok)throw Error(`Attachment download failed: HTTP ${t.status} ${t.statusText}`);return await t.blob()}function m(e){let{source:t,...n}=e;return n}const h=/* @__PURE__ */ new Set([`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_REJECTED`]),g=/* @__PURE__ */ new Set([`TASK_STATE_INPUT_REQUIRED`,`TASK_STATE_AUTH_REQUIRED`]),_={SEND_MESSAGE:`SendMessage`,SEND_STREAMING_MESSAGE:`SendStreamingMessage`,GET_TASK:`GetTask`,CANCEL_TASK:`CancelTask`,GET_AGENT_CARD:`GetAgentCard`},v={EVENT:`agui/event`},y={STATUS_UPDATE:`tasks/statusUpdate`,ARTIFACT_UPDATE:`tasks/artifactUpdate`},b={JOIN:`room/join`,ROSTER:`room/roster`,LEAVE:`room/leave`,MESSAGE:`room/message`,INVITE:`room/invite`,RELAY:`room/relay`,A2UI:`room/a2ui`,A2UI_ACTION:`room/a2ui-action`},x={TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603};function S(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`&&(e.id===null||typeof e.id==`string`||typeof e.id==`number`)&&typeof e.method==`string`}function C(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`&&(e.id===null||typeof e.id==`string`||typeof e.id==`number`)&&!(`method`in e)}function w(e){let t={url:`webrtc://${e.peerId}`,protocolBinding:`https://xt-ml.github.io/shadow-claw/bindings/webrtc-datachannel/v1`,protocolVersion:`1.0`},n={streaming:e.streaming??!0,pushNotifications:!1};return{name:e.name,description:e.description??`AI assistant agent (${e.name})`,version:e.version??`1.0.0`,supportedInterfaces:[t],capabilities:n,defaultInputModes:[`text/plain`,`application/json`],defaultOutputModes:[`text/plain`,`application/json`],skills:e.skills??[],iconUrl:e.iconUrl}}function T(){return{jsonrpc:`2.0`,id:c(),method:_.GET_AGENT_CARD}}function E(e,t){return{jsonrpc:`2.0`,id:e,result:t}}function D(e){if(e.error)return console.warn(`GetAgentCard returned error:`,e.error),null;let t=e.result;return!t||typeof t!=`object`||typeof t.name!=`string`||typeof t.version!=`string`?null:t}var O=class{_cards=/* @__PURE__ */ new Map;clear(){this._cards.clear()}delete(e){this._cards.delete(e)}entries(){return this._cards.entries()}get(e){return this._cards.get(e)}getDisplayName(e){return this._cards.get(e)?.name??e}has(e){return this._cards.has(e)}set(e,t){this._cards.set(e,t)}supportsStreaming(e){return this._cards.get(e)?.capabilities?.streaming??!1}};const k={maxTasks:100,maxHistoryPerTask:50},A=/* @__PURE__ */ new Map([[`TASK_STATE_SUBMITTED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_REJECTED`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])],[`TASK_STATE_WORKING`,/* @__PURE__ */ new Set([`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_INPUT_REQUIRED`,`TASK_STATE_AUTH_REQUIRED`])],[`TASK_STATE_INPUT_REQUIRED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])],[`TASK_STATE_AUTH_REQUIRED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])]]);var j=class{_config;_contextActiveTask=/* @__PURE__ */ new Map;_listeners=/* @__PURE__ */ new Set;_taskOrder=[];_tasks=/* @__PURE__ */ new Map;constructor(e){this._config={...k,...e}}addArtifact(e,t,n=!1){let r=this._tasks.get(e);if(!r)return;if(r.artifacts||=[],n){let e=r.artifacts.find(e=>e.artifactId===t.artifactId);e?e.parts.push(...t.parts):r.artifacts.push(t)}else r.artifacts.push(t);let i={taskId:r.id,contextId:r.contextId??``,artifact:t,append:n,lastChunk:!1};this._emit({type:`artifactUpdate`,taskId:r.id,contextId:r.contextId??``,payload:i})}cancelTask(e){let t=this._tasks.get(e);return!t||h.has(t.status.state)?!1:(this._transitionState(t,`TASK_STATE_CANCELED`,{messageId:c(),role:`ROLE_AGENT`,parts:[{text:`Task canceled by peer request.`}]}),!0)}clear(){this._tasks.clear(),this._taskOrder=[],this._contextActiveTask.clear()}emitRunError(e,t,n){let r=this._tasks.get(e);if(!r)return;let i={type:`RUN_ERROR`,message:t,code:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitRunFinished(e){let t=this._tasks.get(e);if(!t)return;let n={type:`RUN_FINISHED`,threadId:t.contextId??t.id,runId:t.id,timestamp:Date.now()};this._emitAGUI(t,n)}emitRunStarted(e){let t=this._tasks.get(e);if(!t)return;let n={type:`RUN_STARTED`,threadId:t.contextId??t.id,runId:t.id,timestamp:Date.now()};this._emitAGUI(t,n)}emitStateSnapshot(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`STATE_SNAPSHOT`,snapshot:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitTextMessageContent(e,t,n){let r=this._tasks.get(e);if(!r)return;let i={type:`TEXT_MESSAGE_CONTENT`,messageId:t,delta:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitTextMessageEnd(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`TEXT_MESSAGE_END`,messageId:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitTextMessageStart(e,t,n=`assistant`){let r=this._tasks.get(e);if(!r)return;let i={type:`TEXT_MESSAGE_START`,messageId:t,role:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitToolCallEnd(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitToolCallStart(e,t,n,r){let i=this._tasks.get(e);if(!i)return;let a={type:`TOOL_CALL_START`,toolCallId:t,toolCallName:n,parentMessageId:r,timestamp:Date.now()};this._emitAGUI(i,a)}getActiveTaskForContext(e){let t=this._contextActiveTask.get(e);if(t)return this._tasks.get(t)}getActiveTasks(){return Array.from(this._tasks.values()).filter(e=>!h.has(e.status.state))}getAllTasks(){return Array.from(this._tasks.values())}getTask(e){return this._tasks.get(e)}handleSendMessage(e){let t=e.message,n=t.contextId??c(),r=t.taskId??this._contextActiveTask.get(n);return r&&this._tasks.has(r)?this._continueTask(r,t):this._createTask(n,t)}markCompleted(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_COMPLETED`,t)}markFailed(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_FAILED`,{messageId:c(),role:`ROLE_AGENT`,parts:[{text:t}]})}markInputRequired(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_INPUT_REQUIRED`,t)}markWorking(e){let t=this._tasks.get(e);t&&this._transitionState(t,`TASK_STATE_WORKING`)}off(e){this._listeners.delete(e)}on(e){this._listeners.add(e)}_addTask(e){for(this._tasks.set(e.id,e),this._taskOrder.push(e.id);this._taskOrder.length>this._config.maxTasks;){let e=this._taskOrder.shift(),t=this._tasks.get(e);if(t&&h.has(t.status.state))this._tasks.delete(e),t.contextId&&this._contextActiveTask.delete(t.contextId);else{this._taskOrder.unshift(e);break}}}_continueTask(e,t){let n=this._tasks.get(e);return g.has(n.status.state)&&this._transitionState(n,`TASK_STATE_WORKING`),n.history||=[],n.history.push(t),n.history.length>this._config.maxHistoryPerTask&&(n.history=n.history.slice(-this._config.maxHistoryPerTask)),this._touchTask(e),{task:n}}_createTask(e,t){let n=c(),r={id:n,contextId:e,status:{state:`TASK_STATE_SUBMITTED`,timestamp:(/* @__PURE__ */ new Date()).toISOString()},history:[t]};return this._addTask(r),this._contextActiveTask.set(e,n),this._emitStatusUpdate(r),{task:r}}_emit(e){for(let t of this._listeners)try{t(e)}catch(e){console.error(`PeerTaskManager: listener error`,e)}}_emitAGUI(e,t){this._emit({type:`aguiEvent`,taskId:e.id,contextId:e.contextId??``,payload:t})}_emitStatusUpdate(e){let t={taskId:e.id,contextId:e.contextId??``,status:e.status};this._emit({type:`statusUpdate`,taskId:e.id,contextId:e.contextId??``,payload:t})}_touchTask(e){let t=this._taskOrder.indexOf(e);t!==-1&&(this._taskOrder.splice(t,1),this._taskOrder.push(e))}_transitionState(e,t,n){let r=e.status.state,i=A.get(r);i&&!i.has(t)?console.warn(`PeerTaskManager: invalid transition ${r} → ${t} for task ${e.id}`):h.has(r)?console.warn(`PeerTaskManager: task ${e.id} is in terminal state ${r}, cannot transition`):(e.status={state:t,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString()},h.has(t)&&e.contextId&&this._contextActiveTask.get(e.contextId)===e.id&&this._contextActiveTask.delete(e.contextId),this._emitStatusUpdate(e))}};const M=new t.State(null);let N=null;function P(e){N!==null&&(clearTimeout(N),N=null),M.set(e)}function F(e=1500){N!==null&&clearTimeout(N),N=setTimeout(()=>{M.set(null),N=null},e)}const I=15360;var L=class n{static _RECONNECT_BASE_MS=1e3;static _RECONNECT_MAX_MS=6e4;connectedPeersSignal=new t.State([]);connections=/* @__PURE__ */ new Map;messageCallback=null;myPeerId=``;peerCards=new O;running=!1;serverConfig={};transferProgressSignal=M;trustedPeerIds=/* @__PURE__ */ new Set;type=`peerjs`;typingCallback=null;_inboundRemap=/* @__PURE__ */ new Map;_localCard=null;_onTaskCompleteCallback=null;peer=null;_inboundSavePromises=/* @__PURE__ */ new Map;_pendingInboundFile=null;_pendingRequests=/* @__PURE__ */ new Map;_reconnectAttempts=0;_reconnectTimer=null;_roomNotificationHandler=null;_taskManagers=/* @__PURE__ */ new Map;_inboundTransfers=/* @__PURE__ */ new Map;constructor(){typeof globalThis.addEventListener==`function`&&globalThis.addEventListener(`peerjs-dc-handle-chunk`,e=>{if(e?.detail?.chunkInfo){if(this._inboundTransfers.size>0)return;let{count:t,total:n}=e.detail.chunkInfo,r=t+1;P({count:r,total:n,direction:`receive`}),r>=n&&F(1500)}})}completeActiveTask(e){let t=e.replace(/^peer:/,``),n=this._taskManagers.get(t);if(!n)return!1;let r=n.getActiveTasks();if(r.length===0)return!1;let i=r[r.length-1];return n.markWorking(i.id),n.markCompleted(i.id),!0}configure(e,t,n={}){this.myPeerId=e.trim(),this.trustedPeerIds=new Set(t.map(e=>e.trim()).filter(Boolean)),this.serverConfig=n}connectPeer(e){this._getOrOpenConnection(e)}getTaskManager(e){let t=this._taskManagers.get(e);return t||(t=new j,this._taskManagers.set(e,t),t.on(t=>{this._forwardTaskEvent(e,t)})),t}isConfigured(){return this.myPeerId.length>0}isPeerConnected(e){let t=this.connections.get(e);return!!t&&!!t.open}onMessage(e){this.messageCallback=e}onTaskComplete(e){this._onTaskCompleteCallback=e}onTyping(e){this.typingCallback=e}sendRoomNotification(e,t){let n=this._getOrOpenConnection(e);if(!n)return!1;if(n.open)try{return n.send(t),!0}catch(t){return console.error(`PeerJsChannel: failed to send room notification to ${e}:`,t),!1}return this._waitForOpen(n).then(()=>{try{n.send(t)}catch(t){console.error(`PeerJsChannel: failed to flush room notification to ${e}:`,t)}}).catch(()=>{}),!0}setRoomNotificationHandler(e){this._roomNotificationHandler=e}async sendAttachmentsToRoom(t,n,i){let a=this.myPeerId,o=(i||[]).filter(e=>!!e.path);if(o.length!==0)try{let i=await e();for(let e of o){let o;try{o=await r(i,n,e.path)}catch(t){console.warn(`PeerJsChannel: failed to read file ${e.path} for room:`,t);continue}let s=e.path,l=e.mimeType||`application/octet-stream`,u=Math.max(1,Math.ceil(o.length/I));for(let r of t.members){if(r.peerId===a)continue;let t=this._getOrOpenConnection(r.peerId);if(t)try{await this._waitForOpen(t);let e=c();t.send({type:`__file_header`,id:e,name:s,mimeType:l,size:o.length,totalChunks:u,chunkSize:I,groupId:n});for(let n=0;n<u;n++){let r=n*I,i=Math.min(r+I,o.length),a=o.subarray(r,i),c=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);t.send({type:`__file_chunk`,id:e,name:s,index:n,totalChunks:u,data:c}),P({count:n+1,total:u,direction:`send`}),await this._waitForBufferDrain(t)}F(1500)}catch(t){console.warn(`PeerJsChannel: failed to stream file ${e.path} to room member ${r.peerId}:`,t)}}}}catch(e){console.error(`PeerJsChannel: failed to access DB for room file transfer`,e)}}setTyping(e,t){let n=e.replace(/^peer:/,``),r=this.connections.get(n);if(r)try{r.send({type:`typing`,typing:t})}catch{}}start(){this.isConfigured()&&!this.running&&(this.running=!0,this._localCard=w({peerId:this.myPeerId,name:this.myPeerId,description:`ShadowClaw AI assistant`,streaming:!0}),this._initPeer())}ensureConnected(e=!1){if(!this.running||!this.isConfigured())return;this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0;let t=this.peer;if(!t||t.destroyed||e&&!t.open){if(t&&!t.destroyed)try{t.destroy()}catch{}this.peer=null,this._initPeer()}else if(t.disconnected)try{t.reconnect?.()}catch{this._initPeer()}}stop(){if(this.running=!1,this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this.connections.forEach(e=>{try{e.close()}catch{}}),this.connections.clear(),this.peerCards.clear(),this._taskManagers.clear(),this._pendingRequests.forEach(({timer:e})=>clearTimeout(e)),this._pendingRequests.clear(),this._updateConnectedPeersSignal(),this.peer){try{this.peer.destroy()}catch{}this.peer=null}}async send(t,n,i){let a=t.replace(/^peer:/,``),o=this._getOrOpenConnection(a);if(!o)console.warn(`PeerJsChannel: no connection available for ${a}`);else try{await this._waitForOpen(o);let{attachments:a}=R(n),s=[...(i||[]).filter(e=>!!e.path),...a.map(e=>({path:e.path,mimeType:`application/octet-stream`}))],l=/* @__PURE__ */ new Map,u=[];try{let n=await e();for(let e of s)if(e.path)try{let i=await r(n,t,e.path),a=e.path;l.has(e.path)||l.set(e.path,a);let s=e.mimeType||`application/octet-stream`,d=c(),f=Math.max(1,Math.ceil(i.length/I));o.send({type:`__file_header`,id:d,name:a,mimeType:s,size:i.length,totalChunks:f,chunkSize:I,groupId:t});for(let e=0;e<f;e++){let t=e*I,n=Math.min(t+I,i.length),r=i.subarray(t,n),s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);o.send({type:`__file_chunk`,id:d,name:a,index:e,totalChunks:f,data:s}),P({count:e+1,total:f,direction:`send`}),await this._waitForBufferDrain(o)}F(1500),u.push({kind:`file`,name:a,mimeType:s,size:i.length})}catch(t){console.warn(`PeerJsChannel: failed to process file ${e.path}:`,t)}}catch(e){console.error(`PeerJsChannel: failed to access DB`,e)}let d=n;for(let[e,t]of l){let n=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);d=d.replace(RegExp(`(!?\\[.*?\\])\\(${n}\\)`,`g`),`$1(${t})`)}let f=[...u,{kind:`text`,text:d}],p=c(),m={jsonrpc:`2.0`,id:p,method:_.SEND_MESSAGE,params:{message:{messageId:c(),role:`ROLE_AGENT`,parts:f}}};o.send(m),this._registerPendingRequest(p,e=>{})}catch(e){console.error(`PeerJsChannel: send failed for ${a}:`,e),window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{remotePeerId:a,error:e instanceof Error?e.message:String(e)}}))}}async sendA2UI(e,t){let n=e.replace(/^peer:/,``),r=this._getOrOpenConnection(n);if(!r)console.warn(`PeerJsChannel.sendA2UI: no connection available for ${n}`);else try{await this._waitForOpen(r);let e={jsonrpc:`2.0`,method:`message/send`,id:c(),params:{message:{role:`agent`,parts:[{kind:`a2ui`,envelope:t}]}}};r.send(e)}catch(e){console.error(`PeerJsChannel.sendA2UI: failed for ${n}:`,e)}}async sendA2UIAction(e,t){let n=e.replace(/^peer:/,``),r=this._getOrOpenConnection(n);if(!r)console.warn(`PeerJsChannel.sendA2UIAction: no connection available for ${n}`);else try{await this._waitForOpen(r);let e={jsonrpc:`2.0`,method:`message/send`,id:c(),params:{message:{role:`user`,parts:[{kind:`a2ui-action`,action:t}]}}};r.send(e)}catch(e){console.error(`PeerJsChannel.sendA2UIAction: failed for ${n}:`,e)}}_exchangeAgentCards(e,t){if(!this._localCard)return;let n=T();t.send(n),this._registerPendingRequest(n.id,t=>{let n=D(t);n&&(this.peerCards.set(e,n),console.log(`PeerJsChannel: received AgentCard from ${e}: "${n.name}"`))})}_forwardTaskEvent(e,t){let n=this.connections.get(e);if(!n)return;let r;switch(t.type){case`statusUpdate`:r=y.STATUS_UPDATE;break;case`artifactUpdate`:r=y.ARTIFACT_UPDATE;break;case`aguiEvent`:r=v.EVENT;break;default:return}let i={jsonrpc:`2.0`,method:r,params:t.payload};try{n.send(i)}catch(n){console.error(`PeerJsChannel: failed to forward ${t.type} to ${e}:`,n)}}_getOrOpenConnection(e){let t=this.connections.get(e);if(t)return t;if(!this.peer)return null;try{let t=this.peer.connect(e,{reliable:!0,serialization:`binary`});return t?(this._handleIncomingConnection(t),t):null}catch(t){return console.error(`PeerJsChannel: failed to connect to ${e}:`,t),null}}_handleA2ACancelTask(e,t){let n=t.params;if(!n?.taskId){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing taskId in CancelTask params`});return}let r=this._taskManagers.get(e);if(!r){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_FOUND,message:`Task not found: ${n.taskId}`});return}if(!r.cancelTask(n.taskId)){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_CANCELABLE,message:`Task not cancelable: ${n.taskId}`});return}let i=this.connections.get(e);if(i){let e=r.getTask(n.taskId),a={jsonrpc:`2.0`,id:t.id,result:{task:e}};i.send(a)}}_handleA2AGetTask(e,t){let n=t.params;if(!n?.taskId){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing taskId in GetTask params`});return}let r=this._taskManagers.get(e)?.getTask(n.taskId);if(!r){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_FOUND,message:`Task not found: ${n.taskId}`});return}let i=this.connections.get(e);if(i){let e={jsonrpc:`2.0`,id:t.id,result:{task:r}};i.send(e)}}_handleA2AJsonRpc(e,t){if(C(t)){let e=String(t.id??``),n=this._pendingRequests.get(e);n&&(clearTimeout(n.timer),this._pendingRequests.delete(e),n.resolve(t));return}let n=t.method;if(n){if(n.startsWith(`room/`))this._roomNotificationHandler?.(e,n,t.params);else if(S(t)){let r={[_.GET_AGENT_CARD]:(e,t)=>this._handleGetAgentCard(e,t),[_.SEND_MESSAGE]:(e,t)=>this._handleA2ASendMessage(e,t),[_.CANCEL_TASK]:(e,t)=>this._handleA2ACancelTask(e,t),[_.GET_TASK]:(e,t)=>this._handleA2AGetTask(e,t)}[n];if(r){r(e,t);return}if(n===`message/send`){let n=t.params;n?.message?.parts&&Array.isArray(n.message.parts)&&this._processInboundA2AEnvelope(e,n.message.parts).catch(e=>console.error(`PeerJsChannel: failed to process inbound A2A envelope`,e))}else this._sendJsonRpcError(e,t.id,{code:x.METHOD_NOT_FOUND,message:`Method not found: ${n}`})}else({[v.EVENT]:(e,t)=>this._handleAGUIEventNotification(e,t),[y.STATUS_UPDATE]:(e,t)=>this._handleTaskStatusNotification(e,t),[y.ARTIFACT_UPDATE]:()=>{},"message/send":(e,t)=>{t?.message?.parts&&Array.isArray(t.message.parts)&&this._processInboundA2AEnvelope(e,t.message.parts).catch(e=>console.error(`PeerJsChannel: failed to process inbound A2A envelope`,e))}})[n]?.(e,t.params)}}_handleA2ASendMessage(e,t){let n=t.params;if(!n?.message){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing message in SendMessage params`});return}let r=this._taskManagers.get(e);r||(r=new j,this._taskManagers.set(e,r),r.on(t=>{this._forwardTaskEvent(e,t)}));let i=r.handleSendMessage(n),a=this.connections.get(e);if(a){let e={jsonrpc:`2.0`,id:t.id,result:i};a.send(e)}n.message.parts&&Array.isArray(n.message.parts)&&this._processInboundA2AEnvelope(e,n.message.parts,i.task?.id,i.task?.contextId).catch(e=>console.error(`PeerJsChannel: failed to process A2A SendMessage`,e))}_handleAGUIEventNotification(e,t){if(!t||typeof t!=`object`)return;let n=t;window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{remotePeerId:e,event:n}}))}_handleGetAgentCard(e,t){if(!this._localCard){this._sendJsonRpcError(e,t.id,{code:x.INTERNAL_ERROR,message:`Agent card not available`});return}let n=E(t.id,this._localCard),r=this.connections.get(e);r&&r.send(n)}_handleInboundData(e,t){if(t instanceof ArrayBuffer||t instanceof Uint8Array){if(this._pendingInboundFile){let n=this._pendingInboundFile.name,r=new Uint8Array(t),i=this._pendingInboundFile.targetGroupId||`peer:${e}`,a=this._saveInboundFile(i,n,r);this._inboundSavePromises.set(n,a),this._pendingInboundFile=null}return}if(!t||typeof t!=`object`)return;let n=t;if(n.type===`__file_header`){let t=n.id||n.name,r=n.totalChunks||1,i=this._inboundTransfers.get(t),a=typeof n.groupId==`string`&&n.groupId.startsWith(`room:`)?n.groupId:`peer:${e}`;this._inboundTransfers.set(t,{transferId:t,name:n.name,mimeType:n.mimeType||`application/octet-stream`,size:n.size||0,totalChunks:r,receivedChunks:i?.receivedChunks||/* @__PURE__ */ new Map,receivedBytes:i?.receivedBytes||0,targetGroupId:a}),this._pendingInboundFile={name:n.name,mimeType:n.mimeType,size:n.size,targetGroupId:a},P({count:0,total:r,direction:`receive`})}else if(n.type===`__file_chunk`){let t=n.id||n.name,r=this._inboundTransfers.get(t);if(!r){let e=n.totalChunks||1;r={transferId:t,name:n.name,mimeType:`application/octet-stream`,size:0,totalChunks:e,receivedChunks:/* @__PURE__ */ new Map,receivedBytes:0},this._inboundTransfers.set(t,r)}let i=typeof n.index==`number`?n.index:0,a=n.data instanceof ArrayBuffer?new Uint8Array(n.data):n.data instanceof Uint8Array?n.data:new Uint8Array(n.data||[]);if(r.receivedChunks.has(i)||(r.receivedChunks.set(i,a),r.receivedBytes+=a.byteLength),P({count:r.receivedChunks.size,total:r.totalChunks,direction:`receive`}),r.receivedChunks.size>=r.totalChunks){let n=new Uint8Array(r.size||r.receivedBytes),i=0;for(let e=0;e<r.totalChunks;e++){let t=r.receivedChunks.get(e);t&&(n.set(t,i),i+=t.byteLength)}let a=r.targetGroupId||`peer:${e}`,o=this._saveInboundFile(a,r.name,n);this._inboundSavePromises.set(r.name,o),this._inboundTransfers.delete(t),this._pendingInboundFile=null,F(1500)}}else if(n.type===`typing`)this.typingCallback?.(`peer:${e}`,!!n.typing);else if(n.type===`chat`){let t=typeof n.text==`string`?n.text.trim():``;t&&this.messageCallback?.({id:c(),groupId:`peer:${e}`,sender:e,content:t,timestamp:Date.now(),channel:`peerjs`})}else if(n.jsonrpc===`2.0`)this._handleA2AJsonRpc(e,n);else if(n.type===`command:execute`){let t=n.payload||{},r=t.action||``,i=t.args||{},a=t.commandId||``;import(`./init-control-plane-BEbcwmmv.js`).then(({executeClientControlCommand:e})=>e(r,i)).then(t=>{let n=this.connections.get(e);if(n){let e=!!t?.error;n.send({id:c(),type:`command:result`,payload:{commandId:a,action:r,success:!e,data:t,...e?{error:t.error}:{}}})}}).catch(t=>{let n=this.connections.get(e);n&&n.send({id:c(),type:`command:result`,payload:{commandId:a,action:r,success:!1,error:t?.message||String(t)}})})}}_isTrustedPeer(e){if(this.trustedPeerIds.size===0||this.trustedPeerIds.has(e))return!0;for(let t of this.trustedPeerIds){let n=t.trim();if(n.endsWith(`*`)&&e.startsWith(n.slice(0,-1))||n===`cli`&&e.startsWith(`cli-`))return!0}return!1}_handleIncomingConnection(e){let t=e.peer;if(this._isTrustedPeer(t))this._attachChunkProgressTracker(e),this.connections.set(t,e),this._updateConnectedPeersSignal(),e.on(`open`,()=>{console.log(`PeerJsChannel: connection opened with ${t}`),this._exchangeAgentCards(t,e)}),e.on(`data`,e=>{this._handleInboundData(t,e)}),e.on(`close`,()=>{console.log(`PeerJsChannel: connection closed with ${t}`),this.connections.delete(t),this.peerCards.delete(t),this._taskManagers.delete(t),this._updateConnectedPeersSignal()}),e.on(`error`,e=>{console.error(`PeerJsChannel: connection error with ${t}:`,e),this.connections.delete(t),this._updateConnectedPeersSignal(),window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{remotePeerId:t,error:e.message}}))}),e.on(`iceStateChanged`,e=>{(e===`failed`||e===`disconnected`||e===`closed`)&&(console.warn(`PeerJsChannel: ICE state changed to ${e} for ${t}`),this.connections.delete(t),this._updateConnectedPeersSignal())});else{console.warn(`PeerJsChannel: rejecting connection from untrusted peer: ${t}`);try{e.close()}catch{}}}_attachChunkProgressTracker(e){let t=e;if(t._chunkProgressPatched)return;t._chunkProgressPatched=!0;let n=this,r=t._handleChunk;typeof r==`function`&&(t._handleChunk=function(e){if(e&&typeof e==`object`&&`__peerData`in e&&n._inboundTransfers.size===0){let t=e.__peerData,n=this._chunkedData?.[t]?.count??0,r=e.total;if(typeof globalThis.dispatchEvent==`function`&&typeof CustomEvent==`function`)globalThis.dispatchEvent(new CustomEvent(`peerjs-dc-handle-chunk`,{detail:{chunkInfo:{count:n,total:r}}}));else{let e=n+1;P({count:e,total:r,direction:`receive`}),e>=r&&F(1500)}}return r.call(this,e)})}_handleTaskStatusNotification(e,t){if(!t||typeof t!=`object`)return;let n=t;if(n.status?.state&&h.has(n.status.state)){let t=`peer:${e}`;this._onTaskCompleteCallback?.(t)}window.dispatchEvent(new CustomEvent(`shadow-claw-task-status`,{detail:{remotePeerId:e,...n}}))}async _initPeer(){let{Peer:e}=await import(`./bundler-UnYfEehP.js`),t={},n=this.serverConfig.host??`0.peerjs.com`,r=this.serverConfig.port??443,i=this.serverConfig.path??`/`,a=this.serverConfig.secure??!0;t.host=n,t.port=r,t.path=i,t.secure=a,t.debug=3,t.config={iceServers:this.serverConfig.iceServers??[{urls:`stun:stun.l.google.com:19302`},{urls:`stun:stun1.l.google.com:19302`}]},this.peer=new e(this.myPeerId,t),this.peer.on(`open`,e=>{console.log(`PeerJsChannel: connected to signaling server, peer ID: ${e}`),this._reconnectAttempts=0}),this.peer.on(`connection`,e=>{this._handleIncomingConnection(e)}),this.peer.on(`error`,e=>{console.error(`PeerJsChannel: peer error [${e.type}]:`,e.message),(e.type===`peer-unavailable`||e.type===`unavailable-id`)&&window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{error:e.message}})),e.type!==`peer-unavailable`&&e.type!==`network`&&e.type!==`disconnected`&&e.type===`unavailable-id`&&console.warn(`PeerJsChannel: peer ID is already in use. Stop the channel and reconfigure.`)}),this.peer.on(`disconnected`,()=>{this.running&&this._scheduleReconnect()}),this.peer.on(`close`,()=>{console.log(`PeerJsChannel: peer closed`)})}_registerPendingRequest(e,t){let n=String(e??``),r=setTimeout(()=>{this._pendingRequests.delete(n),console.warn(`PeerJsChannel: JSON-RPC request ${n} timed out (10s)`)},1e4);this._pendingRequests.set(n,{resolve:t,timer:r})}_scheduleReconnect(){if(this._reconnectTimer!==null)return;let e=Math.min(n._RECONNECT_BASE_MS*2**this._reconnectAttempts,n._RECONNECT_MAX_MS);this._reconnectAttempts++,console.log(`PeerJsChannel: disconnected from signaling server, reconnecting in ${(e/1e3).toFixed(1)}s (attempt ${this._reconnectAttempts})`),this._reconnectTimer=setTimeout(()=>{if(this._reconnectTimer=null,this.running)try{this.peer?.reconnect?.()}catch{this._scheduleReconnect()}},e)}_sendJsonRpcError(e,t,n){let r=this.connections.get(e);if(!r)return;let i={jsonrpc:`2.0`,id:t,error:n};try{r.send(i)}catch{}}async _waitForBufferDrain(e,t=65536){let n=e.dataChannel||e._dc;n&&typeof n.bufferedAmount==`number`&&(n.bufferedAmount<=t||await new Promise(e=>{let r=setInterval(()=>{(!n||n.bufferedAmount<=t)&&(clearInterval(r),e())},20);if(typeof n.addEventListener==`function`){let i=()=>{clearInterval(r),n.removeEventListener(`bufferedamountlow`,i),e()};try{n.bufferedAmountLowThreshold=t,n.addEventListener(`bufferedamountlow`,i,{once:!0})}catch{}}}))}async _saveInboundFile(t,n,r){try{let a=await e(),o=n,c=1;for(;await s(a,t,o);){let e=n.lastIndexOf(`.`);if(e>0&&e<n.length-1){let t=n.substring(0,e),r=n.substring(e);o=`${t} (${c})${r}`}else o=`${n} (${c})`;c++}o!==n&&this._inboundRemap.set(n,o),await i(a,t,o,r);try{let{orchestratorStore:e}=await import(`./orchestrator-BlvEG3PO.js`).then(e=>e.n);e.activeGroupId===t&&await e.loadFiles(a)}catch{}}catch(e){console.error(`PeerJsChannel: failed to write inbound file bytes`,e)}}_updateConnectedPeersSignal(){this.connectedPeersSignal.set(Array.from(this.connections.keys()))}_waitForOpen(e){return e.open?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>{n(/* @__PURE__ */ Error(`Connection open timeout (5s)`))},5e3);e.on(`open`,()=>{clearTimeout(r),t()}),e.on(`error`,e=>{clearTimeout(r),n(e)})})}async _processInboundA2AEnvelope(e,t,n,r){let i=`peer:${e}`,a=``,o=[],s=[],l;for(let e of t)if(e.kind===`text`&&typeof e.text==`string`)a+=e.text;else if(e.kind===`file`){let t=e.name||`attachment`,n=this._inboundSavePromises.get(t);if(n)try{await n}catch{}finally{this._inboundSavePromises.delete(t)}if(this._inboundRemap.has(t)){let e=this._inboundRemap.get(t),n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);a=a.replace(RegExp(`(!?\\[.*?\\])\\(${n}\\)`,`g`),`$1(${e})`),this._inboundRemap.delete(t),t=e}let r=t.split(`/`).pop()||`attachment`;o.push({fileName:r,mimeType:e.mimeType,path:t,size:e.size||0})}else e.kind===`a2ui`&&e.envelope?s.push(e.envelope):e.kind===`a2ui-action`&&e.action&&(l=e.action);a=a.trim(),(a||o.length!==0||s.length!==0||l)&&this.messageCallback?.({id:c(),groupId:i,sender:e,content:a,timestamp:Date.now(),channel:`peerjs`,attachments:o.length>0?o:void 0,a2uiEnvelopes:s.length>0?s:void 0,a2uiAction:l,taskId:n,contextId:r})}};function R(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r,i=e;for(;(r=n.exec(e))!==null;){let e=r[1],n=z((r[2]||``).trim());n&&t.push({alt:e,path:n})}return{remainingText:i,attachments:t}}function z(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}export{u as a,f as i,M as n,b as r,L as t};
|
|
1
|
+
import"./config-y_2Fg77m.js";import{n as e}from"./db-BUuJo1Gf.js";import{t}from"./dist-CeFyqf9k.js";import{$t as n,gn as r,tn as i,un as a,xn as o}from"./orchestrator-OoUK7CF9.js";import{i as s}from"./tools-CwQq5tJH.js";import{t as c}from"./ulid-BSJxYh6W.js";function l(e){return n(e,{replacement:`-`,fallback:`attachment`,stripLeadingDots:!0,collapseReplacement:!0,stripControlChars:!0})}function u(e){return e.previewDisposition===`inline`||o(e.fileName,e.mimeType||``)===`image/png`}function d(e,t=``,n=Date.now()){let r=l(e),i=t.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``);return`attachments/${n}-${i?`${i}-`:``}${r}`}async function f(e,t,n=[]){let r=[];for(let i of n){let n=l(i.fileName||``),s=i.path||d(n,i.id),c=i.source,u=o(n,i.mimeType||``),f=i.size;if(c){let r=await p(c);u=o(n,i.mimeType||r.type),f=typeof f==`number`?f:r.size,await a(e,t,s,r)}r.push(m({...i,fileName:n,mimeType:u,size:f,path:s,previewDisposition:i.previewDisposition||(u===`image/png`?`inline`:`file`)}))}return r}async function p(e){if(e.kind===`local-file`)return e.file;if(e.kind===`inline-text`)return new Blob([e.text],{type:e.mimeType||`text/plain`});let t=await fetch(e.url,{headers:e.headers});if(!t.ok)throw Error(`Attachment download failed: HTTP ${t.status} ${t.statusText}`);return await t.blob()}function m(e){let{source:t,...n}=e;return n}const h=/* @__PURE__ */ new Set([`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_REJECTED`]),g=/* @__PURE__ */ new Set([`TASK_STATE_INPUT_REQUIRED`,`TASK_STATE_AUTH_REQUIRED`]),_={SEND_MESSAGE:`SendMessage`,SEND_STREAMING_MESSAGE:`SendStreamingMessage`,GET_TASK:`GetTask`,CANCEL_TASK:`CancelTask`,GET_AGENT_CARD:`GetAgentCard`},v={EVENT:`agui/event`},y={STATUS_UPDATE:`tasks/statusUpdate`,ARTIFACT_UPDATE:`tasks/artifactUpdate`},b={JOIN:`room/join`,ROSTER:`room/roster`,LEAVE:`room/leave`,MESSAGE:`room/message`,INVITE:`room/invite`,RELAY:`room/relay`,A2UI:`room/a2ui`,A2UI_ACTION:`room/a2ui-action`},x={TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603};function S(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`&&(e.id===null||typeof e.id==`string`||typeof e.id==`number`)&&typeof e.method==`string`}function C(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`&&(e.id===null||typeof e.id==`string`||typeof e.id==`number`)&&!(`method`in e)}function w(e){let t={url:`webrtc://${e.peerId}`,protocolBinding:`https://xt-ml.github.io/shadow-claw/bindings/webrtc-datachannel/v1`,protocolVersion:`1.0`},n={streaming:e.streaming??!0,pushNotifications:!1};return{name:e.name,description:e.description??`AI assistant agent (${e.name})`,version:e.version??`1.0.0`,supportedInterfaces:[t],capabilities:n,defaultInputModes:[`text/plain`,`application/json`],defaultOutputModes:[`text/plain`,`application/json`],skills:e.skills??[],iconUrl:e.iconUrl}}function T(){return{jsonrpc:`2.0`,id:c(),method:_.GET_AGENT_CARD}}function E(e,t){return{jsonrpc:`2.0`,id:e,result:t}}function D(e){if(e.error)return console.warn(`GetAgentCard returned error:`,e.error),null;let t=e.result;return!t||typeof t!=`object`||typeof t.name!=`string`||typeof t.version!=`string`?null:t}var O=class{_cards=/* @__PURE__ */ new Map;clear(){this._cards.clear()}delete(e){this._cards.delete(e)}entries(){return this._cards.entries()}get(e){return this._cards.get(e)}getDisplayName(e){return this._cards.get(e)?.name??e}has(e){return this._cards.has(e)}set(e,t){this._cards.set(e,t)}supportsStreaming(e){return this._cards.get(e)?.capabilities?.streaming??!1}};const k={maxTasks:100,maxHistoryPerTask:50},A=/* @__PURE__ */ new Map([[`TASK_STATE_SUBMITTED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_REJECTED`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])],[`TASK_STATE_WORKING`,/* @__PURE__ */ new Set([`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_INPUT_REQUIRED`,`TASK_STATE_AUTH_REQUIRED`])],[`TASK_STATE_INPUT_REQUIRED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])],[`TASK_STATE_AUTH_REQUIRED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])]]);var j=class{_config;_contextActiveTask=/* @__PURE__ */ new Map;_listeners=/* @__PURE__ */ new Set;_taskOrder=[];_tasks=/* @__PURE__ */ new Map;constructor(e){this._config={...k,...e}}addArtifact(e,t,n=!1){let r=this._tasks.get(e);if(!r)return;if(r.artifacts||=[],n){let e=r.artifacts.find(e=>e.artifactId===t.artifactId);e?e.parts.push(...t.parts):r.artifacts.push(t)}else r.artifacts.push(t);let i={taskId:r.id,contextId:r.contextId??``,artifact:t,append:n,lastChunk:!1};this._emit({type:`artifactUpdate`,taskId:r.id,contextId:r.contextId??``,payload:i})}cancelTask(e){let t=this._tasks.get(e);return!t||h.has(t.status.state)?!1:(this._transitionState(t,`TASK_STATE_CANCELED`,{messageId:c(),role:`ROLE_AGENT`,parts:[{text:`Task canceled by peer request.`}]}),!0)}clear(){this._tasks.clear(),this._taskOrder=[],this._contextActiveTask.clear()}emitRunError(e,t,n){let r=this._tasks.get(e);if(!r)return;let i={type:`RUN_ERROR`,message:t,code:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitRunFinished(e){let t=this._tasks.get(e);if(!t)return;let n={type:`RUN_FINISHED`,threadId:t.contextId??t.id,runId:t.id,timestamp:Date.now()};this._emitAGUI(t,n)}emitRunStarted(e){let t=this._tasks.get(e);if(!t)return;let n={type:`RUN_STARTED`,threadId:t.contextId??t.id,runId:t.id,timestamp:Date.now()};this._emitAGUI(t,n)}emitStateSnapshot(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`STATE_SNAPSHOT`,snapshot:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitTextMessageContent(e,t,n){let r=this._tasks.get(e);if(!r)return;let i={type:`TEXT_MESSAGE_CONTENT`,messageId:t,delta:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitTextMessageEnd(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`TEXT_MESSAGE_END`,messageId:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitTextMessageStart(e,t,n=`assistant`){let r=this._tasks.get(e);if(!r)return;let i={type:`TEXT_MESSAGE_START`,messageId:t,role:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitToolCallEnd(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitToolCallStart(e,t,n,r){let i=this._tasks.get(e);if(!i)return;let a={type:`TOOL_CALL_START`,toolCallId:t,toolCallName:n,parentMessageId:r,timestamp:Date.now()};this._emitAGUI(i,a)}getActiveTaskForContext(e){let t=this._contextActiveTask.get(e);if(t)return this._tasks.get(t)}getActiveTasks(){return Array.from(this._tasks.values()).filter(e=>!h.has(e.status.state))}getAllTasks(){return Array.from(this._tasks.values())}getTask(e){return this._tasks.get(e)}handleSendMessage(e){let t=e.message,n=t.contextId??c(),r=t.taskId??this._contextActiveTask.get(n);return r&&this._tasks.has(r)?this._continueTask(r,t):this._createTask(n,t)}markCompleted(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_COMPLETED`,t)}markFailed(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_FAILED`,{messageId:c(),role:`ROLE_AGENT`,parts:[{text:t}]})}markInputRequired(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_INPUT_REQUIRED`,t)}markWorking(e){let t=this._tasks.get(e);t&&this._transitionState(t,`TASK_STATE_WORKING`)}off(e){this._listeners.delete(e)}on(e){this._listeners.add(e)}_addTask(e){for(this._tasks.set(e.id,e),this._taskOrder.push(e.id);this._taskOrder.length>this._config.maxTasks;){let e=this._taskOrder.shift(),t=this._tasks.get(e);if(t&&h.has(t.status.state))this._tasks.delete(e),t.contextId&&this._contextActiveTask.delete(t.contextId);else{this._taskOrder.unshift(e);break}}}_continueTask(e,t){let n=this._tasks.get(e);return g.has(n.status.state)&&this._transitionState(n,`TASK_STATE_WORKING`),n.history||=[],n.history.push(t),n.history.length>this._config.maxHistoryPerTask&&(n.history=n.history.slice(-this._config.maxHistoryPerTask)),this._touchTask(e),{task:n}}_createTask(e,t){let n=c(),r={id:n,contextId:e,status:{state:`TASK_STATE_SUBMITTED`,timestamp:(/* @__PURE__ */ new Date()).toISOString()},history:[t]};return this._addTask(r),this._contextActiveTask.set(e,n),this._emitStatusUpdate(r),{task:r}}_emit(e){for(let t of this._listeners)try{t(e)}catch(e){console.error(`PeerTaskManager: listener error`,e)}}_emitAGUI(e,t){this._emit({type:`aguiEvent`,taskId:e.id,contextId:e.contextId??``,payload:t})}_emitStatusUpdate(e){let t={taskId:e.id,contextId:e.contextId??``,status:e.status};this._emit({type:`statusUpdate`,taskId:e.id,contextId:e.contextId??``,payload:t})}_touchTask(e){let t=this._taskOrder.indexOf(e);t!==-1&&(this._taskOrder.splice(t,1),this._taskOrder.push(e))}_transitionState(e,t,n){let r=e.status.state,i=A.get(r);i&&!i.has(t)?console.warn(`PeerTaskManager: invalid transition ${r} → ${t} for task ${e.id}`):h.has(r)?console.warn(`PeerTaskManager: task ${e.id} is in terminal state ${r}, cannot transition`):(e.status={state:t,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString()},h.has(t)&&e.contextId&&this._contextActiveTask.get(e.contextId)===e.id&&this._contextActiveTask.delete(e.contextId),this._emitStatusUpdate(e))}};const M=new t.State(null);let N=null;function P(e){N!==null&&(clearTimeout(N),N=null),M.set(e)}function F(e=1500){N!==null&&clearTimeout(N),N=setTimeout(()=>{M.set(null),N=null},e)}const I=15360;var L=class n{static _RECONNECT_BASE_MS=1e3;static _RECONNECT_MAX_MS=6e4;connectedPeersSignal=new t.State([]);connections=/* @__PURE__ */ new Map;messageCallback=null;myPeerId=``;peerCards=new O;running=!1;serverConfig={};transferProgressSignal=M;trustedPeerIds=/* @__PURE__ */ new Set;type=`peerjs`;typingCallback=null;_inboundRemap=/* @__PURE__ */ new Map;_localCard=null;_onTaskCompleteCallback=null;peer=null;_inboundSavePromises=/* @__PURE__ */ new Map;_pendingInboundFile=null;_pendingRequests=/* @__PURE__ */ new Map;_reconnectAttempts=0;_reconnectTimer=null;_roomNotificationHandler=null;_taskManagers=/* @__PURE__ */ new Map;_inboundTransfers=/* @__PURE__ */ new Map;constructor(){typeof globalThis.addEventListener==`function`&&globalThis.addEventListener(`peerjs-dc-handle-chunk`,e=>{if(e?.detail?.chunkInfo){if(this._inboundTransfers.size>0)return;let{count:t,total:n}=e.detail.chunkInfo,r=t+1;P({count:r,total:n,direction:`receive`}),r>=n&&F(1500)}})}completeActiveTask(e){let t=e.replace(/^peer:/,``),n=this._taskManagers.get(t);if(!n)return!1;let r=n.getActiveTasks();if(r.length===0)return!1;let i=r[r.length-1];return n.markWorking(i.id),n.markCompleted(i.id),!0}configure(e,t,n={}){this.myPeerId=e.trim(),this.trustedPeerIds=new Set(t.map(e=>e.trim()).filter(Boolean)),this.serverConfig=n}connectPeer(e){this._getOrOpenConnection(e)}getTaskManager(e){let t=this._taskManagers.get(e);return t||(t=new j,this._taskManagers.set(e,t),t.on(t=>{this._forwardTaskEvent(e,t)})),t}isConfigured(){return this.myPeerId.length>0}isPeerConnected(e){let t=this.connections.get(e);return!!t&&!!t.open}onMessage(e){this.messageCallback=e}onTaskComplete(e){this._onTaskCompleteCallback=e}onTyping(e){this.typingCallback=e}sendRoomNotification(e,t){let n=this._getOrOpenConnection(e);if(!n)return!1;if(n.open)try{return n.send(t),!0}catch(t){return console.error(`PeerJsChannel: failed to send room notification to ${e}:`,t),!1}return this._waitForOpen(n).then(()=>{try{n.send(t)}catch(t){console.error(`PeerJsChannel: failed to flush room notification to ${e}:`,t)}}).catch(()=>{}),!0}setRoomNotificationHandler(e){this._roomNotificationHandler=e}async sendAttachmentsToRoom(t,n,i){let a=this.myPeerId,o=(i||[]).filter(e=>!!e.path);if(o.length!==0)try{let i=await e();for(let e of o){let o;try{o=await r(i,n,e.path)}catch(t){console.warn(`PeerJsChannel: failed to read file ${e.path} for room:`,t);continue}let s=e.path,l=e.mimeType||`application/octet-stream`,u=Math.max(1,Math.ceil(o.length/I));for(let r of t.members){if(r.peerId===a)continue;let t=this._getOrOpenConnection(r.peerId);if(t)try{await this._waitForOpen(t);let e=c();t.send({type:`__file_header`,id:e,name:s,mimeType:l,size:o.length,totalChunks:u,chunkSize:I,groupId:n});for(let n=0;n<u;n++){let r=n*I,i=Math.min(r+I,o.length),a=o.subarray(r,i),c=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);t.send({type:`__file_chunk`,id:e,name:s,index:n,totalChunks:u,data:c}),P({count:n+1,total:u,direction:`send`}),await this._waitForBufferDrain(t)}F(1500)}catch(t){console.warn(`PeerJsChannel: failed to stream file ${e.path} to room member ${r.peerId}:`,t)}}}}catch(e){console.error(`PeerJsChannel: failed to access DB for room file transfer`,e)}}setTyping(e,t){let n=e.replace(/^peer:/,``),r=this.connections.get(n);if(r)try{r.send({type:`typing`,typing:t})}catch{}}start(){this.isConfigured()&&!this.running&&(this.running=!0,this._localCard=w({peerId:this.myPeerId,name:this.myPeerId,description:`ShadowClaw AI assistant`,streaming:!0}),this._initPeer())}ensureConnected(e=!1){if(!this.running||!this.isConfigured())return;this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0;let t=this.peer;if(!t||t.destroyed||e&&!t.open){if(t&&!t.destroyed)try{t.destroy()}catch{}this.peer=null,this._initPeer()}else if(t.disconnected)try{t.reconnect?.()}catch{this._initPeer()}}stop(){if(this.running=!1,this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this.connections.forEach(e=>{try{e.close()}catch{}}),this.connections.clear(),this.peerCards.clear(),this._taskManagers.clear(),this._pendingRequests.forEach(({timer:e})=>clearTimeout(e)),this._pendingRequests.clear(),this._updateConnectedPeersSignal(),this.peer){try{this.peer.destroy()}catch{}this.peer=null}}async send(t,n,i){let a=t.replace(/^peer:/,``),o=this._getOrOpenConnection(a);if(!o)console.warn(`PeerJsChannel: no connection available for ${a}`);else try{await this._waitForOpen(o);let{attachments:a}=R(n),s=[...(i||[]).filter(e=>!!e.path),...a.map(e=>({path:e.path,mimeType:`application/octet-stream`}))],l=/* @__PURE__ */ new Map,u=[];try{let n=await e();for(let e of s)if(e.path)try{let i=await r(n,t,e.path),a=e.path;l.has(e.path)||l.set(e.path,a);let s=e.mimeType||`application/octet-stream`,d=c(),f=Math.max(1,Math.ceil(i.length/I));o.send({type:`__file_header`,id:d,name:a,mimeType:s,size:i.length,totalChunks:f,chunkSize:I,groupId:t});for(let e=0;e<f;e++){let t=e*I,n=Math.min(t+I,i.length),r=i.subarray(t,n),s=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);o.send({type:`__file_chunk`,id:d,name:a,index:e,totalChunks:f,data:s}),P({count:e+1,total:f,direction:`send`}),await this._waitForBufferDrain(o)}F(1500),u.push({kind:`file`,name:a,mimeType:s,size:i.length})}catch(t){console.warn(`PeerJsChannel: failed to process file ${e.path}:`,t)}}catch(e){console.error(`PeerJsChannel: failed to access DB`,e)}let d=n;for(let[e,t]of l){let n=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);d=d.replace(RegExp(`(!?\\[.*?\\])\\(${n}\\)`,`g`),`$1(${t})`)}let f=[...u,{kind:`text`,text:d}],p=c(),m={jsonrpc:`2.0`,id:p,method:_.SEND_MESSAGE,params:{message:{messageId:c(),role:`ROLE_AGENT`,parts:f}}};o.send(m),this._registerPendingRequest(p,e=>{})}catch(e){console.error(`PeerJsChannel: send failed for ${a}:`,e),window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{remotePeerId:a,error:e instanceof Error?e.message:String(e)}}))}}async sendA2UI(e,t){let n=e.replace(/^peer:/,``),r=this._getOrOpenConnection(n);if(!r)console.warn(`PeerJsChannel.sendA2UI: no connection available for ${n}`);else try{await this._waitForOpen(r);let e={jsonrpc:`2.0`,method:`message/send`,id:c(),params:{message:{role:`agent`,parts:[{kind:`a2ui`,envelope:t}]}}};r.send(e)}catch(e){console.error(`PeerJsChannel.sendA2UI: failed for ${n}:`,e)}}async sendA2UIAction(e,t){let n=e.replace(/^peer:/,``),r=this._getOrOpenConnection(n);if(!r)console.warn(`PeerJsChannel.sendA2UIAction: no connection available for ${n}`);else try{await this._waitForOpen(r);let e={jsonrpc:`2.0`,method:`message/send`,id:c(),params:{message:{role:`user`,parts:[{kind:`a2ui-action`,action:t}]}}};r.send(e)}catch(e){console.error(`PeerJsChannel.sendA2UIAction: failed for ${n}:`,e)}}_exchangeAgentCards(e,t){if(!this._localCard)return;let n=T();t.send(n),this._registerPendingRequest(n.id,t=>{let n=D(t);n&&(this.peerCards.set(e,n),console.log(`PeerJsChannel: received AgentCard from ${e}: "${n.name}"`))})}_forwardTaskEvent(e,t){let n=this.connections.get(e);if(!n)return;let r;switch(t.type){case`statusUpdate`:r=y.STATUS_UPDATE;break;case`artifactUpdate`:r=y.ARTIFACT_UPDATE;break;case`aguiEvent`:r=v.EVENT;break;default:return}let i={jsonrpc:`2.0`,method:r,params:t.payload};try{n.send(i)}catch(n){console.error(`PeerJsChannel: failed to forward ${t.type} to ${e}:`,n)}}_getOrOpenConnection(e){let t=this.connections.get(e);if(t)return t;if(!this.peer)return null;try{let t=this.peer.connect(e,{reliable:!0,serialization:`binary`});return t?(this._handleIncomingConnection(t),t):null}catch(t){return console.error(`PeerJsChannel: failed to connect to ${e}:`,t),null}}_handleA2ACancelTask(e,t){let n=t.params;if(!n?.taskId){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing taskId in CancelTask params`});return}let r=this._taskManagers.get(e);if(!r){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_FOUND,message:`Task not found: ${n.taskId}`});return}if(!r.cancelTask(n.taskId)){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_CANCELABLE,message:`Task not cancelable: ${n.taskId}`});return}let i=this.connections.get(e);if(i){let e=r.getTask(n.taskId),a={jsonrpc:`2.0`,id:t.id,result:{task:e}};i.send(a)}}_handleA2AGetTask(e,t){let n=t.params;if(!n?.taskId){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing taskId in GetTask params`});return}let r=this._taskManagers.get(e)?.getTask(n.taskId);if(!r){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_FOUND,message:`Task not found: ${n.taskId}`});return}let i=this.connections.get(e);if(i){let e={jsonrpc:`2.0`,id:t.id,result:{task:r}};i.send(e)}}_handleA2AJsonRpc(e,t){if(C(t)){let e=String(t.id??``),n=this._pendingRequests.get(e);n&&(clearTimeout(n.timer),this._pendingRequests.delete(e),n.resolve(t));return}let n=t.method;if(n){if(n.startsWith(`room/`))this._roomNotificationHandler?.(e,n,t.params);else if(S(t)){let r={[_.GET_AGENT_CARD]:(e,t)=>this._handleGetAgentCard(e,t),[_.SEND_MESSAGE]:(e,t)=>this._handleA2ASendMessage(e,t),[_.CANCEL_TASK]:(e,t)=>this._handleA2ACancelTask(e,t),[_.GET_TASK]:(e,t)=>this._handleA2AGetTask(e,t)}[n];if(r){r(e,t);return}if(n===`message/send`){let n=t.params;n?.message?.parts&&Array.isArray(n.message.parts)&&this._processInboundA2AEnvelope(e,n.message.parts).catch(e=>console.error(`PeerJsChannel: failed to process inbound A2A envelope`,e))}else this._sendJsonRpcError(e,t.id,{code:x.METHOD_NOT_FOUND,message:`Method not found: ${n}`})}else({[v.EVENT]:(e,t)=>this._handleAGUIEventNotification(e,t),[y.STATUS_UPDATE]:(e,t)=>this._handleTaskStatusNotification(e,t),[y.ARTIFACT_UPDATE]:()=>{},"message/send":(e,t)=>{t?.message?.parts&&Array.isArray(t.message.parts)&&this._processInboundA2AEnvelope(e,t.message.parts).catch(e=>console.error(`PeerJsChannel: failed to process inbound A2A envelope`,e))}})[n]?.(e,t.params)}}_handleA2ASendMessage(e,t){let n=t.params;if(!n?.message){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing message in SendMessage params`});return}let r=this._taskManagers.get(e);r||(r=new j,this._taskManagers.set(e,r),r.on(t=>{this._forwardTaskEvent(e,t)}));let i=r.handleSendMessage(n),a=this.connections.get(e);if(a){let e={jsonrpc:`2.0`,id:t.id,result:i};a.send(e)}n.message.parts&&Array.isArray(n.message.parts)&&this._processInboundA2AEnvelope(e,n.message.parts,i.task?.id,i.task?.contextId).catch(e=>console.error(`PeerJsChannel: failed to process A2A SendMessage`,e))}_handleAGUIEventNotification(e,t){if(!t||typeof t!=`object`)return;let n=t;window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{remotePeerId:e,event:n}}))}_handleGetAgentCard(e,t){if(!this._localCard){this._sendJsonRpcError(e,t.id,{code:x.INTERNAL_ERROR,message:`Agent card not available`});return}let n=E(t.id,this._localCard),r=this.connections.get(e);r&&r.send(n)}_handleInboundData(e,t){if(t instanceof ArrayBuffer||t instanceof Uint8Array){if(this._pendingInboundFile){let n=this._pendingInboundFile.name,r=new Uint8Array(t),i=this._pendingInboundFile.targetGroupId||`peer:${e}`,a=this._saveInboundFile(i,n,r);this._inboundSavePromises.set(n,a),this._pendingInboundFile=null}return}if(!t||typeof t!=`object`)return;let n=t;if(n.type===`__file_header`){let t=n.id||n.name,r=n.totalChunks||1,i=this._inboundTransfers.get(t),a=typeof n.groupId==`string`&&n.groupId.startsWith(`room:`)?n.groupId:`peer:${e}`;this._inboundTransfers.set(t,{transferId:t,name:n.name,mimeType:n.mimeType||`application/octet-stream`,size:n.size||0,totalChunks:r,receivedChunks:i?.receivedChunks||/* @__PURE__ */ new Map,receivedBytes:i?.receivedBytes||0,targetGroupId:a}),this._pendingInboundFile={name:n.name,mimeType:n.mimeType,size:n.size,targetGroupId:a},P({count:0,total:r,direction:`receive`})}else if(n.type===`__file_chunk`){let t=n.id||n.name,r=this._inboundTransfers.get(t);if(!r){let e=n.totalChunks||1;r={transferId:t,name:n.name,mimeType:`application/octet-stream`,size:0,totalChunks:e,receivedChunks:/* @__PURE__ */ new Map,receivedBytes:0},this._inboundTransfers.set(t,r)}let i=typeof n.index==`number`?n.index:0,a=n.data instanceof ArrayBuffer?new Uint8Array(n.data):n.data instanceof Uint8Array?n.data:new Uint8Array(n.data||[]);if(r.receivedChunks.has(i)||(r.receivedChunks.set(i,a),r.receivedBytes+=a.byteLength),P({count:r.receivedChunks.size,total:r.totalChunks,direction:`receive`}),r.receivedChunks.size>=r.totalChunks){let n=new Uint8Array(r.size||r.receivedBytes),i=0;for(let e=0;e<r.totalChunks;e++){let t=r.receivedChunks.get(e);t&&(n.set(t,i),i+=t.byteLength)}let a=r.targetGroupId||`peer:${e}`,o=this._saveInboundFile(a,r.name,n);this._inboundSavePromises.set(r.name,o),this._inboundTransfers.delete(t),this._pendingInboundFile=null,F(1500)}}else if(n.type===`typing`)this.typingCallback?.(`peer:${e}`,!!n.typing);else if(n.type===`chat`){let t=typeof n.text==`string`?n.text.trim():``;t&&this.messageCallback?.({id:c(),groupId:`peer:${e}`,sender:e,content:t,timestamp:Date.now(),channel:`peerjs`})}else if(n.jsonrpc===`2.0`)this._handleA2AJsonRpc(e,n);else if(n.type===`command:execute`){let t=n.payload||{},r=t.action||``,i=t.args||{},a=t.commandId||``;import(`./init-control-plane-DGOY_RNS.js`).then(({executeClientControlCommand:e})=>e(r,i)).then(t=>{let n=this.connections.get(e);if(n){let e=!!t?.error;n.send({id:c(),type:`command:result`,payload:{commandId:a,action:r,success:!e,data:t,...e?{error:t.error}:{}}})}}).catch(t=>{let n=this.connections.get(e);n&&n.send({id:c(),type:`command:result`,payload:{commandId:a,action:r,success:!1,error:t?.message||String(t)}})})}}_isTrustedPeer(e){if(this.trustedPeerIds.size===0||this.trustedPeerIds.has(e))return!0;for(let t of this.trustedPeerIds){let n=t.trim();if(n.endsWith(`*`)&&e.startsWith(n.slice(0,-1))||n===`cli`&&e.startsWith(`cli-`))return!0}return!1}_handleIncomingConnection(e){let t=e.peer;if(this._isTrustedPeer(t))this._attachChunkProgressTracker(e),this.connections.set(t,e),this._updateConnectedPeersSignal(),e.on(`open`,()=>{console.log(`PeerJsChannel: connection opened with ${t}`),this._exchangeAgentCards(t,e)}),e.on(`data`,e=>{this._handleInboundData(t,e)}),e.on(`close`,()=>{console.log(`PeerJsChannel: connection closed with ${t}`),this.connections.delete(t),this.peerCards.delete(t),this._taskManagers.delete(t),this._updateConnectedPeersSignal()}),e.on(`error`,e=>{console.error(`PeerJsChannel: connection error with ${t}:`,e),this.connections.delete(t),this._updateConnectedPeersSignal(),window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{remotePeerId:t,error:e.message}}))}),e.on(`iceStateChanged`,e=>{(e===`failed`||e===`disconnected`||e===`closed`)&&(console.warn(`PeerJsChannel: ICE state changed to ${e} for ${t}`),this.connections.delete(t),this._updateConnectedPeersSignal())});else{console.warn(`PeerJsChannel: rejecting connection from untrusted peer: ${t}`);try{e.close()}catch{}}}_attachChunkProgressTracker(e){let t=e;if(t._chunkProgressPatched)return;t._chunkProgressPatched=!0;let n=this,r=t._handleChunk;typeof r==`function`&&(t._handleChunk=function(e){if(e&&typeof e==`object`&&`__peerData`in e&&n._inboundTransfers.size===0){let t=e.__peerData,n=this._chunkedData?.[t]?.count??0,r=e.total;if(typeof globalThis.dispatchEvent==`function`&&typeof CustomEvent==`function`)globalThis.dispatchEvent(new CustomEvent(`peerjs-dc-handle-chunk`,{detail:{chunkInfo:{count:n,total:r}}}));else{let e=n+1;P({count:e,total:r,direction:`receive`}),e>=r&&F(1500)}}return r.call(this,e)})}_handleTaskStatusNotification(e,t){if(!t||typeof t!=`object`)return;let n=t;if(n.status?.state&&h.has(n.status.state)){let t=`peer:${e}`;this._onTaskCompleteCallback?.(t)}window.dispatchEvent(new CustomEvent(`shadow-claw-task-status`,{detail:{remotePeerId:e,...n}}))}async _initPeer(){let{Peer:e}=await import(`./bundler-UnYfEehP.js`),t={},n=this.serverConfig.host??`0.peerjs.com`,r=this.serverConfig.port??443,i=this.serverConfig.path??`/`,a=this.serverConfig.secure??!0;t.host=n,t.port=r,t.path=i,t.secure=a,t.debug=3,t.config={iceServers:this.serverConfig.iceServers??[{urls:`stun:stun.l.google.com:19302`},{urls:`stun:stun1.l.google.com:19302`}]},this.peer=new e(this.myPeerId,t),this.peer.on(`open`,e=>{console.log(`PeerJsChannel: connected to signaling server, peer ID: ${e}`),this._reconnectAttempts=0}),this.peer.on(`connection`,e=>{this._handleIncomingConnection(e)}),this.peer.on(`error`,e=>{console.error(`PeerJsChannel: peer error [${e.type}]:`,e.message),(e.type===`peer-unavailable`||e.type===`unavailable-id`)&&window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{error:e.message}})),e.type!==`peer-unavailable`&&e.type!==`network`&&e.type!==`disconnected`&&e.type===`unavailable-id`&&console.warn(`PeerJsChannel: peer ID is already in use. Stop the channel and reconfigure.`)}),this.peer.on(`disconnected`,()=>{this.running&&this._scheduleReconnect()}),this.peer.on(`close`,()=>{console.log(`PeerJsChannel: peer closed`)})}_registerPendingRequest(e,t){let n=String(e??``),r=setTimeout(()=>{this._pendingRequests.delete(n),console.warn(`PeerJsChannel: JSON-RPC request ${n} timed out (10s)`)},1e4);this._pendingRequests.set(n,{resolve:t,timer:r})}_scheduleReconnect(){if(this._reconnectTimer!==null)return;let e=Math.min(n._RECONNECT_BASE_MS*2**this._reconnectAttempts,n._RECONNECT_MAX_MS);this._reconnectAttempts++,console.log(`PeerJsChannel: disconnected from signaling server, reconnecting in ${(e/1e3).toFixed(1)}s (attempt ${this._reconnectAttempts})`),this._reconnectTimer=setTimeout(()=>{if(this._reconnectTimer=null,this.running)try{this.peer?.reconnect?.()}catch{this._scheduleReconnect()}},e)}_sendJsonRpcError(e,t,n){let r=this.connections.get(e);if(!r)return;let i={jsonrpc:`2.0`,id:t,error:n};try{r.send(i)}catch{}}async _waitForBufferDrain(e,t=65536){let n=e.dataChannel||e._dc;n&&typeof n.bufferedAmount==`number`&&(n.bufferedAmount<=t||await new Promise(e=>{let r=setInterval(()=>{(!n||n.bufferedAmount<=t)&&(clearInterval(r),e())},20);if(typeof n.addEventListener==`function`){let i=()=>{clearInterval(r),n.removeEventListener(`bufferedamountlow`,i),e()};try{n.bufferedAmountLowThreshold=t,n.addEventListener(`bufferedamountlow`,i,{once:!0})}catch{}}}))}async _saveInboundFile(t,n,r){try{let a=await e(),o=n,c=1;for(;await s(a,t,o);){let e=n.lastIndexOf(`.`);if(e>0&&e<n.length-1){let t=n.substring(0,e),r=n.substring(e);o=`${t} (${c})${r}`}else o=`${n} (${c})`;c++}o!==n&&this._inboundRemap.set(n,o),await i(a,t,o,r);try{let{orchestratorStore:e}=await import(`./orchestrator-OoUK7CF9.js`).then(e=>e.n);e.activeGroupId===t&&await e.loadFiles(a)}catch{}}catch(e){console.error(`PeerJsChannel: failed to write inbound file bytes`,e)}}_updateConnectedPeersSignal(){this.connectedPeersSignal.set(Array.from(this.connections.keys()))}_waitForOpen(e){return e.open?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>{n(/* @__PURE__ */ Error(`Connection open timeout (5s)`))},5e3);e.on(`open`,()=>{clearTimeout(r),t()}),e.on(`error`,e=>{clearTimeout(r),n(e)})})}async _processInboundA2AEnvelope(e,t,n,r){let i=`peer:${e}`,a=``,o=[],s=[],l;for(let e of t)if(e.kind===`text`&&typeof e.text==`string`)a+=e.text;else if(e.kind===`file`){let t=e.name||`attachment`,n=this._inboundSavePromises.get(t);if(n)try{await n}catch{}finally{this._inboundSavePromises.delete(t)}if(this._inboundRemap.has(t)){let e=this._inboundRemap.get(t),n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);a=a.replace(RegExp(`(!?\\[.*?\\])\\(${n}\\)`,`g`),`$1(${e})`),this._inboundRemap.delete(t),t=e}let r=t.split(`/`).pop()||`attachment`;o.push({fileName:r,mimeType:e.mimeType,path:t,size:e.size||0})}else e.kind===`a2ui`&&e.envelope?s.push(e.envelope):e.kind===`a2ui-action`&&e.action&&(l=e.action);a=a.trim(),(a||o.length!==0||s.length!==0||l)&&this.messageCallback?.({id:c(),groupId:i,sender:e,content:a,timestamp:Date.now(),channel:`peerjs`,attachments:o.length>0?o:void 0,a2uiEnvelopes:s.length>0?s:void 0,a2uiAction:l,taskId:n,contextId:r})}};function R(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r,i=e;for(;(r=n.exec(e))!==null;){let e=r[1],n=z((r[2]||``).trim());n&&t.push({alt:e,path:n})}return{remainingText:i,attachments:t}}function z(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}export{u as a,f as i,M as n,b as r,L as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./config-y_2Fg77m.js";import{n as t}from"./db-BUuJo1Gf.js";import{t as n}from"./get-config-Bkvl__ZS.js";import{t as r}from"./set-config-DSiuMe0k.js";function i(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`sub-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function a(t){if(!t)return i();let a=await n(t,e.SUBSCRIBER_ID);if(typeof a==`string`&&a.trim().length>0)return a;let o=i();return await r(t,e.SUBSCRIBER_ID,o),o}async function o(r){let i=await t(),a=await n(i,e.PUSH_PROXY_URL);if(!a&&typeof localStorage<`u`)try{a=localStorage.getItem(e.PUSH_PROXY_URL)||void 0}catch{}if(!a)return r;let o=r.startsWith(`/`)?r:`/${r}`;return`${a.endsWith(`/`)?a.slice(0,-1):a}${o}`}function s(e,t={}){let n={...t};try{let t=typeof location<`u`?location.origin:`http://127.0.0.1:8888`,r=new URL(e,t).hostname.toLowerCase();r===`localhost`||r===`127.0.0.1`||r===`::1`||r===`[::1]`?n.targetAddressSpace=`loopback`:(/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(r)||!r.includes(`.`)||r.endsWith(`.local`)||r.endsWith(`.lan`)||r.endsWith(`.home`)||r.endsWith(`.internal`))&&(n.targetAddressSpace=`private`)}catch{}return n}function c(e){let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t);return Uint8Array.from([...n].map(e=>e.charCodeAt(0)))}async function l(){let e=await o(`/push/vapid-public-key`);return(await(await fetch(e,s(e))).json()).publicKey}async function u(n,r,i){let u=await navigator.serviceWorker.ready,d=await l(),f=await u.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:c(d)}),p=n||typeof localStorage<`u`&&localStorage.getItem(e.CONTROL_PLANE_CLIENT_ID)||void 0,m=r,h=i;if(!p||!m)try{let e=await import(`./init-control-plane-
|
|
1
|
+
import{r as e}from"./config-y_2Fg77m.js";import{n as t}from"./db-BUuJo1Gf.js";import{t as n}from"./get-config-Bkvl__ZS.js";import{t as r}from"./set-config-DSiuMe0k.js";function i(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`sub-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function a(t){if(!t)return i();let a=await n(t,e.SUBSCRIBER_ID);if(typeof a==`string`&&a.trim().length>0)return a;let o=i();return await r(t,e.SUBSCRIBER_ID,o),o}async function o(r){let i=await t(),a=await n(i,e.PUSH_PROXY_URL);if(!a&&typeof localStorage<`u`)try{a=localStorage.getItem(e.PUSH_PROXY_URL)||void 0}catch{}if(!a)return r;let o=r.startsWith(`/`)?r:`/${r}`;return`${a.endsWith(`/`)?a.slice(0,-1):a}${o}`}function s(e,t={}){let n={...t};try{let t=typeof location<`u`?location.origin:`http://127.0.0.1:8888`,r=new URL(e,t).hostname.toLowerCase();r===`localhost`||r===`127.0.0.1`||r===`::1`||r===`[::1]`?n.targetAddressSpace=`loopback`:(/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(r)||!r.includes(`.`)||r.endsWith(`.local`)||r.endsWith(`.lan`)||r.endsWith(`.home`)||r.endsWith(`.internal`))&&(n.targetAddressSpace=`private`)}catch{}return n}function c(e){let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t);return Uint8Array.from([...n].map(e=>e.charCodeAt(0)))}async function l(){let e=await o(`/push/vapid-public-key`);return(await(await fetch(e,s(e))).json()).publicKey}async function u(n,r,i){let u=await navigator.serviceWorker.ready,d=await l(),f=await u.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:c(d)}),p=n||typeof localStorage<`u`&&localStorage.getItem(e.CONTROL_PLANE_CLIENT_ID)||void 0,m=r,h=i;if(!p||!m)try{let e=await import(`./init-control-plane-DGOY_RNS.js`);!p&&typeof e.getOrCreateControlPlaneClientId==`function`&&(p=e.getOrCreateControlPlaneClientId()),!m&&typeof e.detectDeviceLabel==`function`&&(m=e.detectDeviceLabel())}catch{}if(!h)try{let e=await Promise.race([t(),new Promise(e=>setTimeout(()=>e(null),500))]);e&&(h=await a(e))}catch{}let g=typeof f.toJSON==`function`?f.toJSON():JSON.parse(JSON.stringify(f)),_=await o(`/push/subscribe`);return await fetch(_,s(_,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...g,...p?{clientId:p}:{},...m?{deviceLabel:m}:{},...h?{subscriberId:h}:{}})})),f}async function d(n){if(typeof navigator<`u`&&navigator.serviceWorker)try{let r=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!r)return;let i,c,l=n;typeof localStorage<`u`&&(i=localStorage.getItem(e.CONTROL_PLANE_CLIENT_ID)||void 0);try{let e=await import(`./init-control-plane-DGOY_RNS.js`);!i&&typeof e.getOrCreateControlPlaneClientId==`function`&&(i=e.getOrCreateControlPlaneClientId()),typeof e.detectDeviceLabel==`function`&&(c=e.detectDeviceLabel())}catch{}if(!l)try{let e=await Promise.race([t(),new Promise(e=>setTimeout(()=>e(null),500))]);e&&(l=await a(e))}catch{}let u=typeof r.toJSON==`function`?r.toJSON():JSON.parse(JSON.stringify(r)),d=await o(`/push/subscribe`);await fetch(d,s(d,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...u,...i?{clientId:i}:{},...c?{deviceLabel:c}:{},...l?{subscriberId:l}:{}})}))}catch{}}async function f(){let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;let{endpoint:t}=e;await e.unsubscribe();let n=await o(`/push/subscribe`);await fetch(n,s(n,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({endpoint:t})}))}async function p(){return(await navigator.serviceWorker.ready).pushManager.getSubscription()}export{d as a,u as i,s as n,f as o,o as r,a as s,p as t};
|
|
@@ -36,4 +36,4 @@ const shadowClawImportScripts = (...urls) => {
|
|
|
36
36
|
|
|
37
37
|
shadowClawNativeImportScripts(...urls.map((url) => shadowClawServiceWorkerTrustedTypesPolicy.createScriptURL(url)));
|
|
38
38
|
};
|
|
39
|
-
if(!self.define){let e,s={};const r=(r,i)=>(r=new URL(r+".js",i).href,s[r]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=r,e.onload=s,document.head.appendChild(e)}else e=r,shadowClawImportScripts(r),s()}).then(()=>{let e=s[r];if(!e)throw new Error(`Module ${r} didn’t register its module`);return e}));self.define=(i,
|
|
39
|
+
if(!self.define){let e,s={};const r=(r,i)=>(r=new URL(r+".js",i).href,s[r]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=r,e.onload=s,document.head.appendChild(e)}else e=r,shadowClawImportScripts(r),s()}).then(()=>{let e=s[r];if(!e)throw new Error(`Module ${r} didn’t register its module`);return e}));self.define=(i,n)=>{const o=e||("document"in self?document.currentScript.src:"")||location.href;if(s[o])return;let c={};const a=e=>r(e,o),t={module:{uri:o},exports:c,require:a};s[o]=Promise.all(i.map(e=>t[e]||a(e))).then(e=>(n(...e),c))}}define(["./workbox-92eae37e"],function(e){"use strict";shadowClawImportScripts("service-worker/fetch-proxy.js","service-worker/push-handler.js","service-worker/share-target.js"),self.addEventListener("message",e=>{e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()}),e.clientsClaim(),e.precacheAndRoute([{url:"index.html",revision:"d396287de990eb152ca25dae6680d257"},{url:"404.html",revision:"74bc1afc55391d3ff43b99e39de1c72f"},{url:"index.css",revision:"7fd4b888962af18e251009bc1fe8a6ac"},{url:"index.js",revision:"a5482250f7865a05a532ae4f712b5ea2"},{url:"theme-init.js",revision:"0026d3e9c196392e99990a843862d7fc"},{url:"manifest.json",revision:"62f8d50f4e8fd710cb66c883f94b1c48"},{url:"favicon.ico",revision:"58fff7908409f246a6228529f384802e"},{url:"assets/icons/96.png",revision:"f91548690416c59ceb56cdb99809b955"},{url:"assets/icons/72.png",revision:"cba8470097972bdbc5d9a06fe67bfcf2"},{url:"assets/icons/512.png",revision:"ec2a8f28b812a0c2665a04cb3c535aab"},{url:"assets/icons/48.png",revision:"29eb2f38df4d5a6385399a04d7bdef00"},{url:"assets/icons/192.png",revision:"bf98264d7a62a47542e577245a292b77"},{url:"assets/icons/180.png",revision:"69128cf857af09292bb06fac0df9938b"},{url:"assets/icons/152.png",revision:"645ae818149dc508cc6146d620120db2"},{url:"assets/icons/128.png",revision:"84678d51d243c104d0c85a4e909fd0a6"},{url:"assets/icons/1024.png",revision:"ae17c81b3b93137df1702de6a9fcdab6"}],{}),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html"),{allowlist:[/^\/$/,/^(?:\/[^/]+)*\/$/,/^(?:\/[^/]+)*\/(chat|files|pages|tasks|settings)(?:\/.*)?$/],denylist:[/\/assets\//,/\.(png|jpe?g|gif|webp|svg|ico|bmp|avif|mp4|webm|mp3|wav|ogg|pdf|zip|gz|tar|css|js|json|wasm)$/i]})),e.registerRoute(({url:e,sameOrigin:s})=>{if(e.pathname.startsWith("/assets/v86.9pfs/"))return!1;const r=e.hostname.toLowerCase();if("huggingface.co"===r||r.endsWith(".huggingface.co")||r.endsWith(".hf.co")||"hf.co"===r||"hf-mirror.com"===r||r.endsWith(".hf-mirror.com")||"cdnjs.cloudflare.com"===r||"esm.sh"===r||r.endsWith(".esm.sh")||"unpkg.com"===r||"cdn.jsdelivr.net"===r||r.endsWith(".jsdelivr.net")||"esm.run"===r||"openrouter.ai"===r||r.endsWith(".openrouter.ai")||"api.telegram.org"===r)return!1;if(e.pathname.startsWith("/api/control/"))return!1;const i=e.pathname.endsWith("/share/share-target.html"),n="/proxy"===e.pathname||e.pathname.startsWith("/git-proxy/")||i||e.pathname.startsWith("/push/")||e.pathname.startsWith("/schedule/")||e.pathname.startsWith("/telegram/");return(!("localhost"===r||"127.0.0.1"===r||"::1"===r||"[::1]"===r)||!n)&&("boolean"!=typeof s||s)},new e.NetworkFirst({cacheName:"shadow-claw-cache",plugins:[new e.ExpirationPlugin({maxAgeSeconds:31536e3})]}),"GET")});
|