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
package/dist/server.js
CHANGED
|
@@ -110,7 +110,7 @@ function Mr(e,t){return kr(e)||Ar(e,t)||Nr(e,t)||jr()}function Nr(e,t){if(e){if(
|
|
|
110
110
|
(id, groupId, enabled, schedule, prompt, tools, lastRun, createdAt, type, freshContext, subagent, name, task_order)
|
|
111
111
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n.id,n.groupId,+!!n.enabled,n.schedule??null,n.prompt??``,n.tools?JSON.stringify(n.tools):null,n.lastRun??null,n.createdAt,n.type??null,n.freshContext?1:null,n.subagent?1:null,n.name??null,n.order??null);else if(t===`messages`)e.prepare(`INSERT OR REPLACE INTO messages
|
|
112
112
|
(id, groupId, timestamp, content, sender, channel, isFromMe, isTrigger, attachments, a2uiAction, a2uiEnvelopes, freshContext, subagent)
|
|
113
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n.id,n.groupId,n.timestamp,n.content,n.sender,n.channel??`chat`,+!!n.isFromMe,+!!n.isTrigger,n.attachments?JSON.stringify(n.attachments):null,n.a2uiAction?JSON.stringify(n.a2uiAction):null,n.a2uiEnvelopes?JSON.stringify(n.a2uiEnvelopes):null,n.freshContext?1:null,n.subagent?1:null);else{let r=Object.keys(n),i=r.map(()=>`?`).join(`, `),a=r.map(e=>{let t=n[e];return typeof t==`object`&&t?JSON.stringify(t):t});e.prepare(`INSERT OR REPLACE INTO ${t} (${r.join(`, `)}) VALUES (${i})`).run(...a)}return{result:void 0,onsuccess:null,onerror:null}},delete(n){return t===`config`?e.prepare(`DELETE FROM config WHERE key = ?`).run(n):t===`tasks`?e.prepare(`DELETE FROM tasks WHERE id = ?`).run(n):e.prepare(`DELETE FROM ${t} WHERE id = ?`).run(n),{result:void 0,onsuccess:null,onerror:null}}}}function ma(e,t,n,r){return new Promise((n,i)=>{try{let i=r(pa(e.db,t)),a=i.onsuccess;typeof a==`function`&&a(),n(i.result)}catch(e){i(e)}})}function ha(e,t,n,r){return e?ua(e)?ma(e,t,n,r):new Promise((i,a)=>{try{let o=e.transaction(t,n);if(!o)return a(/* @__PURE__ */ Error(`failed to get transaction`));let s=r(o.objectStore(t));s.onsuccess=()=>i(s.result),s.onerror=()=>a(s.error)}catch(e){a(e)}}):Promise.reject(/* @__PURE__ */ Error(`failed to get database, cannot update task.`))}var ga=R((()=>{la(),fa()})),_a=/* @__PURE__ */ pt({getConfig:()=>va});function va(e,t){return ha(e,`config`,`readonly`,e=>e.get(t)).then(e=>e?.value)}var ya=R((()=>{ga()}));function ba(e){let t=e.trim();if(!t)return()=>!1;if(t.startsWith(`/`)&&(t.endsWith(`/`)||/\/[gimuy]*$/.test(t)))try{let e=t.lastIndexOf(`/`),n=t.slice(1,e),r=t.slice(e+1),i=new RegExp(n,r||`i`);return e=>i.test(e)}catch{}if(t.includes(`^`)||t.includes(`$`)||t.includes(`(`)&&t.includes(`)`))try{let e=new RegExp(t,`i`);return t=>e.test(t)}catch{}if(t.startsWith(`*.`)){let e=t.slice(2).toLowerCase();return t=>{let n=t.toLowerCase();return n===e||n.endsWith(`.`+e)}}let n=t.toLowerCase();return e=>{let t=e.toLowerCase();return t===n||t.endsWith(`.`+n)}}var xa=R((()=>{}));function Sa(e){Ta=e.map(e=>ba(e)).filter(Boolean)}var Ca,wa,Ta,Ea=R((()=>{ta(),la(),ya(),xa(),Ca=[`youtube.com`,`youtube-nocookie.com`,`youtu.be`,`xt-ml.github.io`,`kherrick.github.io`],wa=[...Ca],Sa(wa)}));function Da(e){Ua=e.map(e=>ba(e)).filter(Boolean)}function Oa(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.toLowerCase().trim():``).filter(Boolean):typeof e==`string`?e.split(/[\n,]+/).map(e=>e.toLowerCase().trim()).filter(Boolean):[]}function ka(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.split(/[\n,]+/).map(e=>e.trim()).filter(Boolean):[]}function Aa(e){let t=Oa(e);Va=new Set(t)}function ja(e){let t=ka(e);Ha=t,Da(t)}function Ma(e){if(!e||typeof e!=`string`)return!1;let t=e.trim().toLowerCase();return!t.includes(`-`)||t===`shadow-claw`||t.startsWith(`shadow-claw-`)||t.startsWith(`sc-`)?!0:Va.has(t)}function Na(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();if(!t||/^(?:javascript|data|vbscript):/i.test(t))return!1;if(/^blob:/i.test(t)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`))return!0;try{let e=typeof globalThis<`u`&&globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`,n=new URL(t,e);if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(typeof globalThis<`u`&&globalThis.location?.origin&&globalThis.location.origin!==`null`&&n.origin===globalThis.location.origin)return!0;let r=n.hostname.toLowerCase();return Ua.some(e=>e(r))}catch{return!1}}function Pa(e){if(!e||typeof e!=`object`)return;let t=e.allowedCustomElements||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedElements:void 0);t!==void 0&&Aa(t);let n=e.allowedCustomElementDomains||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedDomains:void 0);n!==void 0&&ja(n)}function Fa(e){Wa=e}function Ia(){if(typeof document>`u`)return;let e=document.getElementById(`shadow-claw-site-config`);if(e&&e.textContent)try{let t=JSON.parse(e.textContent);Pa(t),Wa?.(t)}catch{}}function La(){Ia(),!(Ka||typeof customElements>`u`||typeof customElements.define!=`function`)&&(Ga=customElements.define.bind(customElements),customElements.define=function(e,t,n){if(!Ma((e||``).toLowerCase().trim())){let t=`[Security] Registration blocked: <${e}> is not an approved custom element.`;throw console.error(t),Error(t)}return Ga(e,t,n)},Ka=!0)}function Ra(e=typeof document<`u`?document.documentElement:null){if(typeof MutationObserver>`u`||!e)return null;if(typeof e.querySelectorAll==`function`)try{e.querySelectorAll(`*`).forEach(e=>{let t=e.tagName?e.tagName.toLowerCase():``;t.includes(`-`)&&!Ma(t)&&(console.warn(`[Security] Removing existing unapproved custom element: <${t}>`),e.remove())})}catch{}let t=new MutationObserver(e=>{for(let t of e)t.addedNodes.forEach(e=>{if(e.nodeType===1){let t=e,n=t.tagName?t.tagName.toLowerCase():``;n.includes(`-`)&&!Ma(n)&&(console.warn(`[Security] Removing unapproved custom element: <${n}>`),t.remove())}})});return t.observe(e,{childList:!0,subtree:!0}),t}var za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa=R((()=>{xa(),za=[],Ba=[],Va=new Set(za.map(e=>e.toLowerCase().trim())),Ha=[...Ba],Ua=[],Da(Ha),Wa=null,Ga=null,Ka=!1}));function Ja(e){ro=Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean).join(` `):typeof e==`string`&&e.trim()?e.trim():Qa}function Ya(e){if(!e||typeof e!=`object`)return;let t=e.allowedCustomElements||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedElements:void 0);t!==void 0&&Aa(t);let n=e.allowedCustomElementDomains||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedDomains:void 0);n!==void 0&&ja(n);let r=typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.scripts:void 0;r!==void 0&&Xa(r),e.security?.iframeSandbox===void 0?(e.security?.allowSameOrigin===!0||e.security?.allowIframeSameOrigin===!0)&&(ro.includes(`allow-same-origin`)||(ro=`${ro} allow-same-origin`.trim())):Ja(e.security.iframeSandbox),e.security?.workerSrc!==void 0&&(io=ka(e.security.workerSrc)),e.security?.connectSrc!==void 0&&(ao=ka(e.security.connectSrc)),e.security?.scriptSrc!==void 0&&(oo=ka(e.security.scriptSrc)),e.security?.styleSrc!==void 0&&(so=ka(e.security.styleSrc)),e.security?.imgSrc!==void 0&&(co=ka(e.security.imgSrc))}function Xa(e){lo=Array.isArray(e)?e.map(e=>({src:typeof e==`string`?e:e?.src,hasInit:typeof e==`object`&&e?!!e.hasInit:!1})).filter(e=>typeof e.src==`string`&&Na(e.src)):[]}async function Za(e){try{let{getDb:t}=await Promise.resolve().then(()=>(la(),na)),{getConfig:n}=await Promise.resolve().then(()=>(ya(),_a)),r=e??await t();if(!r)return;let[i,a]=await Promise.all([n(r,`allowed_custom_elements`),n(r,`allowed_custom_element_host_patterns`)]);if(typeof i==`string`&&i.trim())try{Aa(JSON.parse(i))}catch{Aa(i)}if(typeof a==`string`&&a.trim())try{ja(JSON.parse(a))}catch{ja(a)}}catch(e){console.warn(`Failed to load custom element security from db:`,e)}}var Qa,$a,eo,to,no,ro,io,ao,oo,so,co,lo,uo=R((()=>{qa(),qa(),Ea(),yo(),Qa=`allow-modals allow-scripts allow-popups allow-popups-to-escape-sandbox`,$a=[`'self'`,`blob:`,`data:`],eo=[`'self'`,`blob:`,`data:`],to=[`'self'`,`'unsafe-inline'`,`https:`,`http:`],no=[`'self'`,`blob:`,`data:`,`https:`,`http:`],ro=Qa,[...$a],[...eo],[...to],[...no],Fa(Ya)})),fo=R((()=>{Ut(),Ea(),uo()}));function po(){let e=globalThis.trustedTypes;return!e||typeof e.createPolicy!=`function`?null:e}function mo(){if(vo!==void 0)return vo;let e=po();if(!e)return vo=null,vo;if(typeof e.getPolicy==`function`){let t=e.getPolicy(_o);if(t)return vo=t,vo}try{vo=e.createPolicy(_o,{createHTML:e=>e,createScriptURL:e=>e})}catch{vo=typeof e.getPolicy==`function`?e.getPolicy(_o)??null:null}return vo}function ho(){return _o}function go(e){let t=mo();return!t||typeof t.createScriptURL!=`function`?e:t.createScriptURL(e)}var _o,vo,yo=R((()=>{fo(),_o=`shadowclaw`}));yo();const bo=[`shadow-claw.config.json`,`shadow-claw-config.json`,`shadowclaw.config.json`,`site-config.json`,`pages/site-config.json`];function xo(e){try{if(p!==void 0&&typeof p.readFileSync==`function`&&p.existsSync(e)){let t=p.readFileSync(e,`utf8`);return JSON.parse(t)}}catch{}return null}function So(e){let t=[];if(e){let n=c.resolve(e);t.push(n),t.push(c.resolve(n,`..`)),t.push(c.resolve(n,`../..`))}if(n!==void 0&&typeof n.cwd==`function`){let e=c.resolve(n.cwd());t.includes(e)||t.push(e)}for(let e of t)for(let t of bo){let n=xo(c.resolve(e,t));if(n&&typeof n==`object`)return n}return null}function Co(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;if(!e||typeof e!=`object`)return{scriptHosts:[],workerSources:[],connectSources:[]};let i=e.allowedCustomElementDomains||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedDomains:void 0);if(Array.isArray(i)){for(let e of i)if(typeof e==`string`&&e.trim()){let n=e.trim();t.add(`https://${n}`),t.add(`http://${n}`),r.add(`https://${n}`),r.add(`http://${n}`)}}let a=typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.scripts:void 0;if(Array.isArray(a))for(let e of a){let n=typeof e==`string`?e:e?.src;if(typeof n==`string`&&(n.startsWith(`http://`)||n.startsWith(`https://`)||n.startsWith(`//`)))try{let e=new URL(n.startsWith(`//`)?`https:${n}`:n).origin;t.add(e),r.add(e)}catch{}}if(e.security&&typeof e.security==`object`){if(Array.isArray(e.security.scriptSrc))for(let n of e.security.scriptSrc)typeof n==`string`&&n.trim()&&t.add(n.trim());if(Array.isArray(e.security.workerSrc))for(let t of e.security.workerSrc)typeof t==`string`&&t.trim()&&n.add(t.trim());if(Array.isArray(e.security.connectSrc))for(let t of e.security.connectSrc)typeof t==`string`&&t.trim()&&r.add(t.trim())}return{scriptHosts:Array.from(t),workerSources:Array.from(n),connectSources:Array.from(r)}}function wo(e={}){let t=e.includeTrustedTypes??!0,r=e.config;r===void 0&&e.rootPath?r=So(e.rootPath):r===void 0&&n!==void 0&&typeof n.cwd==`function`&&(r=So(n.cwd()));let i=Co(r),a=[`'self'`,`'unsafe-inline'`,...i.scriptHosts,...e.scriptSources??[]],o=[`'self'`,`blob:`,`data:`,...i.workerSources,...e.workerSources??[]],s=[`'self'`,`https:`,`wss:`,`ws:`,`data:`,...i.connectSources,...e.connectSources??[]],c=[`default-src 'self'`,`base-uri 'self'`,`frame-ancestors 'none'`,`frame-src 'self' https://www.youtube.com`,`object-src 'none'`,`img-src 'self' data: blob: https: http:`,`media-src 'self' data: blob: https: http:`,`font-src 'self' data: https://fonts.googleapis.com https://fonts.gstatic.com`,`style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://fonts.googleapis.com`,`script-src ${Array.from(new Set(a)).join(` `)}`,`worker-src ${Array.from(new Set(o)).join(` `)}`,`connect-src ${Array.from(new Set(s)).join(` `)}`,`report-uri /__cspreport`];return t&&c.push(`trusted-types ${ho()} shadowclaw-sandbox dompurify default`,`require-trusted-types-for 'script'`),c.join(`; `)}function To(e){return!/\bfirefox\//i.test(e)}function Eo(e={}){let t=wo({...e,includeTrustedTypes:e.includeTrustedTypes??!0}),n=wo({...e,includeTrustedTypes:!1});return(e,r,i)=>{let a=!To(e.get(`user-agent`)??``);r.setHeader(`Content-Security-Policy-Report-Only`,a?n:t),r.setHeader(`Origin-Agent-Cluster`,`?1`),i()}}function Do(e,t){return(n,r,i)=>{let a=n.headers[`access-control-request-private-network`]===`true`,o=!!n.headers.origin;(a||o)&&(t&&a&&e.log(`VERBOSE`,`[PNA] Allowing Private Network Access`),r.setHeader(`Access-Control-Allow-Private-Network`,`true`)),i()}}function Oo(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 ko(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 Ao(){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))}var jo=R((()=>{}));async function Mo(e,t={}){let{maxRetries:n=3,baseDelayMs:r=1e3,maxDelayMs:i=3e4,jitterFactor:a=.5,shouldRetry:o=()=>!0,onRetry:s,signal:c}=t,l;for(let t=0;t<=n;t++){if(c?.aborted)throw c.reason??new DOMException(`Aborted`,`AbortError`);try{return await e()}catch(e){if(l=e,e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`)throw e;if(t>=n||!o(e,t+1))break;let u=Oo(t,r,i,a);s&&s(t+1,n,u,e),await ko(u,c)}}throw l}function No(e){return/network|ECONNRESET|ECONNREFUSED|ETIMEDOUT|fetch failed|EAI_AGAIN|EAI_NONAME|getaddrinfo/i.test(e.message)}function Po(e){if(e instanceof TypeError)return!0;if(typeof e?.status==`number`)return Io.has(e.status);if(e instanceof Error){let t=e.message.match(/\b(4\d{2}|5\d{2})\b/);if(t)return Io.has(Number(t[1]));if(No(e))return!0}return!1}function Fo(e){return e instanceof TypeError?!0:e&&typeof e.status==`number`?Io.has(e.status):e instanceof Error&&No(e)}var Io,Lo=R((()=>{jo(),Io=/* @__PURE__ */ new Set([408,429,500,502,503,504])}));function eee(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`::1`||t===`[::1]`||/^127\.\d+\.\d+\.\d+$/.test(t)}function tee(e){if(!e)return!1;let t=e.trim().toLowerCase();return/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t)||/^169\.254\./.test(t)}function nee(e){if(!e)return!1;let t=e.trim().toLowerCase();return eee(t)||tee(t)||!t.includes(`.`)?!0:Ro.some(e=>t.endsWith(e))}var Ro,ree=R((()=>{Ro=[`.local`,`.lan`,`.home`,`.internal`]}));function zo(e){return Array.isArray(e)?e[0]||``:typeof e==`string`?e:``}function Bo(e,t){let n=Number.parseInt(e??``,10);return!Number.isFinite(n)||n<=0?t:n}function iee(e,t){let n=Number.parseInt(e??``,10);return!Number.isFinite(n)||n<0?t:n}function aee(e){return/^\/telegram\/(?:bot|file\/bot)[^/]+\//.test(e)}function oee(e){try{let t=new URL(e);return t.hostname===`api.telegram.org`&&aee(t.pathname)&&(t.pathname=t.pathname.replace(/^\/telegram\/(?:bot|file\/bot)[^/]+\//,e=>e.includes(`/file/`)?`/telegram/file/bot[REDACTED]/`:`/telegram/bot[REDACTED]/`)),t.toString()}catch{return e.replace(/\/file\/bot[^/]+\//,`/file/bot[REDACTED]/`).replace(/\/bot[^/]+\//,`/bot[REDACTED]/`)}}function Vo(e){return nee(e)}async function Ho(e,t,n){if(!n||n<=0)return fetch(e,t);let r=new AbortController,i=t.signal,a=i?AbortSignal.any([i,r.signal]):r.signal,o=setTimeout(()=>{r.abort()},n);try{return await fetch(e,{...t,signal:a})}catch(e){throw e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`?Error(`Upstream request timed out after ${n}ms`):e}finally{clearTimeout(o)}}function see(e){return Array.isArray(e.tools)&&e.tools.length>0}function Uo(e){let t={...e};return delete t.tools,delete t.tool_choice,t}function Wo(e){return/does not support tools/i.test(e||``)}async function Go(e,t,n){let{targetUrl:r,method:i,headers:a,body:o,verbose:s,maxRetries:c,requestTimeoutMs:l,forwardAuth:u,allowPrivate:d,fromServiceWorker:f}=n;s&&console.log(`[Proxy] Forwarding ${i} request to: ${oee(r)}`);try{let e;try{e=new URL(r)}catch{t.status(400).json({error:`Invalid URL`});return}if(e.protocol!==`http:`&&e.protocol!==`https:`){t.status(400).json({error:`Unsupported URL scheme — only http and https are allowed`});return}if(Vo(e.hostname)&&!d&&!f){t.status(403).json({error:`Requests to private or internal addresses are blocked`});return}let n={...a};n[`User-Agent`]=Ko,delete n.host,delete n.origin,delete n.referer,u||(delete n.Authorization,delete n.authorization),delete n[`accept-encoding`],delete n[`content-length`],delete n.connection;let p=await Mo(()=>Ho(e.toString(),{method:i,headers:n,body:i===`GET`||i===`HEAD`?void 0:o instanceof N?o:o?.toString()},l),{maxRetries:c??3,shouldRetry:Po,onRetry:(e,t,n,r)=>{s&&console.log(`[Proxy] Retry ${e}/${t} after ${n}ms due to: ${r.message||r}`)}});t.status(p.status),p.headers.forEach((e,n)=>{let r=n.toLowerCase();r!==`content-encoding`&&r!==`transfer-encoding`&&r!==`content-length`&&r!==`connection`&&t.setHeader(n,e)}),t.setHeader(`Access-Control-Allow-Origin`,`*`);let m=N.from(await p.arrayBuffer());t.send(m)}catch(e){console.error(`Proxy error:`,e),t.status(500).json({error:`Proxy request failed`})}}async function cee(e,t,n){let{targetUrl:r,headers:i,body:a,verbose:o,maxRetries:s,requestTimeoutMs:c,allowPrivate:l,fromServiceWorker:u}=n;o&&console.log(`[Proxy] Streaming POST request to: ${oee(r)}`);try{let e;try{e=new URL(r)}catch{t.status(400).json({error:`Invalid URL`});return}if(e.protocol!==`http:`&&e.protocol!==`https:`){t.status(400).json({error:`Unsupported URL scheme — only http and https are allowed`});return}if(Vo(e.hostname)&&!l&&!u){t.status(403).json({error:`Requests to private or internal addresses are blocked`});return}let n={...i};delete n.host,delete n.origin,delete n.referer,delete n[`accept-encoding`],delete n[`content-length`],delete n.connection;let d=await Mo(()=>Ho(e.toString(),{method:`POST`,headers:{...n,"User-Agent":Ko},body:a},c),{maxRetries:s??3,shouldRetry:Po,onRetry:(e,t,n,r)=>{o&&console.log(`[Proxy] Streaming Retry ${e}/${t} after ${n}ms due to: ${r.message||r}`)}});if(!d.ok){let e=await d.text();t.status(d.status),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.json({error:e});return}if(t.status(200),t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.flushHeaders(),!d.body){t.end();return}let f=d.body.getReader();try{for(;;){let{done:e,value:n}=await f.read();if(e)break;t.write(N.from(n))}}finally{f.releaseLock()}t.end()}catch(e){console.error(`Streaming proxy error:`,e),t.headersSent?t.end():t.status(500).json({error:`Streaming proxy request failed`})}}var Ko,qo=R((()=>{Lo(),ree(),Ko=n.env.SHADOWCLAW_USER_AGENT||`ShadowClaw/1.0`}));qo();function lee(e,t){return(n,r,i)=>{let a=Date.now(),o=zo(n.headers[`x-forwarded-for`])||n.socket?.remoteAddress||n.ip||`unknown`,s=zo(n.headers.origin)||`-`,c=zo(n.headers.host)||`-`,l=zo(n.headers[`access-control-request-method`])||`-`,u=zo(n.headers[`access-control-request-headers`])||`-`,d=zo(n.headers[`access-control-request-private-network`])||`-`,f=n.originalUrl.replace(/\/telegram\/(?:bot|file\/bot)[^/]+\//,e=>e.startsWith(`/telegram/file/`)?`/telegram/file/bot[REDACTED]/`:`/telegram/bot[REDACTED]/`);e.log(`DEFAULT`,`--> ${n.method} ${f} ip=${o} host=${c} origin=${s}`),n.method===`OPTIONS`&&e.log(`DEFAULT`,` [Preflight] request-method=${l} request-headers=${u} private-network=${d}`),r.on(`finish`,()=>{let i=Date.now()-a,o=r.statusCode,s=r.getHeader(`access-control-allow-origin`)||`-`,c=r.getHeader(`access-control-allow-private-network`)||`-`;e.log(`DEFAULT`,`<-- ${n.method} ${f} ${o} (${i}ms) allow-origin=${s} allow-private-network=${c}`),t&&(e.log(`VERBOSE`,` Query:`,n.query),n.body&&Object.keys(n.body).length>0&&e.log(`VERBOSE`,` Body keys:`,Object.keys(n.body)))}),i()}}Ut();const uee=/* @__PURE__ */ new Set([`chat`,`files`,`pages`,`tasks`,`settings`,`tools`,`channels`]);function Jo(e,t){let n=(e.method||`GET`).toUpperCase();if(n!==`GET`&&n!==`HEAD`)return!1;let r=e.headers||{},i=String(r[`sec-fetch-dest`]||``).toLowerCase();if(i&&i!==`document`)return!1;let a=String(r[`sec-fetch-mode`]||``).toLowerCase(),o=String(r[`sec-fetch-user`]||``).toLowerCase(),s=i===`document`||a===`navigate`||o===`?1`,c=String(r.accept||``);if(!s&&!c.includes(`text/html`))return!1;let l=t.replace(/^\/+|\/+$/g,``);if(!l)return!1;let u=l.split(`/`).filter(Boolean),d=u[0]||``;return!(!uee.has(d)||d===`pages`&&(u.includes(`assets`)||zt(u[u.length-1])))}const Yo=/* @__PURE__ */ new Set([`.well-known`,`.agents`]);function dee(e){let t=e.split(`/`).filter(Boolean),n=t.filter(e=>e.length>0&&e.startsWith(`.`));if(n.length===0)return!0;if(n.length!==1)return!1;let r=n[0];return Yo.has(r)?t[0]===r||t[1]===r:!1}function fee(e){let t=e.split(`/`).filter(Boolean);return t.length>0&&Yo.has(t[0])||t.length>1&&Yo.has(t[1])}function pee(e,t){e.use(ie(/^(.+)\/index\.html$/,`$1/`)),e.use((e,n,r)=>{n.setHeader(`Access-Control-Allow-Origin`,`*`),n.setHeader(`Access-Control-Allow-Methods`,`GET, HEAD, OPTIONS`),n.setHeader(`Origin-Agent-Cluster`,`?1`);let i=new URL(e.originalUrl,`http://localhost`).pathname;if(!dee(i)){r();return}let a=fee(i)?{dotfiles:`allow`}:void 0;i.startsWith(`/assets/v86.9pfs/`)||i.startsWith(`/assets/v86.ext2/`)?n.setHeader(`Cache-Control`,`public, max-age=31536000, immutable`):n.setHeader(`Cache-Control`,`no-cache`);let o=new URL(e.url||`/`,`http://localhost`).pathname;if(Jo(e,i)||Jo(e,o)){n.sendFile(c.join(t,`index.html`));return}let s=c.join(t,o);p.stat(s,(l,u)=>{if(l||!u){let e=i.replace(/^\/[^/]+/,``);if(e){let r=c.join(t,e);try{if(p.existsSync(r)&&p.statSync(r).isFile()){let t=fee(e)?{dotfiles:`allow`}:void 0;t?n.sendFile(r,t):n.sendFile(r);return}}catch{}}if(i.startsWith(`/files/main/`)){let e=c.resolve(`pages/main`,i.slice(12));p.stat(e,(t,i)=>{!t&&i&&i.isFile()?n.sendFile(e):r()});return}if(i.startsWith(`/static-main/`)){let e=c.resolve(`pages/main`,i.slice(13));p.stat(e,(t,i)=>{!t&&i&&i.isFile()?n.sendFile(e):r()});return}if(i.startsWith(`/pages/`)){let e=c.resolve(`pages`,i.slice(7));p.stat(e,(t,i)=>{!t&&i&&i.isFile()?n.sendFile(e):r()});return}r()}else if(u.isDirectory()){let l=c.join(s,`index.html`);p.access(l,p.constants.F_OK,s=>{s?Jo(e,i)||Jo(e,o)?n.sendFile(c.join(t,`index.html`)):r():a?n.sendFile(l,a):n.sendFile(l)})}else a?n.sendFile(s,a):n.sendFile(s)})}),e.use(A.static(t,{etag:!0}))}qo();function mee(e,t={}){let n=t.verbose??!1,r=t.allowPrivateProxy??!1;e.all(/^\/proxy(\/(.*))?$/,async(e,t)=>{let i=typeof e.query.url==`string`?e.query.url:void 0,a=(e.body&&typeof e.body.url==`string`?e.body.url:void 0)||i;if(!a){let t=e.params[1];if(t){a=t;let n={...e.query};if(delete n.url,Object.keys(n).length>0){let e=a.includes(`?`)?`&`:`?`;a+=e+new URLSearchParams(n).toString()}}}if(!a)return t.status(400).json({error:`Missing 'url' parameter`});let o=(e.body&&typeof e.body.method==`string`&&e.body.method||e.method).toUpperCase(),s=!!(e.body&&e.body.headers&&typeof e.body.headers==`object`),c=(s?e.body.headers:e.headers)||{},l;e.body&&typeof e.body.body==`string`&&(l=e.body.body);let u=s&&!!(c.Authorization||c.authorization);await Go(e,t,{targetUrl:a,method:o,headers:c,body:l,verbose:n,forwardAuth:u,fromServiceWorker:s,allowPrivate:r})}),e.all(/^\/telegram\/((?:bot.*)|(?:file\/bot.*))$/,async(e,t)=>{t.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0`),t.setHeader(`Pragma`,`no-cache`),t.setHeader(`Expires`,`0`);let r=`https://api.telegram.org/${e.params[0]}${Object.keys(e.query).length>0?`?`+new URLSearchParams(e.query).toString():``}`,i=e.method.toUpperCase(),a=e.headers||{},o;if((a[`content-type`]||``).includes(`multipart/form-data`)){let t=[];for await(let n of e)t.push(n);o=N.concat(t)}else e.body&&typeof e.body.body==`string`?o=e.body.body:e.body&&typeof e.body==`object`&&Object.keys(e.body).length>0&&!(`url`in e.body)&&!(`method`in e.body)&&!(`headers`in e.body)&&(o=JSON.stringify(e.body));await Go(e,t,{targetUrl:r,method:i,headers:a,body:o,verbose:n})}),e.all(/^\/git-proxy\/(.*)/,async(e,t)=>{let r=e.params[0],i=Object.keys(e.query).length>0?`?`+new URLSearchParams(e.query).toString():``,a=`https://`+r+i,o=[];for await(let t of e)o.push(t);let s=N.concat(o);await Go(e,t,{targetUrl:a,method:e.method,headers:e.headers,body:s.length>0?s:void 0,verbose:n,forwardAuth:!0})})}const Xo=/* @__PURE__ */ new Map;function Zo(e){if(typeof e!=`string`||e.trim().length===0)return;let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(t.includes(`claude-sonnet-5`)||t.includes(`claude-opus-4-7`)||t.includes(`claude-opus-5`)||t.includes(`claude-opus-4-8`)||t.includes(`claude-mythos-5`)||t.includes(`claude-mythos`)||t.includes(`claude-fable-5`)||t.includes(`claude-fable`))return!0;if(t.includes(`claude-sonnet-4-6`))return!1}function hee(e,t){if(typeof e!=`string`||e.trim().length===0)return;let n=Zo(e),r=Zo(t)??n;typeof r==`boolean`&&Xo.set(e.toLowerCase(),r)}function gee(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(Xo.has(n))return Xo.get(n)===!0;if(Xo.has(r))return Xo.get(r)===!0;let i=Zo(n);if(typeof i==`boolean`)return i;let a=Zo(r);return typeof a==`boolean`&&a}qo();const _ee=i.BEDROCK_REGION||``,vee=i.BEDROCK_PROFILE||``;function yee(e){return{region:_ee||zo(e.headers[`x-bedrock-region`])?.trim()||``,profile:vee||zo(e.headers[`x-bedrock-profile`])?.trim()||``,authMode:zo(e.headers[`x-bedrock-auth-mode`])?.trim()||`provider_chain`}}function bee(e,t){return t===`sso`?fe({profile:e}):de({profile:e})}function xee(e,t){if(/^[a-z]+\.anthropic\./.test(e))return e;let n=t.split(`-`)[0];if(!n)throw Error(`Bedrock region is not configured. Set BEDROCK_REGION or provide x-bedrock-region header.`);return`${n}.${e}`}function See(e){if(e.type===`text`)return{text:e.text};if(e.type===`image`){let t=e.source.data;return{image:{format:e.source.media_type.split(`/`)[1],source:{bytes:N.from(t,`base64`)}}}}if(e.type===`tool_use`)return{toolUse:{toolUseId:e.id,name:e.name,input:e.input}};if(e.type===`tool_result`){let t=typeof e.content==`string`?[{text:e.content}]:Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{text:e.text}:{text:JSON.stringify(e)}):[{text:JSON.stringify(e.content)}];return{toolResult:{toolUseId:e.tool_use_id,content:t}}}return e.type===`thinking`?typeof e.signature!=`string`||e.signature.length===0?void 0:{reasoningContent:{reasoningText:{text:e.thinking||``,signature:e.signature}}}:e.type===`redacted_thinking`?{reasoningContent:{redactedContent:{data:e.data||``}}}:{text:JSON.stringify(e)}}function Cee(e){return!!(e&&typeof e==`object`&&e.cache_control)}function Qo(e){let t=e?.ttl;return{cachePoint:{type:`default`,...t===`1h`||t===`5m`?{ttl:t}:{}}}}function wee(e=4){let t=e;return{take(){return t<=0?!1:(--t,!0)}}}function Tee(e,t){let n=`(continue)`;if(!Array.isArray(e)||e.length===0)return[];let r=(e||[]).map(e=>{let n=Array.isArray(e.content)?e.content:[{type:`text`,text:typeof e.content==`string`?e.content:``}],r=Array.isArray(e.content)?e.content.map(See):[{text:typeof e.content==`string`?e.content:``}],i=[];return r.forEach((e,r)=>{if(e===void 0||e&&typeof e.text==`string`&&e.text.trim().length===0)return;i.push(e);let a=n[r];Cee(a)&&t?.take()&&i.push(Qo(a.cache_control))}),{role:e.role,content:i}}),i=r.filter(e=>e.content.length>0);if(i.length===0&&r.length>0){let e=r[r.length-1];return[{role:e.role===`assistant`?`user`:e.role,content:[{text:n}]}]}let a=[];for(let e of i){let t=a[a.length-1];t&&t.role===e.role?t.content.push(...e.content):a.push(e)}return a.length>0&&a[0].role===`assistant`&&a.shift(),a.length===0?[{role:`user`,content:[{text:n}]}]:(a[a.length-1].role===`assistant`&&a.push({role:`user`,content:[{text:n}]}),a)}function Eee(e){switch(e){case`tool_use`:return`tool_use`;case`max_tokens`:return`max_tokens`;case`stop_sequence`:return`stop_sequence`;default:return`end_turn`}}function Dee(){return`msg_`+Math.random().toString(36).substring(2,10)}function Oee(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`low`||t===`medium`||t===`high`||t===`xhigh`||t===`max`)return t;if(t===`minimal`||t===`none`)return`low`}function kee(e,t){let n=typeof e==`number`&&Number.isFinite(e)?Math.max(1,e):0,r=n>0?n/(typeof t==`number`&&Number.isFinite(t)?Math.max(1,t):8192):.5;return r>=.95?`max`:r>=.85?`xhigh`:r>=.7?`high`:r>=.35?`medium`:`low`}function Aee(e,t,n){if(!e?.thinking)return;let r=e.thinking;if(!gee(t,n)||(typeof r?.type==`string`?r.type.toLowerCase():``)===`disabled`)return{thinking:r};let i=Oee(e?.output_config?.effort),a=kee(r?.budget_tokens,e?.max_tokens);return{thinking:{type:`adaptive`},output_config:{effort:i||a}}}function jee(e,t={}){e.get(`/bedrock-proxy/models`,async(e,t)=>{try{let n=yee(e);if(!n.region||!n.profile)return t.status(400).json({error:`Bedrock is not configured. Set BEDROCK_REGION and BEDROCK_PROFILE environment variables or provide Bedrock fallback settings in the UI.`});let r=new ae({region:n.region,credentials:bee(n.profile,n.authMode)}),i=((await r.send(new oe({byProvider:`Anthropic`}))).modelSummaries||[]).filter(e=>e.modelLifecycle?.status===`ACTIVE`).map(e=>(hee(e.modelId,e.modelName),{id:e.modelId,name:e.modelName}));try{let e=((await r.send(new se({}))).inferenceProfileSummaries||[]).filter(e=>e.status===`ACTIVE`).filter(e=>e.inferenceProfileId?.includes(`anthropic`)||e.inferenceProfileName?.toLowerCase().includes(`anthropic`)).map(e=>({id:e.inferenceProfileId||``,name:`${e.inferenceProfileName||`Unnamed Profile`} (Profile)`})).map(e=>(hee(e.id,e.name),e));i.push(...e)}catch(e){(e&&typeof e==`object`&&`name`in e?e.name:``)!==`AccessDeniedException`&&console.warn(`Failed to list Bedrock inference profiles:`,e instanceof Error?e.message:String(e))}t.json({models:i})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Bedrock models discovery error:`,n),t.status(502).json({error:`Failed to list Bedrock models: ${n}`})}}),e.post(`/bedrock-proxy/invoke`,async(e,t)=>{try{let n=yee(e);if(!n.region||!n.profile)return t.status(400).json({error:`Bedrock is not configured. Set BEDROCK_REGION and BEDROCK_PROFILE environment variables or provide Bedrock fallback settings in the UI.`});let r=e.body;if(!r||typeof r!=`object`)return t.status(400).json({error:`Missing request body`});let i=r.model;if(typeof i!=`string`||!i.startsWith(`anthropic.`)&&!/^[a-z]+\.anthropic\./.test(i))return t.status(400).json({error:`Invalid model ID: '${String(i||``)}'. Must be an Anthropic Bedrock model ID.`});let a=xee(i,n.region),o=r.stream===!0,{model:s,stream:c,...l}=r,u=new ce({region:n.region,credentials:bee(n.profile,n.authMode),maxAttempts:3,retryMode:`adaptive`,requestHandler:{requestTimeout:6e4}}),d=wee(),f;if(l.tools&&l.tools.length>0){let e=[];for(let t of l.tools)e.push({toolSpec:{name:t.name,description:t.description,inputSchema:{json:t.input_schema}}}),Cee(t)&&d.take()&&e.push(Qo(t.cache_control));if(f={tools:e},l.tool_choice){let e=l.tool_choice;e.type===`tool`?f.toolChoice={tool:{name:e.name}}:e.type===`any`?f.toolChoice={any:{}}:f.toolChoice={auto:{}}}}let p=[];if(Array.isArray(l.system))for(let e of l.system){let t=typeof e?.text==`string`?e.text:``;t.trim().length!==0&&(p.push({text:t}),Cee(e)&&d.take()&&p.push(Qo(e.cache_control)))}else typeof l.system==`string`&&l.system.trim().length>0&&p.push({text:l.system});let m=p.length>0?p:void 0,h=Tee(l.messages||[],d),g={};l.max_tokens&&(g.maxTokens=l.max_tokens),l.temperature!==void 0&&(g.temperature=l.temperature),l.top_p!==void 0&&(g.topP=l.top_p),l.stop_sequences&&(g.stopSequences=l.stop_sequences);let _={modelId:a,messages:h,system:m,inferenceConfig:Object.keys(g).length>0?g:void 0,toolConfig:f,additionalModelRequestFields:Aee(l,i,a)};if(o){let e=new ue(_),n=await u.send(e);if(t.status(200),t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.flushHeaders(),t.write(`data: ${JSON.stringify({type:`message_start`,message:{id:Dee(),type:`message`,role:`assistant`,model:a,content:[],usage:{input_tokens:0,output_tokens:0}}})}\n\n`),n.stream){let e=/* @__PURE__ */ new Set;for await(let r of n.stream)if(r.contentBlockStart){let n=r.contentBlockStart.start,i=r.contentBlockStart.contentBlockIndex??0;if(e.add(i),n?.toolUse)t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`tool_use`,id:n.toolUse.toolUseId,name:n.toolUse.name,input:{}}})}\n\n`);else if(n?.reasoningContent!==void 0){let e=typeof n?.reasoningContent?.signature==`string`?n.reasoningContent.signature:typeof n?.reasoningContent?.reasoningText?.signature==`string`?n.reasoningContent.reasoningText.signature:void 0;t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`thinking`,thinking:``,...e?{signature:e}:{}}})}\n\n`)}else t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`text`,text:``}})}\n\n`)}else if(r.contentBlockDelta){let n=r.contentBlockDelta.delta,i=r.contentBlockDelta.contentBlockIndex??0;if(!e.has(i)){e.add(i);let r=n?.toolUse===void 0?`text`:`tool_use`;t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:r===`text`?{type:`text`,text:``}:{type:`tool_use`,id:``,name:``,input:{}}})}\n\n`)}if(n?.text!==void 0)t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`text_delta`,text:n.text}})}\n\n`);else if(n?.reasoningContent?.text!==void 0)t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`thinking_delta`,thinking:n.reasoningContent.text}})}\n\n`);else if(typeof n?.reasoningContent?.signature==`string`||typeof n?.reasoningContent?.reasoningText?.signature==`string`){let e=typeof n.reasoningContent.signature==`string`?n.reasoningContent.signature:n.reasoningContent.reasoningText.signature;t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`signature_delta`,signature:e}})}\n\n`)}else n?.reasoningContent?.redactedContent===void 0?n?.toolUse?.input!==void 0&&t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`input_json_delta`,partial_json:n.toolUse.input}})}\n\n`):t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`redacted_thinking_delta`,data:n.reasoningContent.redactedContent}})}\n\n`)}else if(r.contentBlockStop)t.write(`data: ${JSON.stringify({type:`content_block_stop`,index:r.contentBlockStop.contentBlockIndex??0})}\n\n`);else if(r.messageStop){let e=Eee(r.messageStop.stopReason);t.write(`data: ${JSON.stringify({type:`message_delta`,delta:{stop_reason:e,stop_sequence:null}})}\n\n`),t.write(`data: ${JSON.stringify({type:`message_stop`})}\n\n`)}else if(r.metadata?.usage){let e=r.metadata.usage;t.write(`data: ${JSON.stringify({type:`message_delta`,usage:{input_tokens:e.inputTokens??0,output_tokens:e.outputTokens??0,cache_read_input_tokens:e.cacheReadInputTokens??0,cache_creation_input_tokens:e.cacheWriteInputTokens??0}})}\n\n`)}}t.end()}else{let e=new le(_),n=await u.send(e),r=(n.output?.message?.content||[]).map(e=>e.text===void 0?e.reasoningContent?.reasoningText?{type:`thinking`,thinking:e.reasoningContent.reasoningText.text||``,...typeof e.reasoningContent.reasoningText.signature==`string`?{signature:e.reasoningContent.reasoningText.signature}:{}}:e.reasoningContent?.redactedContent?{type:`redacted_thinking`,data:e.reasoningContent.redactedContent.data||``}:e.toolUse?{type:`tool_use`,id:e.toolUse.toolUseId,name:e.toolUse.name,input:e.toolUse.input}:{type:`text`,text:JSON.stringify(e)}:{type:`text`,text:e.text});t.json({id:Dee(),type:`message`,role:`assistant`,model:a,content:r,stop_reason:Eee(n.stopReason),stop_sequence:null,usage:{input_tokens:n.usage?.inputTokens??0,output_tokens:n.usage?.outputTokens??0,cache_read_input_tokens:n.usage?.cacheReadInputTokens??0,cache_creation_input_tokens:n.usage?.cacheWriteInputTokens??0}})}}catch(e){let n=e,r=e instanceof Error?e.message:String(e),i=n?.name??`UnknownError`,a=n?.$metadata?.httpStatusCode,o=n?.$metadata?.requestId;console.error(`Bedrock invoke error [${i} http=${a??`?`}] requestId=${o??`?`}];`,r);let s=i===`ThrottlingException`||a===429,c=r.includes(`expired`)||r.includes(`credentials`)?401:s?429:502;t.headersSent?(t.write(`data: ${JSON.stringify({type:`error`,error:{type:`server_error`,message:r}})}\n\n`),t.end()):t.status(c).json({error:`Bedrock invocation failed: ${r}`})}})}var Mee=/* @__PURE__ */ z(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(/* @__PURE__ */ new Date()).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(/* @__PURE__ */ Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1}var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=(/* @__PURE__ */ new Date()).getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),Nee=/* @__PURE__ */ z((e=>{var t=Mee();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),Pee=/* @__PURE__ */ z(((e,t)=>{t.exports=Nee()})),Fee=/* @__PURE__ */ z(((e,t)=>{let n=Pee(),r=[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`The Internet connection appears to be offline.`,`Network request failed`];var i=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};let a=(e,t,n)=>{let r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e},o=e=>r.includes(e),s=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};let c=n.operation(t);c.attempt(async n=>{try{r(await e(n))}catch(e){if(!(e instanceof Error)){s(/* @__PURE__ */ TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));return}if(e instanceof i)c.stop(),s(e.originalError);else if(e instanceof TypeError&&!o(e.message))c.stop(),s(e);else{a(e,n,t);try{await t.onFailedAttempt(e)}catch(e){s(e);return}c.retry(e)||s(c.mainError())}}})});t.exports=s,t.exports.default=s,t.exports.AbortError=i})),Iee=/* @__PURE__ */ z(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});f<p;++f)if(t=arguments[f],t!=null)for(n in t)r=l(d,n),i=l(t,n),d!==i&&(m&&i&&(s(i)||(a=o(i)))?(a?(a=!1,u=r&&o(r)?r:[]):u=r&&s(r)?r:{},c(d,{name:n,newValue:e(m,u,i)})):i!==void 0&&c(d,{name:n,newValue:i}));return d}})),Lee=/* @__PURE__ */ z(((e,t)=>{t.exports={name:`gaxios`,version:`7.3.1`,description:`A simple common HTTP client specifically for Google APIs and services.`,main:`build/cjs/src/index.js`,types:`build/cjs/src/index.d.ts`,files:[`build/`],exports:{".":{import:{types:`./build/esm/src/index.d.ts`,default:`./build/esm/src/index.js`},require:{types:`./build/cjs/src/index.d.ts`,default:`./build/cjs/src/index.js`}}},scripts:{lint:`gts check --no-inline-config`,test:`c8 mocha build/esm/test`,"presystem-test":`npm run compile`,"system-test":`mocha build/esm/system-test --timeout 80000`,compile:`tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs`,fix:`gts fix`,prepare:`npm run compile`,pretest:`npm run compile`,webpack:`webpack`,"prebrowser-test":`npm run compile`,"browser-test":`node build/browser-test/browser-test-runner.js`,docs:`jsdoc -c .jsdoc.js`,"samples-test":`cd samples/ && npm link ../ && npm test && cd ../`,prelint:`cd samples; npm link ../; npm install`,clean:`gts clean`},repository:{type:`git`,directory:`core/packages/gaxios`,url:`https://github.com/googleapis/google-cloud-node.git`},keywords:[`google`],engines:{node:`>=18`},author:`Google, LLC`,license:`Apache-2.0`,devDependencies:{"@babel/plugin-proposal-private-methods":`^7.18.6`,"@types/cors":`^2.8.6`,"@types/express":`^5.0.0`,"@types/extend":`^3.0.1`,"@types/mocha":`^10.0.10`,"@types/multiparty":`4.2.1`,"@types/mv":`^2.1.0`,"@types/ncp":`^2.0.8`,"@types/node":`^24.0.0`,"@types/sinon":`^21.0.0`,"@types/tmp":`^0.2.6`,assert:`^2.0.0`,browserify:`^17.0.0`,c8:`^10.1.3`,cors:`^2.8.5`,express:`^5.0.0`,gts:`^6.0.2`,"is-docker":`^3.0.0`,jsdoc:`^4.0.4`,"jsdoc-fresh":`^5.0.0`,"jsdoc-region-tag":`^4.0.0`,karma:`^6.0.0`,"karma-chrome-launcher":`^3.0.0`,"karma-coverage":`^2.0.0`,"karma-firefox-launcher":`^2.0.0`,"karma-mocha":`^2.0.0`,"karma-remap-coverage":`^0.1.5`,"karma-sourcemap-loader":`^0.4.0`,"karma-webpack":`^5.0.0`,mocha:`^11.1.0`,multiparty:`^4.2.1`,mv:`^2.1.1`,ncp:`^2.0.0`,nock:`14.0.5`,"null-loader":`^4.0.1`,"pack-n-play":`^4.0.0`,puppeteer:`^24.0.0`,sinon:`21.0.3`,"stream-browserify":`^3.0.0`,tmp:`0.2.7`,"ts-loader":`^9.5.2`,typescript:`5.8.3`,"undici-types":`^7.24.1`,webpack:`^5.97.1`,"webpack-cli":`^6.0.1`},dependencies:{extend:`^3.0.2`,"https-proxy-agent":`^7.0.1`,"node-fetch":`^3.3.2`},homepage:`https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios`}})),Ree=/* @__PURE__ */ z(((e,t)=>{t.exports={pkg:Lee()}})),zee=/* @__PURE__ */ z((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=a;let n=t(Iee()),r=t(Ree()).default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${r.name}-gaxios-error`),e.GaxiosError=class t extends Error{config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=r.version;static[Symbol.hasInstance](n){return n&&typeof n==`object`&&e.GAXIOS_ERROR_SYMBOL in n&&n[e.GAXIOS_ERROR_SYMBOL]===r.version?!0:Function.prototype[Symbol.hasInstance].call(t,n)}constructor(e,t,r,a){if(super(e,{cause:a}),this.config=t,this.response=r,this.error=a instanceof Error?a:void 0,this.config=(0,n.default)(!0,{},t),this.response&&(this.response.config=(0,n.default)(!0,{},this.response.config)),this.response){try{this.response.data=i(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}a instanceof DOMException?this.code=a.name:a&&typeof a==`object`&&`code`in a&&(typeof a.code==`string`||typeof a.code==`number`)&&(this.code=a.code)}static extractAPIErrorFromResponse(e,t=`The request failed`){let n=t;if(typeof e.data==`string`&&(n=e.data),e.data&&typeof e.data==`object`&&`error`in e.data&&e.data.error&&!e.ok){if(typeof e.data.error==`string`)return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error==`object`){n=`message`in e.data.error&&typeof e.data.error.message==`string`?e.data.error.message:n;let t=`status`in e.data.error&&typeof e.data.error.status==`string`?e.data.error.status:e.statusText,r=`code`in e.data.error&&typeof e.data.error.code==`number`?e.data.error.code:e.status;if(`errors`in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let t of e.data.error.errors)typeof t==`object`&&`message`in t&&typeof t.message==`string`&&i.push(t.message);return Object.assign({message:i.join(`
|
|
113
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n.id,n.groupId,n.timestamp,n.content,n.sender,n.channel??`chat`,+!!n.isFromMe,+!!n.isTrigger,n.attachments?JSON.stringify(n.attachments):null,n.a2uiAction?JSON.stringify(n.a2uiAction):null,n.a2uiEnvelopes?JSON.stringify(n.a2uiEnvelopes):null,n.freshContext?1:null,n.subagent?1:null);else{let r=Object.keys(n),i=r.map(()=>`?`).join(`, `),a=r.map(e=>{let t=n[e];return typeof t==`object`&&t?JSON.stringify(t):t});e.prepare(`INSERT OR REPLACE INTO ${t} (${r.join(`, `)}) VALUES (${i})`).run(...a)}return{result:void 0,onsuccess:null,onerror:null}},delete(n){return t===`config`?e.prepare(`DELETE FROM config WHERE key = ?`).run(n):t===`tasks`?e.prepare(`DELETE FROM tasks WHERE id = ?`).run(n):e.prepare(`DELETE FROM ${t} WHERE id = ?`).run(n),{result:void 0,onsuccess:null,onerror:null}}}}function ma(e,t,n,r){return new Promise((n,i)=>{try{let i=r(pa(e.db,t)),a=i.onsuccess;typeof a==`function`&&a(),n(i.result)}catch(e){i(e)}})}function ha(e,t,n,r){return e?ua(e)?ma(e,t,n,r):new Promise((i,a)=>{try{let o=e.transaction(t,n);if(!o)return a(/* @__PURE__ */ Error(`failed to get transaction`));let s=r(o.objectStore(t));s.onsuccess=()=>i(s.result),s.onerror=()=>a(s.error)}catch(e){a(e)}}):Promise.reject(/* @__PURE__ */ Error(`failed to get database, cannot update task.`))}var ga=R((()=>{la(),fa()})),_a=/* @__PURE__ */ pt({getConfig:()=>va});function va(e,t){return ha(e,`config`,`readonly`,e=>e.get(t)).then(e=>e?.value)}var ya=R((()=>{ga()}));function ba(e){let t=e.trim();if(!t)return()=>!1;if(t.startsWith(`/`)&&(t.endsWith(`/`)||/\/[gimuy]*$/.test(t)))try{let e=t.lastIndexOf(`/`),n=t.slice(1,e),r=t.slice(e+1),i=new RegExp(n,r||`i`);return e=>i.test(e)}catch{}if(t.includes(`^`)||t.includes(`$`)||t.includes(`(`)&&t.includes(`)`))try{let e=new RegExp(t,`i`);return t=>e.test(t)}catch{}if(t.startsWith(`*.`)){let e=t.slice(2).toLowerCase();return t=>{let n=t.toLowerCase();return n===e||n.endsWith(`.`+e)}}let n=t.toLowerCase();return e=>{let t=e.toLowerCase();return t===n||t.endsWith(`.`+n)}}var xa=R((()=>{}));function Sa(e){Ta=e.map(e=>ba(e)).filter(Boolean)}var Ca,wa,Ta,Ea=R((()=>{ta(),la(),ya(),xa(),Ca=[`youtube.com`,`youtube-nocookie.com`,`youtu.be`,`xt-ml.github.io`,`kherrick.github.io`],wa=[...Ca],Sa(wa)}));function Da(e){Ua=e.map(e=>ba(e)).filter(Boolean)}function Oa(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.toLowerCase().trim():``).filter(Boolean):typeof e==`string`?e.split(/[\n,]+/).map(e=>e.toLowerCase().trim()).filter(Boolean):[]}function ka(e){return Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean):typeof e==`string`?e.split(/[\n,]+/).map(e=>e.trim()).filter(Boolean):[]}function Aa(e){let t=Oa(e);Va=new Set(t)}function ja(e){let t=ka(e);Ha=t,Da(t)}function Ma(e){if(!e||typeof e!=`string`)return!1;let t=e.trim().toLowerCase();return!t.includes(`-`)||t===`shadow-claw`||t.startsWith(`shadow-claw-`)||t.startsWith(`sc-`)?!0:Va.has(t)}function Na(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();if(!t||/^(?:javascript|data|vbscript):/i.test(t))return!1;if(/^blob:/i.test(t)||t.startsWith(`/`)||t.startsWith(`./`)||t.startsWith(`../`))return!0;try{let e=typeof globalThis<`u`&&globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`,n=new URL(t,e);if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(typeof globalThis<`u`&&globalThis.location?.origin&&globalThis.location.origin!==`null`&&n.origin===globalThis.location.origin)return!0;let r=n.hostname.toLowerCase();return Ua.some(e=>e(r))}catch{return!1}}function Pa(e){if(!e||typeof e!=`object`)return;let t=e.allowedCustomElements||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedElements:void 0);t!==void 0&&Aa(t);let n=e.allowedCustomElementDomains||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedDomains:void 0);n!==void 0&&ja(n)}function Fa(e){Wa=e}function Ia(){if(typeof document>`u`)return;let e=document.getElementById(`shadow-claw-site-config`);if(e&&e.textContent)try{let t=JSON.parse(e.textContent);Pa(t),Wa?.(t)}catch{}}function La(){Ia(),!(Ka||typeof customElements>`u`||typeof customElements.define!=`function`)&&(Ga=customElements.define.bind(customElements),customElements.define=function(e,t,n){if(!Ma((e||``).toLowerCase().trim())){let t=`[Security] Registration blocked: <${e}> is not an approved custom element.`;throw console.error(t),Error(t)}return Ga(e,t,n)},Ka=!0)}function Ra(e=typeof document<`u`?document.documentElement:null){if(typeof MutationObserver>`u`||!e)return null;if(typeof e.querySelectorAll==`function`)try{e.querySelectorAll(`*`).forEach(e=>{let t=e.tagName?e.tagName.toLowerCase():``;t.includes(`-`)&&!Ma(t)&&(console.warn(`[Security] Removing existing unapproved custom element: <${t}>`),e.remove())})}catch{}let t=new MutationObserver(e=>{for(let t of e)t.addedNodes.forEach(e=>{if(e.nodeType===1){let t=e,n=t.tagName?t.tagName.toLowerCase():``;n.includes(`-`)&&!Ma(n)&&(console.warn(`[Security] Removing unapproved custom element: <${n}>`),t.remove())}})});return t.observe(e,{childList:!0,subtree:!0}),t}var za,Ba,Va,Ha,Ua,Wa,Ga,Ka,qa=R((()=>{xa(),za=[],Ba=[],Va=new Set(za.map(e=>e.toLowerCase().trim())),Ha=[...Ba],Ua=[],Da(Ha),Wa=null,Ga=null,Ka=!1}));function Ja(e){ro=Array.isArray(e)?e.map(e=>typeof e==`string`?e.trim():``).filter(Boolean).join(` `):typeof e==`string`&&e.trim()?e.trim():Qa}function Ya(e){if(!e||typeof e!=`object`)return;let t=e.allowedCustomElements||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedElements:void 0);t!==void 0&&Aa(t);let n=e.allowedCustomElementDomains||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedDomains:void 0);n!==void 0&&ja(n);let r=typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.scripts:void 0;r!==void 0&&Xa(r),e.security?.iframeSandbox===void 0?(e.security?.allowSameOrigin===!0||e.security?.allowIframeSameOrigin===!0)&&(ro.includes(`allow-same-origin`)||(ro=`${ro} allow-same-origin`.trim())):Ja(e.security.iframeSandbox),e.security?.workerSrc!==void 0&&(io=ka(e.security.workerSrc)),e.security?.connectSrc!==void 0&&(ao=ka(e.security.connectSrc)),e.security?.scriptSrc!==void 0&&(oo=ka(e.security.scriptSrc)),e.security?.styleSrc!==void 0&&(so=ka(e.security.styleSrc)),e.security?.imgSrc!==void 0&&(co=ka(e.security.imgSrc))}function Xa(e){lo=Array.isArray(e)?e.map(e=>{let t=typeof e==`string`?e:e?.src,n=typeof e==`object`&&e&&typeof e.id==`string`?e.id.trim():void 0,r=typeof e==`object`&&e&&typeof e.name==`string`?e.name.trim():void 0,i=typeof e==`object`&&e?!!(e.global||e.autoload):!1,a=typeof e==`object`&&e&&typeof e.type==`string`?e.type:void 0,o=typeof e==`object`&&e&&typeof e.async==`boolean`?e.async:void 0,s=typeof e==`object`&&e&&typeof e.defer==`boolean`?e.defer:void 0,c=typeof e==`object`&&e?!!e.hasInit:!1;return{src:t,...n?{id:n}:{},...r?{name:r}:{},...i?{global:!0,autoload:!0}:{},...a?{type:a}:{},...o?{async:o}:{},...s?{defer:s}:{},hasInit:c}}).filter(e=>typeof e.src==`string`&&Na(e.src)):[]}async function Za(e){try{let{getDb:t}=await Promise.resolve().then(()=>(la(),na)),{getConfig:n}=await Promise.resolve().then(()=>(ya(),_a)),r=e??await t();if(!r)return;let[i,a]=await Promise.all([n(r,`allowed_custom_elements`),n(r,`allowed_custom_element_host_patterns`)]);if(typeof i==`string`&&i.trim())try{Aa(JSON.parse(i))}catch{Aa(i)}if(typeof a==`string`&&a.trim())try{ja(JSON.parse(a))}catch{ja(a)}}catch(e){console.warn(`Failed to load custom element security from db:`,e)}}var Qa,$a,eo,to,no,ro,io,ao,oo,so,co,lo,uo=R((()=>{qa(),qa(),Ea(),yo(),Qa=`allow-modals allow-scripts allow-popups allow-popups-to-escape-sandbox`,$a=[`'self'`,`blob:`,`data:`],eo=[`'self'`,`blob:`,`data:`],to=[`'self'`,`'unsafe-inline'`,`https:`,`http:`],no=[`'self'`,`blob:`,`data:`,`https:`,`http:`],ro=Qa,[...$a],[...eo],[...to],[...no],Fa(Ya)})),fo=R((()=>{Ut(),Ea(),uo()}));function po(){let e=globalThis.trustedTypes;return!e||typeof e.createPolicy!=`function`?null:e}function mo(){if(vo!==void 0)return vo;let e=po();if(!e)return vo=null,vo;if(typeof e.getPolicy==`function`){let t=e.getPolicy(_o);if(t)return vo=t,vo}try{vo=e.createPolicy(_o,{createHTML:e=>e,createScriptURL:e=>e})}catch{vo=typeof e.getPolicy==`function`?e.getPolicy(_o)??null:null}return vo}function ho(){return _o}function go(e){let t=mo();return!t||typeof t.createScriptURL!=`function`?e:t.createScriptURL(e)}var _o,vo,yo=R((()=>{fo(),_o=`shadowclaw`}));yo();const bo=[`shadow-claw.config.json`,`shadow-claw-config.json`,`shadowclaw.config.json`,`site-config.json`,`pages/site-config.json`];function xo(e){try{if(p!==void 0&&typeof p.readFileSync==`function`&&p.existsSync(e)){let t=p.readFileSync(e,`utf8`);return JSON.parse(t)}}catch{}return null}function So(e){let t=[];if(e){let n=c.resolve(e);t.push(n),t.push(c.resolve(n,`..`)),t.push(c.resolve(n,`../..`))}if(n!==void 0&&typeof n.cwd==`function`){let e=c.resolve(n.cwd());t.includes(e)||t.push(e)}for(let e of t)for(let t of bo){let n=xo(c.resolve(e,t));if(n&&typeof n==`object`)return n}return null}function Co(e){let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;if(!e||typeof e!=`object`)return{scriptHosts:[],workerSources:[],connectSources:[]};let i=e.allowedCustomElementDomains||(typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.allowedDomains:void 0);if(Array.isArray(i)){for(let e of i)if(typeof e==`string`&&e.trim()){let n=e.trim();t.add(`https://${n}`),t.add(`http://${n}`),r.add(`https://${n}`),r.add(`http://${n}`)}}let a=typeof e.customElements==`object`&&!Array.isArray(e.customElements)?e.customElements?.scripts:void 0;if(Array.isArray(a))for(let e of a){let n=typeof e==`string`?e:e?.src;if(typeof n==`string`&&(n.startsWith(`http://`)||n.startsWith(`https://`)||n.startsWith(`//`)))try{let e=new URL(n.startsWith(`//`)?`https:${n}`:n).origin;t.add(e),r.add(e)}catch{}}if(e.security&&typeof e.security==`object`){if(Array.isArray(e.security.scriptSrc))for(let n of e.security.scriptSrc)typeof n==`string`&&n.trim()&&t.add(n.trim());if(Array.isArray(e.security.workerSrc))for(let t of e.security.workerSrc)typeof t==`string`&&t.trim()&&n.add(t.trim());if(Array.isArray(e.security.connectSrc))for(let t of e.security.connectSrc)typeof t==`string`&&t.trim()&&r.add(t.trim())}return{scriptHosts:Array.from(t),workerSources:Array.from(n),connectSources:Array.from(r)}}function wo(e={}){let t=e.includeTrustedTypes??!0,r=e.config;r===void 0&&e.rootPath?r=So(e.rootPath):r===void 0&&n!==void 0&&typeof n.cwd==`function`&&(r=So(n.cwd()));let i=Co(r),a=[`'self'`,`'unsafe-inline'`,...i.scriptHosts,...e.scriptSources??[]],o=[`'self'`,`blob:`,`data:`,...i.workerSources,...e.workerSources??[]],s=[`'self'`,`https:`,`wss:`,`ws:`,`data:`,...i.connectSources,...e.connectSources??[]],c=[`default-src 'self'`,`base-uri 'self'`,`frame-ancestors 'none'`,`frame-src 'self' https://www.youtube.com`,`object-src 'none'`,`img-src 'self' data: blob: https: http:`,`media-src 'self' data: blob: https: http:`,`font-src 'self' data: https://fonts.googleapis.com https://fonts.gstatic.com`,`style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://fonts.googleapis.com`,`script-src ${Array.from(new Set(a)).join(` `)}`,`worker-src ${Array.from(new Set(o)).join(` `)}`,`connect-src ${Array.from(new Set(s)).join(` `)}`,`report-uri /__cspreport`];return t&&c.push(`trusted-types ${ho()} shadowclaw-sandbox dompurify default`,`require-trusted-types-for 'script'`),c.join(`; `)}function To(e){return!/\bfirefox\//i.test(e)}function Eo(e={}){let t=wo({...e,includeTrustedTypes:e.includeTrustedTypes??!0}),n=wo({...e,includeTrustedTypes:!1});return(e,r,i)=>{let a=!To(e.get(`user-agent`)??``);r.setHeader(`Content-Security-Policy-Report-Only`,a?n:t),r.setHeader(`Origin-Agent-Cluster`,`?1`),i()}}function Do(e,t){return(n,r,i)=>{let a=n.headers[`access-control-request-private-network`]===`true`,o=!!n.headers.origin;(a||o)&&(t&&a&&e.log(`VERBOSE`,`[PNA] Allowing Private Network Access`),r.setHeader(`Access-Control-Allow-Private-Network`,`true`)),i()}}function Oo(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 ko(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 Ao(){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))}var jo=R((()=>{}));async function Mo(e,t={}){let{maxRetries:n=3,baseDelayMs:r=1e3,maxDelayMs:i=3e4,jitterFactor:a=.5,shouldRetry:o=()=>!0,onRetry:s,signal:c}=t,l;for(let t=0;t<=n;t++){if(c?.aborted)throw c.reason??new DOMException(`Aborted`,`AbortError`);try{return await e()}catch(e){if(l=e,e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`)throw e;if(t>=n||!o(e,t+1))break;let u=Oo(t,r,i,a);s&&s(t+1,n,u,e),await ko(u,c)}}throw l}function No(e){return/network|ECONNRESET|ECONNREFUSED|ETIMEDOUT|fetch failed|EAI_AGAIN|EAI_NONAME|getaddrinfo/i.test(e.message)}function Po(e){if(e instanceof TypeError)return!0;if(typeof e?.status==`number`)return Io.has(e.status);if(e instanceof Error){let t=e.message.match(/\b(4\d{2}|5\d{2})\b/);if(t)return Io.has(Number(t[1]));if(No(e))return!0}return!1}function Fo(e){return e instanceof TypeError?!0:e&&typeof e.status==`number`?Io.has(e.status):e instanceof Error&&No(e)}var Io,Lo=R((()=>{jo(),Io=/* @__PURE__ */ new Set([408,429,500,502,503,504])}));function eee(e){if(!e)return!1;let t=e.trim().toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`::1`||t===`[::1]`||/^127\.\d+\.\d+\.\d+$/.test(t)}function tee(e){if(!e)return!1;let t=e.trim().toLowerCase();return/^10\./.test(t)||/^192\.168\./.test(t)||/^172\.(1[6-9]|2\d|3[01])\./.test(t)||/^169\.254\./.test(t)}function nee(e){if(!e)return!1;let t=e.trim().toLowerCase();return eee(t)||tee(t)||!t.includes(`.`)?!0:Ro.some(e=>t.endsWith(e))}var Ro,ree=R((()=>{Ro=[`.local`,`.lan`,`.home`,`.internal`]}));function zo(e){return Array.isArray(e)?e[0]||``:typeof e==`string`?e:``}function Bo(e,t){let n=Number.parseInt(e??``,10);return!Number.isFinite(n)||n<=0?t:n}function iee(e,t){let n=Number.parseInt(e??``,10);return!Number.isFinite(n)||n<0?t:n}function aee(e){return/^\/telegram\/(?:bot|file\/bot)[^/]+\//.test(e)}function oee(e){try{let t=new URL(e);return t.hostname===`api.telegram.org`&&aee(t.pathname)&&(t.pathname=t.pathname.replace(/^\/telegram\/(?:bot|file\/bot)[^/]+\//,e=>e.includes(`/file/`)?`/telegram/file/bot[REDACTED]/`:`/telegram/bot[REDACTED]/`)),t.toString()}catch{return e.replace(/\/file\/bot[^/]+\//,`/file/bot[REDACTED]/`).replace(/\/bot[^/]+\//,`/bot[REDACTED]/`)}}function Vo(e){return nee(e)}async function Ho(e,t,n){if(!n||n<=0)return fetch(e,t);let r=new AbortController,i=t.signal,a=i?AbortSignal.any([i,r.signal]):r.signal,o=setTimeout(()=>{r.abort()},n);try{return await fetch(e,{...t,signal:a})}catch(e){throw e instanceof DOMException&&e.name===`AbortError`||e instanceof Error&&e.name===`AbortError`?Error(`Upstream request timed out after ${n}ms`):e}finally{clearTimeout(o)}}function see(e){return Array.isArray(e.tools)&&e.tools.length>0}function Uo(e){let t={...e};return delete t.tools,delete t.tool_choice,t}function Wo(e){return/does not support tools/i.test(e||``)}async function Go(e,t,n){let{targetUrl:r,method:i,headers:a,body:o,verbose:s,maxRetries:c,requestTimeoutMs:l,forwardAuth:u,allowPrivate:d,fromServiceWorker:f}=n;s&&console.log(`[Proxy] Forwarding ${i} request to: ${oee(r)}`);try{let e;try{e=new URL(r)}catch{t.status(400).json({error:`Invalid URL`});return}if(e.protocol!==`http:`&&e.protocol!==`https:`){t.status(400).json({error:`Unsupported URL scheme — only http and https are allowed`});return}if(Vo(e.hostname)&&!d&&!f){t.status(403).json({error:`Requests to private or internal addresses are blocked`});return}let n={...a};n[`User-Agent`]=Ko,delete n.host,delete n.origin,delete n.referer,u||(delete n.Authorization,delete n.authorization),delete n[`accept-encoding`],delete n[`content-length`],delete n.connection;let p=await Mo(()=>Ho(e.toString(),{method:i,headers:n,body:i===`GET`||i===`HEAD`?void 0:o instanceof N?o:o?.toString()},l),{maxRetries:c??3,shouldRetry:Po,onRetry:(e,t,n,r)=>{s&&console.log(`[Proxy] Retry ${e}/${t} after ${n}ms due to: ${r.message||r}`)}});t.status(p.status),p.headers.forEach((e,n)=>{let r=n.toLowerCase();r!==`content-encoding`&&r!==`transfer-encoding`&&r!==`content-length`&&r!==`connection`&&t.setHeader(n,e)}),t.setHeader(`Access-Control-Allow-Origin`,`*`);let m=N.from(await p.arrayBuffer());t.send(m)}catch(e){console.error(`Proxy error:`,e),t.status(500).json({error:`Proxy request failed`})}}async function cee(e,t,n){let{targetUrl:r,headers:i,body:a,verbose:o,maxRetries:s,requestTimeoutMs:c,allowPrivate:l,fromServiceWorker:u}=n;o&&console.log(`[Proxy] Streaming POST request to: ${oee(r)}`);try{let e;try{e=new URL(r)}catch{t.status(400).json({error:`Invalid URL`});return}if(e.protocol!==`http:`&&e.protocol!==`https:`){t.status(400).json({error:`Unsupported URL scheme — only http and https are allowed`});return}if(Vo(e.hostname)&&!l&&!u){t.status(403).json({error:`Requests to private or internal addresses are blocked`});return}let n={...i};delete n.host,delete n.origin,delete n.referer,delete n[`accept-encoding`],delete n[`content-length`],delete n.connection;let d=await Mo(()=>Ho(e.toString(),{method:`POST`,headers:{...n,"User-Agent":Ko},body:a},c),{maxRetries:s??3,shouldRetry:Po,onRetry:(e,t,n,r)=>{o&&console.log(`[Proxy] Streaming Retry ${e}/${t} after ${n}ms due to: ${r.message||r}`)}});if(!d.ok){let e=await d.text();t.status(d.status),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.json({error:e});return}if(t.status(200),t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.flushHeaders(),!d.body){t.end();return}let f=d.body.getReader();try{for(;;){let{done:e,value:n}=await f.read();if(e)break;t.write(N.from(n))}}finally{f.releaseLock()}t.end()}catch(e){console.error(`Streaming proxy error:`,e),t.headersSent?t.end():t.status(500).json({error:`Streaming proxy request failed`})}}var Ko,qo=R((()=>{Lo(),ree(),Ko=n.env.SHADOWCLAW_USER_AGENT||`ShadowClaw/1.0`}));qo();function lee(e,t){return(n,r,i)=>{let a=Date.now(),o=zo(n.headers[`x-forwarded-for`])||n.socket?.remoteAddress||n.ip||`unknown`,s=zo(n.headers.origin)||`-`,c=zo(n.headers.host)||`-`,l=zo(n.headers[`access-control-request-method`])||`-`,u=zo(n.headers[`access-control-request-headers`])||`-`,d=zo(n.headers[`access-control-request-private-network`])||`-`,f=n.originalUrl.replace(/\/telegram\/(?:bot|file\/bot)[^/]+\//,e=>e.startsWith(`/telegram/file/`)?`/telegram/file/bot[REDACTED]/`:`/telegram/bot[REDACTED]/`);e.log(`DEFAULT`,`--> ${n.method} ${f} ip=${o} host=${c} origin=${s}`),n.method===`OPTIONS`&&e.log(`DEFAULT`,` [Preflight] request-method=${l} request-headers=${u} private-network=${d}`),r.on(`finish`,()=>{let i=Date.now()-a,o=r.statusCode,s=r.getHeader(`access-control-allow-origin`)||`-`,c=r.getHeader(`access-control-allow-private-network`)||`-`;e.log(`DEFAULT`,`<-- ${n.method} ${f} ${o} (${i}ms) allow-origin=${s} allow-private-network=${c}`),t&&(e.log(`VERBOSE`,` Query:`,n.query),n.body&&Object.keys(n.body).length>0&&e.log(`VERBOSE`,` Body keys:`,Object.keys(n.body)))}),i()}}Ut();const uee=/* @__PURE__ */ new Set([`chat`,`files`,`pages`,`tasks`,`settings`,`tools`,`channels`]);function Jo(e,t){let n=(e.method||`GET`).toUpperCase();if(n!==`GET`&&n!==`HEAD`)return!1;let r=e.headers||{},i=String(r[`sec-fetch-dest`]||``).toLowerCase();if(i&&i!==`document`)return!1;let a=String(r[`sec-fetch-mode`]||``).toLowerCase(),o=String(r[`sec-fetch-user`]||``).toLowerCase(),s=i===`document`||a===`navigate`||o===`?1`,c=String(r.accept||``);if(!s&&!c.includes(`text/html`))return!1;let l=t.replace(/^\/+|\/+$/g,``);if(!l)return!1;let u=l.split(`/`).filter(Boolean),d=u[0]||``;return!(!uee.has(d)||d===`pages`&&(u.includes(`assets`)||zt(u[u.length-1])))}const Yo=/* @__PURE__ */ new Set([`.well-known`,`.agents`]);function dee(e){let t=e.split(`/`).filter(Boolean),n=t.filter(e=>e.length>0&&e.startsWith(`.`));if(n.length===0)return!0;if(n.length!==1)return!1;let r=n[0];return Yo.has(r)?t[0]===r||t[1]===r:!1}function fee(e){let t=e.split(`/`).filter(Boolean);return t.length>0&&Yo.has(t[0])||t.length>1&&Yo.has(t[1])}function pee(e,t){e.use(ie(/^(.+)\/index\.html$/,`$1/`)),e.use((e,n,r)=>{n.setHeader(`Access-Control-Allow-Origin`,`*`),n.setHeader(`Access-Control-Allow-Methods`,`GET, HEAD, OPTIONS`),n.setHeader(`Origin-Agent-Cluster`,`?1`);let i=new URL(e.originalUrl,`http://localhost`).pathname;if(!dee(i)){r();return}let a=fee(i)?{dotfiles:`allow`}:void 0;i.startsWith(`/assets/v86.9pfs/`)||i.startsWith(`/assets/v86.ext2/`)?n.setHeader(`Cache-Control`,`public, max-age=31536000, immutable`):n.setHeader(`Cache-Control`,`no-cache`);let o=new URL(e.url||`/`,`http://localhost`).pathname;if(Jo(e,i)||Jo(e,o)){n.sendFile(c.join(t,`index.html`));return}let s=c.join(t,o);p.stat(s,(l,u)=>{if(l||!u){let e=i.replace(/^\/[^/]+/,``);if(e){let r=c.join(t,e);try{if(p.existsSync(r)&&p.statSync(r).isFile()){let t=fee(e)?{dotfiles:`allow`}:void 0;t?n.sendFile(r,t):n.sendFile(r);return}}catch{}}if(i.startsWith(`/files/main/`)){let e=c.resolve(`pages/main`,i.slice(12));p.stat(e,(t,i)=>{!t&&i&&i.isFile()?n.sendFile(e):r()});return}if(i.startsWith(`/static-main/`)){let e=c.resolve(`pages/main`,i.slice(13));p.stat(e,(t,i)=>{!t&&i&&i.isFile()?n.sendFile(e):r()});return}if(i.startsWith(`/pages/`)){let e=c.resolve(`pages`,i.slice(7));p.stat(e,(t,i)=>{!t&&i&&i.isFile()?n.sendFile(e):r()});return}r()}else if(u.isDirectory()){let l=c.join(s,`index.html`);p.access(l,p.constants.F_OK,s=>{s?Jo(e,i)||Jo(e,o)?n.sendFile(c.join(t,`index.html`)):r():a?n.sendFile(l,a):n.sendFile(l)})}else a?n.sendFile(s,a):n.sendFile(s)})}),e.use(A.static(t,{etag:!0}))}qo();function mee(e,t={}){let n=t.verbose??!1,r=t.allowPrivateProxy??!1;e.all(/^\/proxy(\/(.*))?$/,async(e,t)=>{let i=typeof e.query.url==`string`?e.query.url:void 0,a=(e.body&&typeof e.body.url==`string`?e.body.url:void 0)||i;if(!a){let t=e.params[1];if(t){a=t;let n={...e.query};if(delete n.url,Object.keys(n).length>0){let e=a.includes(`?`)?`&`:`?`;a+=e+new URLSearchParams(n).toString()}}}if(!a)return t.status(400).json({error:`Missing 'url' parameter`});let o=(e.body&&typeof e.body.method==`string`&&e.body.method||e.method).toUpperCase(),s=!!(e.body&&e.body.headers&&typeof e.body.headers==`object`),c=(s?e.body.headers:e.headers)||{},l;e.body&&typeof e.body.body==`string`&&(l=e.body.body);let u=s&&!!(c.Authorization||c.authorization);await Go(e,t,{targetUrl:a,method:o,headers:c,body:l,verbose:n,forwardAuth:u,fromServiceWorker:s,allowPrivate:r})}),e.all(/^\/telegram\/((?:bot.*)|(?:file\/bot.*))$/,async(e,t)=>{t.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0`),t.setHeader(`Pragma`,`no-cache`),t.setHeader(`Expires`,`0`);let r=`https://api.telegram.org/${e.params[0]}${Object.keys(e.query).length>0?`?`+new URLSearchParams(e.query).toString():``}`,i=e.method.toUpperCase(),a=e.headers||{},o;if((a[`content-type`]||``).includes(`multipart/form-data`)){let t=[];for await(let n of e)t.push(n);o=N.concat(t)}else e.body&&typeof e.body.body==`string`?o=e.body.body:e.body&&typeof e.body==`object`&&Object.keys(e.body).length>0&&!(`url`in e.body)&&!(`method`in e.body)&&!(`headers`in e.body)&&(o=JSON.stringify(e.body));await Go(e,t,{targetUrl:r,method:i,headers:a,body:o,verbose:n})}),e.all(/^\/git-proxy\/(.*)/,async(e,t)=>{let r=e.params[0],i=Object.keys(e.query).length>0?`?`+new URLSearchParams(e.query).toString():``,a=`https://`+r+i,o=[];for await(let t of e)o.push(t);let s=N.concat(o);await Go(e,t,{targetUrl:a,method:e.method,headers:e.headers,body:s.length>0?s:void 0,verbose:n,forwardAuth:!0})})}const Xo=/* @__PURE__ */ new Map;function Zo(e){if(typeof e!=`string`||e.trim().length===0)return;let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``);if(t.includes(`claude-sonnet-5`)||t.includes(`claude-opus-4-7`)||t.includes(`claude-opus-5`)||t.includes(`claude-opus-4-8`)||t.includes(`claude-mythos-5`)||t.includes(`claude-mythos`)||t.includes(`claude-fable-5`)||t.includes(`claude-fable`))return!0;if(t.includes(`claude-sonnet-4-6`))return!1}function hee(e,t){if(typeof e!=`string`||e.trim().length===0)return;let n=Zo(e),r=Zo(t)??n;typeof r==`boolean`&&Xo.set(e.toLowerCase(),r)}function gee(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(Xo.has(n))return Xo.get(n)===!0;if(Xo.has(r))return Xo.get(r)===!0;let i=Zo(n);if(typeof i==`boolean`)return i;let a=Zo(r);return typeof a==`boolean`&&a}qo();const _ee=i.BEDROCK_REGION||``,vee=i.BEDROCK_PROFILE||``;function yee(e){return{region:_ee||zo(e.headers[`x-bedrock-region`])?.trim()||``,profile:vee||zo(e.headers[`x-bedrock-profile`])?.trim()||``,authMode:zo(e.headers[`x-bedrock-auth-mode`])?.trim()||`provider_chain`}}function bee(e,t){return t===`sso`?fe({profile:e}):de({profile:e})}function xee(e,t){if(/^[a-z]+\.anthropic\./.test(e))return e;let n=t.split(`-`)[0];if(!n)throw Error(`Bedrock region is not configured. Set BEDROCK_REGION or provide x-bedrock-region header.`);return`${n}.${e}`}function See(e){if(e.type===`text`)return{text:e.text};if(e.type===`image`){let t=e.source.data;return{image:{format:e.source.media_type.split(`/`)[1],source:{bytes:N.from(t,`base64`)}}}}if(e.type===`tool_use`)return{toolUse:{toolUseId:e.id,name:e.name,input:e.input}};if(e.type===`tool_result`){let t=typeof e.content==`string`?[{text:e.content}]:Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{text:e.text}:{text:JSON.stringify(e)}):[{text:JSON.stringify(e.content)}];return{toolResult:{toolUseId:e.tool_use_id,content:t}}}return e.type===`thinking`?typeof e.signature!=`string`||e.signature.length===0?void 0:{reasoningContent:{reasoningText:{text:e.thinking||``,signature:e.signature}}}:e.type===`redacted_thinking`?{reasoningContent:{redactedContent:{data:e.data||``}}}:{text:JSON.stringify(e)}}function Cee(e){return!!(e&&typeof e==`object`&&e.cache_control)}function Qo(e){let t=e?.ttl;return{cachePoint:{type:`default`,...t===`1h`||t===`5m`?{ttl:t}:{}}}}function wee(e=4){let t=e;return{take(){return t<=0?!1:(--t,!0)}}}function Tee(e,t){let n=`(continue)`;if(!Array.isArray(e)||e.length===0)return[];let r=(e||[]).map(e=>{let n=Array.isArray(e.content)?e.content:[{type:`text`,text:typeof e.content==`string`?e.content:``}],r=Array.isArray(e.content)?e.content.map(See):[{text:typeof e.content==`string`?e.content:``}],i=[];return r.forEach((e,r)=>{if(e===void 0||e&&typeof e.text==`string`&&e.text.trim().length===0)return;i.push(e);let a=n[r];Cee(a)&&t?.take()&&i.push(Qo(a.cache_control))}),{role:e.role,content:i}}),i=r.filter(e=>e.content.length>0);if(i.length===0&&r.length>0){let e=r[r.length-1];return[{role:e.role===`assistant`?`user`:e.role,content:[{text:n}]}]}let a=[];for(let e of i){let t=a[a.length-1];t&&t.role===e.role?t.content.push(...e.content):a.push(e)}return a.length>0&&a[0].role===`assistant`&&a.shift(),a.length===0?[{role:`user`,content:[{text:n}]}]:(a[a.length-1].role===`assistant`&&a.push({role:`user`,content:[{text:n}]}),a)}function Eee(e){switch(e){case`tool_use`:return`tool_use`;case`max_tokens`:return`max_tokens`;case`stop_sequence`:return`stop_sequence`;default:return`end_turn`}}function Dee(){return`msg_`+Math.random().toString(36).substring(2,10)}function Oee(e){if(typeof e!=`string`)return;let t=e.trim().toLowerCase();if(t===`low`||t===`medium`||t===`high`||t===`xhigh`||t===`max`)return t;if(t===`minimal`||t===`none`)return`low`}function kee(e,t){let n=typeof e==`number`&&Number.isFinite(e)?Math.max(1,e):0,r=n>0?n/(typeof t==`number`&&Number.isFinite(t)?Math.max(1,t):8192):.5;return r>=.95?`max`:r>=.85?`xhigh`:r>=.7?`high`:r>=.35?`medium`:`low`}function Aee(e,t,n){if(!e?.thinking)return;let r=e.thinking;if(!gee(t,n)||(typeof r?.type==`string`?r.type.toLowerCase():``)===`disabled`)return{thinking:r};let i=Oee(e?.output_config?.effort),a=kee(r?.budget_tokens,e?.max_tokens);return{thinking:{type:`adaptive`},output_config:{effort:i||a}}}function jee(e,t={}){e.get(`/bedrock-proxy/models`,async(e,t)=>{try{let n=yee(e);if(!n.region||!n.profile)return t.status(400).json({error:`Bedrock is not configured. Set BEDROCK_REGION and BEDROCK_PROFILE environment variables or provide Bedrock fallback settings in the UI.`});let r=new ae({region:n.region,credentials:bee(n.profile,n.authMode)}),i=((await r.send(new oe({byProvider:`Anthropic`}))).modelSummaries||[]).filter(e=>e.modelLifecycle?.status===`ACTIVE`).map(e=>(hee(e.modelId,e.modelName),{id:e.modelId,name:e.modelName}));try{let e=((await r.send(new se({}))).inferenceProfileSummaries||[]).filter(e=>e.status===`ACTIVE`).filter(e=>e.inferenceProfileId?.includes(`anthropic`)||e.inferenceProfileName?.toLowerCase().includes(`anthropic`)).map(e=>({id:e.inferenceProfileId||``,name:`${e.inferenceProfileName||`Unnamed Profile`} (Profile)`})).map(e=>(hee(e.id,e.name),e));i.push(...e)}catch(e){(e&&typeof e==`object`&&`name`in e?e.name:``)!==`AccessDeniedException`&&console.warn(`Failed to list Bedrock inference profiles:`,e instanceof Error?e.message:String(e))}t.json({models:i})}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Bedrock models discovery error:`,n),t.status(502).json({error:`Failed to list Bedrock models: ${n}`})}}),e.post(`/bedrock-proxy/invoke`,async(e,t)=>{try{let n=yee(e);if(!n.region||!n.profile)return t.status(400).json({error:`Bedrock is not configured. Set BEDROCK_REGION and BEDROCK_PROFILE environment variables or provide Bedrock fallback settings in the UI.`});let r=e.body;if(!r||typeof r!=`object`)return t.status(400).json({error:`Missing request body`});let i=r.model;if(typeof i!=`string`||!i.startsWith(`anthropic.`)&&!/^[a-z]+\.anthropic\./.test(i))return t.status(400).json({error:`Invalid model ID: '${String(i||``)}'. Must be an Anthropic Bedrock model ID.`});let a=xee(i,n.region),o=r.stream===!0,{model:s,stream:c,...l}=r,u=new ce({region:n.region,credentials:bee(n.profile,n.authMode),maxAttempts:3,retryMode:`adaptive`,requestHandler:{requestTimeout:6e4}}),d=wee(),f;if(l.tools&&l.tools.length>0){let e=[];for(let t of l.tools)e.push({toolSpec:{name:t.name,description:t.description,inputSchema:{json:t.input_schema}}}),Cee(t)&&d.take()&&e.push(Qo(t.cache_control));if(f={tools:e},l.tool_choice){let e=l.tool_choice;e.type===`tool`?f.toolChoice={tool:{name:e.name}}:e.type===`any`?f.toolChoice={any:{}}:f.toolChoice={auto:{}}}}let p=[];if(Array.isArray(l.system))for(let e of l.system){let t=typeof e?.text==`string`?e.text:``;t.trim().length!==0&&(p.push({text:t}),Cee(e)&&d.take()&&p.push(Qo(e.cache_control)))}else typeof l.system==`string`&&l.system.trim().length>0&&p.push({text:l.system});let m=p.length>0?p:void 0,h=Tee(l.messages||[],d),g={};l.max_tokens&&(g.maxTokens=l.max_tokens),l.temperature!==void 0&&(g.temperature=l.temperature),l.top_p!==void 0&&(g.topP=l.top_p),l.stop_sequences&&(g.stopSequences=l.stop_sequences);let _={modelId:a,messages:h,system:m,inferenceConfig:Object.keys(g).length>0?g:void 0,toolConfig:f,additionalModelRequestFields:Aee(l,i,a)};if(o){let e=new ue(_),n=await u.send(e);if(t.status(200),t.setHeader(`Content-Type`,`text/event-stream`),t.setHeader(`Cache-Control`,`no-cache`),t.setHeader(`Connection`,`keep-alive`),t.setHeader(`Access-Control-Allow-Origin`,`*`),t.flushHeaders(),t.write(`data: ${JSON.stringify({type:`message_start`,message:{id:Dee(),type:`message`,role:`assistant`,model:a,content:[],usage:{input_tokens:0,output_tokens:0}}})}\n\n`),n.stream){let e=/* @__PURE__ */ new Set;for await(let r of n.stream)if(r.contentBlockStart){let n=r.contentBlockStart.start,i=r.contentBlockStart.contentBlockIndex??0;if(e.add(i),n?.toolUse)t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`tool_use`,id:n.toolUse.toolUseId,name:n.toolUse.name,input:{}}})}\n\n`);else if(n?.reasoningContent!==void 0){let e=typeof n?.reasoningContent?.signature==`string`?n.reasoningContent.signature:typeof n?.reasoningContent?.reasoningText?.signature==`string`?n.reasoningContent.reasoningText.signature:void 0;t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`thinking`,thinking:``,...e?{signature:e}:{}}})}\n\n`)}else t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:{type:`text`,text:``}})}\n\n`)}else if(r.contentBlockDelta){let n=r.contentBlockDelta.delta,i=r.contentBlockDelta.contentBlockIndex??0;if(!e.has(i)){e.add(i);let r=n?.toolUse===void 0?`text`:`tool_use`;t.write(`data: ${JSON.stringify({type:`content_block_start`,index:i,content_block:r===`text`?{type:`text`,text:``}:{type:`tool_use`,id:``,name:``,input:{}}})}\n\n`)}if(n?.text!==void 0)t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`text_delta`,text:n.text}})}\n\n`);else if(n?.reasoningContent?.text!==void 0)t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`thinking_delta`,thinking:n.reasoningContent.text}})}\n\n`);else if(typeof n?.reasoningContent?.signature==`string`||typeof n?.reasoningContent?.reasoningText?.signature==`string`){let e=typeof n.reasoningContent.signature==`string`?n.reasoningContent.signature:n.reasoningContent.reasoningText.signature;t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`signature_delta`,signature:e}})}\n\n`)}else n?.reasoningContent?.redactedContent===void 0?n?.toolUse?.input!==void 0&&t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`input_json_delta`,partial_json:n.toolUse.input}})}\n\n`):t.write(`data: ${JSON.stringify({type:`content_block_delta`,index:i,delta:{type:`redacted_thinking_delta`,data:n.reasoningContent.redactedContent}})}\n\n`)}else if(r.contentBlockStop)t.write(`data: ${JSON.stringify({type:`content_block_stop`,index:r.contentBlockStop.contentBlockIndex??0})}\n\n`);else if(r.messageStop){let e=Eee(r.messageStop.stopReason);t.write(`data: ${JSON.stringify({type:`message_delta`,delta:{stop_reason:e,stop_sequence:null}})}\n\n`),t.write(`data: ${JSON.stringify({type:`message_stop`})}\n\n`)}else if(r.metadata?.usage){let e=r.metadata.usage;t.write(`data: ${JSON.stringify({type:`message_delta`,usage:{input_tokens:e.inputTokens??0,output_tokens:e.outputTokens??0,cache_read_input_tokens:e.cacheReadInputTokens??0,cache_creation_input_tokens:e.cacheWriteInputTokens??0}})}\n\n`)}}t.end()}else{let e=new le(_),n=await u.send(e),r=(n.output?.message?.content||[]).map(e=>e.text===void 0?e.reasoningContent?.reasoningText?{type:`thinking`,thinking:e.reasoningContent.reasoningText.text||``,...typeof e.reasoningContent.reasoningText.signature==`string`?{signature:e.reasoningContent.reasoningText.signature}:{}}:e.reasoningContent?.redactedContent?{type:`redacted_thinking`,data:e.reasoningContent.redactedContent.data||``}:e.toolUse?{type:`tool_use`,id:e.toolUse.toolUseId,name:e.toolUse.name,input:e.toolUse.input}:{type:`text`,text:JSON.stringify(e)}:{type:`text`,text:e.text});t.json({id:Dee(),type:`message`,role:`assistant`,model:a,content:r,stop_reason:Eee(n.stopReason),stop_sequence:null,usage:{input_tokens:n.usage?.inputTokens??0,output_tokens:n.usage?.outputTokens??0,cache_read_input_tokens:n.usage?.cacheReadInputTokens??0,cache_creation_input_tokens:n.usage?.cacheWriteInputTokens??0}})}}catch(e){let n=e,r=e instanceof Error?e.message:String(e),i=n?.name??`UnknownError`,a=n?.$metadata?.httpStatusCode,o=n?.$metadata?.requestId;console.error(`Bedrock invoke error [${i} http=${a??`?`}] requestId=${o??`?`}];`,r);let s=i===`ThrottlingException`||a===429,c=r.includes(`expired`)||r.includes(`credentials`)?401:s?429:502;t.headersSent?(t.write(`data: ${JSON.stringify({type:`error`,error:{type:`server_error`,message:r}})}\n\n`),t.end()):t.status(c).json({error:`Bedrock invocation failed: ${r}`})}})}var Mee=/* @__PURE__ */ z(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(/* @__PURE__ */ new Date()).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(/* @__PURE__ */ Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1}var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=(/* @__PURE__ */ new Date()).getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),Nee=/* @__PURE__ */ z((e=>{var t=Mee();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),Pee=/* @__PURE__ */ z(((e,t)=>{t.exports=Nee()})),Fee=/* @__PURE__ */ z(((e,t)=>{let n=Pee(),r=[`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`The Internet connection appears to be offline.`,`Network request failed`];var i=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};let a=(e,t,n)=>{let r=n.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=r,e},o=e=>r.includes(e),s=(e,t)=>new Promise((r,s)=>{t={onFailedAttempt:()=>{},retries:10,...t};let c=n.operation(t);c.attempt(async n=>{try{r(await e(n))}catch(e){if(!(e instanceof Error)){s(/* @__PURE__ */ TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));return}if(e instanceof i)c.stop(),s(e.originalError);else if(e instanceof TypeError&&!o(e.message))c.stop(),s(e);else{a(e,n,t);try{await t.onFailedAttempt(e)}catch(e){s(e);return}c.retry(e)||s(c.mainError())}}})});t.exports=s,t.exports.default=s,t.exports.AbortError=i})),Iee=/* @__PURE__ */ z(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=function(e){return typeof Array.isArray==`function`?Array.isArray(e):r.call(e)===`[object Array]`},s=function(e){if(!e||r.call(e)!==`[object Object]`)return!1;var t=n.call(e,`constructor`),i=e.constructor&&e.constructor.prototype&&n.call(e.constructor.prototype,`isPrototypeOf`);if(e.constructor&&!t&&!i)return!1;for(var a in e);return a===void 0||n.call(e,a)},c=function(e,t){i&&t.name===`__proto__`?i(e,t.name,{enumerable:!0,configurable:!0,value:t.newValue,writable:!0}):e[t.name]=t.newValue},l=function(e,t){if(t===`__proto__`){if(!n.call(e,t))return;if(a)return a(e,t).value}return e[t]};t.exports=function e(){var t,n,r,i,a,u,d=arguments[0],f=1,p=arguments.length,m=!1;for(typeof d==`boolean`&&(m=d,d=arguments[1]||{},f=2),(d==null||typeof d!=`object`&&typeof d!=`function`)&&(d={});f<p;++f)if(t=arguments[f],t!=null)for(n in t)r=l(d,n),i=l(t,n),d!==i&&(m&&i&&(s(i)||(a=o(i)))?(a?(a=!1,u=r&&o(r)?r:[]):u=r&&s(r)?r:{},c(d,{name:n,newValue:e(m,u,i)})):i!==void 0&&c(d,{name:n,newValue:i}));return d}})),Lee=/* @__PURE__ */ z(((e,t)=>{t.exports={name:`gaxios`,version:`7.3.1`,description:`A simple common HTTP client specifically for Google APIs and services.`,main:`build/cjs/src/index.js`,types:`build/cjs/src/index.d.ts`,files:[`build/`],exports:{".":{import:{types:`./build/esm/src/index.d.ts`,default:`./build/esm/src/index.js`},require:{types:`./build/cjs/src/index.d.ts`,default:`./build/cjs/src/index.js`}}},scripts:{lint:`gts check --no-inline-config`,test:`c8 mocha build/esm/test`,"presystem-test":`npm run compile`,"system-test":`mocha build/esm/system-test --timeout 80000`,compile:`tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs`,fix:`gts fix`,prepare:`npm run compile`,pretest:`npm run compile`,webpack:`webpack`,"prebrowser-test":`npm run compile`,"browser-test":`node build/browser-test/browser-test-runner.js`,docs:`jsdoc -c .jsdoc.js`,"samples-test":`cd samples/ && npm link ../ && npm test && cd ../`,prelint:`cd samples; npm link ../; npm install`,clean:`gts clean`},repository:{type:`git`,directory:`core/packages/gaxios`,url:`https://github.com/googleapis/google-cloud-node.git`},keywords:[`google`],engines:{node:`>=18`},author:`Google, LLC`,license:`Apache-2.0`,devDependencies:{"@babel/plugin-proposal-private-methods":`^7.18.6`,"@types/cors":`^2.8.6`,"@types/express":`^5.0.0`,"@types/extend":`^3.0.1`,"@types/mocha":`^10.0.10`,"@types/multiparty":`4.2.1`,"@types/mv":`^2.1.0`,"@types/ncp":`^2.0.8`,"@types/node":`^24.0.0`,"@types/sinon":`^21.0.0`,"@types/tmp":`^0.2.6`,assert:`^2.0.0`,browserify:`^17.0.0`,c8:`^10.1.3`,cors:`^2.8.5`,express:`^5.0.0`,gts:`^6.0.2`,"is-docker":`^3.0.0`,jsdoc:`^4.0.4`,"jsdoc-fresh":`^5.0.0`,"jsdoc-region-tag":`^4.0.0`,karma:`^6.0.0`,"karma-chrome-launcher":`^3.0.0`,"karma-coverage":`^2.0.0`,"karma-firefox-launcher":`^2.0.0`,"karma-mocha":`^2.0.0`,"karma-remap-coverage":`^0.1.5`,"karma-sourcemap-loader":`^0.4.0`,"karma-webpack":`^5.0.0`,mocha:`^11.1.0`,multiparty:`^4.2.1`,mv:`^2.1.1`,ncp:`^2.0.0`,nock:`14.0.5`,"null-loader":`^4.0.1`,"pack-n-play":`^4.0.0`,puppeteer:`^24.0.0`,sinon:`21.0.3`,"stream-browserify":`^3.0.0`,tmp:`0.2.7`,"ts-loader":`^9.5.2`,typescript:`5.8.3`,"undici-types":`^7.24.1`,webpack:`^5.97.1`,"webpack-cli":`^6.0.1`},dependencies:{extend:`^3.0.2`,"https-proxy-agent":`^7.0.1`,"node-fetch":`^3.3.2`},homepage:`https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios`}})),Ree=/* @__PURE__ */ z(((e,t)=>{t.exports={pkg:Lee()}})),zee=/* @__PURE__ */ z((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosError=e.GAXIOS_ERROR_SYMBOL=void 0,e.defaultErrorRedactor=a;let n=t(Iee()),r=t(Ree()).default.pkg;e.GAXIOS_ERROR_SYMBOL=Symbol.for(`${r.name}-gaxios-error`),e.GaxiosError=class t extends Error{config;response;code;status;error;[e.GAXIOS_ERROR_SYMBOL]=r.version;static[Symbol.hasInstance](n){return n&&typeof n==`object`&&e.GAXIOS_ERROR_SYMBOL in n&&n[e.GAXIOS_ERROR_SYMBOL]===r.version?!0:Function.prototype[Symbol.hasInstance].call(t,n)}constructor(e,t,r,a){if(super(e,{cause:a}),this.config=t,this.response=r,this.error=a instanceof Error?a:void 0,this.config=(0,n.default)(!0,{},t),this.response&&(this.response.config=(0,n.default)(!0,{},this.response.config)),this.response){try{this.response.data=i(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}a instanceof DOMException?this.code=a.name:a&&typeof a==`object`&&`code`in a&&(typeof a.code==`string`||typeof a.code==`number`)&&(this.code=a.code)}static extractAPIErrorFromResponse(e,t=`The request failed`){let n=t;if(typeof e.data==`string`&&(n=e.data),e.data&&typeof e.data==`object`&&`error`in e.data&&e.data.error&&!e.ok){if(typeof e.data.error==`string`)return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error==`object`){n=`message`in e.data.error&&typeof e.data.error.message==`string`?e.data.error.message:n;let t=`status`in e.data.error&&typeof e.data.error.status==`string`?e.data.error.status:e.statusText,r=`code`in e.data.error&&typeof e.data.error.code==`number`?e.data.error.code:e.status;if(`errors`in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let t of e.data.error.errors)typeof t==`object`&&`message`in t&&typeof t.message==`string`&&i.push(t.message);return Object.assign({message:i.join(`
|
|
114
114
|
`)||n,code:r,status:t},e.data.error)}return Object.assign({message:n,code:r,status:t},e.data.error)}}return{message:n,code:e.status,status:e.statusText}}};function i(e,t){switch(e){case`stream`:return t;case`json`:return JSON.parse(JSON.stringify(t));case`arraybuffer`:return JSON.parse(N.from(t).toString(`utf8`));case`blob`:return JSON.parse(t.text());default:return t}}function a(e){let t="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(e){e&&e.forEach((n,r)=>{(/^authentication$/i.test(r)||/^authorization$/i.test(r)||/secret/i.test(r))&&e.set(r,t)})}function r(e,n){if(typeof e==`object`&&e&&typeof e[n]==`string`){let r=e[n];(/grant_type=/i.test(r)||/assertion=/i.test(r)||/secret/i.test(r))&&(e[n]=t)}}function i(e){e&&typeof e==`object`&&(e instanceof FormData||e instanceof URLSearchParams||`forEach`in e&&`set`in e?e.forEach((n,r)=>{([`grant_type`,`assertion`].includes(r)||/secret/.test(r))&&e.set(r,t)}):(`grant_type`in e&&(e.grant_type=t),`assertion`in e&&(e.assertion=t),`client_secret`in e&&(e.client_secret=t)))}return e.config&&(n(e.config.headers),r(e.config,`data`),i(e.config.data),r(e.config,`body`),i(e.config.body),e.config.url.searchParams.has(`token`)&&e.config.url.searchParams.set(`token`,t),e.config.url.searchParams.has(`client_secret`)&&e.config.url.searchParams.set(`client_secret`,t)),e.response&&(a({config:e.response.config}),n(e.response.headers),e.response.bodyUsed&&(r(e.response,`data`),i(e.response.data))),e}})),Bee=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRetryConfig=t;async function t(e){let t=r(e);if(!e||!e.config||!t&&!e.config.retry)return{shouldRetry:!1};if(t||={},t.currentRetryAttempt=t.currentRetryAttempt||0,t.retry=t.retry===void 0||t.retry===null?3:t.retry,t.httpMethodsToRetry=t.httpMethodsToRetry||[`GET`,`HEAD`,`PUT`,`OPTIONS`,`DELETE`],t.noResponseRetries=t.noResponseRetries===void 0||t.noResponseRetries===null?2:t.noResponseRetries,t.retryDelayMultiplier=t.retryDelayMultiplier?t.retryDelayMultiplier:2,t.timeOfFirstRequest=t.timeOfFirstRequest?t.timeOfFirstRequest:Date.now(),t.totalTimeout=t.totalTimeout?t.totalTimeout:2**53-1,t.maxRetryDelay=t.maxRetryDelay?t.maxRetryDelay:2**53-1,t.statusCodesToRetry=t.statusCodesToRetry||[[100,199],[408,408],[429,429],[500,599]],e.config.retryConfig=t,!await(t.shouldRetry||n)(e))return{shouldRetry:!1,config:e.config};let a=i(t);e.config.retryConfig.currentRetryAttempt+=1;let o=t.retryBackoff?t.retryBackoff(e,a):new Promise(e=>{setTimeout(e,a)});return t.onRetryAttempt&&await t.onRetryAttempt(e),await o,{shouldRetry:!0,config:e.config}}function n(e){let t=r(e);if(e.config.signal?.aborted&&e.code!==`TimeoutError`||e.code===`AbortError`||!t||t.retry===0||!e.response&&(t.currentRetryAttempt||0)>=t.noResponseRetries||!t.httpMethodsToRetry||!t.httpMethodsToRetry.includes(e.config.method?.toUpperCase()||`GET`))return!1;if(e.response&&e.response.status){let n=!1;for(let[r,i]of t.statusCodesToRetry){let t=e.response.status;if(t>=r&&t<=i){n=!0;break}}if(!n)return!1}return t.currentRetryAttempt=t.currentRetryAttempt||0,!(t.currentRetryAttempt>=t.retry)}function r(e){if(e&&e.config&&e.config.retryConfig)return e.config.retryConfig}function i(e){let t=(e.currentRetryAttempt?0:e.retryDelay??100)+(e.retryDelayMultiplier**+e.currentRetryAttempt-1)/2*1e3,n=e.totalTimeout-(Date.now()-e.timeOfFirstRequest);return Math.min(t,n,e.maxRetryDelay)}})),Vee=/* @__PURE__ */ z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GaxiosInterceptorManager=void 0,e.GaxiosInterceptorManager=class extends Set{}})),Hee=/* @__PURE__ */ z(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Uee=/* @__PURE__ */ z(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Hee(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(/* @__PURE__ */ new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),Wee=/* @__PURE__ */ z(((e,t)=>{e.formatArgs=i,e.save=a,e.load=o,e.useColors=r,e.storage=s(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=/* @__PURE__ */ `#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function r(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function i(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function a(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function o(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&n!==void 0&&`env`in n&&(t=n.env.DEBUG),t}function s(){try{return localStorage}catch{}}t.exports=Uee()(e);let{formatters:c}=t.exports;c.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Gee=/* @__PURE__ */ pt({createSupportsColor:()=>es,default:()=>Yee});function $o(e,t=globalThis.Deno?globalThis.Deno.args:r.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,i=t.indexOf(n+e),a=t.indexOf(`--`);return i!==-1&&(a===-1||i<a)}function Kee(){if(!(`FORCE_COLOR`in ts))return;if(ts.FORCE_COLOR===`true`)return 1;if(ts.FORCE_COLOR===`false`)return 0;if(ts.FORCE_COLOR.length===0)return 1;let e=Math.min(Number.parseInt(ts.FORCE_COLOR,10),3);if([0,1,2,3].includes(e))return e}function qee(e){return e!==0&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Jee(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let i=Kee();i!==void 0&&(ns=i);let a=n?ns:i;if(a===0)return 0;if(n){if($o(`color=16m`)||$o(`color=full`)||$o(`color=truecolor`))return 3;if($o(`color=256`))return 2}if(`TF_BUILD`in ts&&`AGENT_NAME`in ts)return 1;if(e&&!t&&a===void 0)return 0;let o=a||0;if(ts.TERM===`dumb`)return o;if(r.platform===`win32`){let e=b.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in ts)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in ts)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in ts)||ts.CI_NAME===`codeship`?1:o;if(`TEAMCITY_VERSION`in ts)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ts.TEAMCITY_VERSION);if(ts.COLORTERM===`truecolor`||ts.TERM===`xterm-kitty`||ts.TERM===`xterm-ghostty`||ts.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in ts){let e=Number.parseInt((ts.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(ts.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(ts.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ts.TERM)||`COLORTERM`in ts?1:o}function es(e,t={}){return qee(Jee(e,{streamIsTTY:e&&e.isTTY,...t}))}var ts,ns,Yee,Xee=R((()=>{({env:ts}=r),$o(`no-color`)||$o(`no-colors`)||$o(`color=false`)||$o(`color=never`)?ns=0:($o(`color`)||$o(`colors`)||$o(`color=true`)||$o(`color=always`))&&(ns=1),Yee={stdout:es({isTTY:ve.isatty(1)}),stderr:es({isTTY:ve.isatty(2)})}})),Zee=/* @__PURE__ */ z(((e,t)=>{let r=B(`tty`),i=B(`util`);e.init=d,e.log=c,e.formatArgs=o,e.save=l,e.load=u,e.useColors=a,e.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=(Xee(),gt(Gee));t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(n.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),i=n.env[t];return i=/^(yes|on|true|enabled)$/i.test(i)?!0:/^(no|off|false|disabled)$/i.test(i)?!1:i===`null`?null:Number(i),e[r]=i,e},{});function a(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:r.isatty(n.stderr.fd)}function o(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
115
115
|
`).join(`
|
|
116
116
|
`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=s()+n+` `+e[0]}function s(){return e.inspectOpts.hideDate?``:(/* @__PURE__ */ new Date()).toISOString()+` `}function c(...t){return n.stderr.write(i.formatWithOptions(e.inspectOpts,...t)+`
|
|
@@ -3828,7 +3828,7 @@ actions:
|
|
|
3828
3828
|
createSurface — render a new surface (requires components array with a root component)
|
|
3829
3829
|
updateComponents — add or replace components on an existing surface
|
|
3830
3830
|
updateDataModel — update a single path in the data model (re-renders bound components)
|
|
3831
|
-
deleteSurface — remove the surface from the chat`,input_schema:{type:`object`,properties:{action:{type:`string`,enum:[`createSurface`,`updateComponents`,`updateDataModel`,`deleteSurface`],description:`The A2UI operation to perform`},surfaceId:{type:`string`,description:`Unique identifier for this surface. Use a stable ID so you can update it later.`},components:{type:`array`,description:`Flat array of component objects (required for createSurface/updateComponents). Each object MUST have an 'id' field and a 'component' field. The component with id 'root' is the tree root (required for createSurface). Component field values: Text | Row | Column | Button | TextField | Image | Icon | Video | AudioPlayer | List | Card | Tabs | Modal | Divider | CheckBox | ChoicePicker | Slider | DateTimeInput. Put all properties at the TOP LEVEL alongside 'component' and 'id'. DO NOT nest properties under a 'properties' key. Children arrays contain other component ID strings, not nested objects.`,items:{type:`object`,additionalProperties:!0}},dataModel:{type:`object`,description:`Initial data model for the surface (used with createSurface). Components can reference values via { "path": "/key" }.`,properties:{},additionalProperties:!0},path:{type:`string`,description:`JSON Pointer path to update (required for updateDataModel). Examples: "/result", "/user/name", "/count". Use "/" to replace the entire data model.`},value:{type:`string`,description:`New value to set at the specified path (used with updateDataModel). Omit to delete the key at the given path.`},surfaceProperties:{type:`object`,description:`Optional display/branding properties for this surface (e.g. agentDisplayName).`,properties:{},additionalProperties:!0}},required:[`action`,`surfaceId`]}}})),U5e,W5e=R((()=>{U5e={name:`spawn_subagent`,description:`Spawn one or more independent agent loops to work on subtasks in parallel and collect their results. Each subagent has its own tool-use loop, inherits the current API key, and can optionally override provider/model. and runs concurrently with other subagents via Promise.all. Use spawn_subagent when a task has independent parallel workstreams — for example: researching multiple topics simultaneously, processing a list of items in parallel, or delegating isolated subtasks to specialized agents. Do NOT use spawn_subagent for sequential tasks where step 2 depends on step 1's output — just do those steps directly. Do NOT use spawn_subagent for simple single-step work that takes one tool call. Use the parallel_agents field to fan out multiple subagents in a single call.`,input_schema:{type:`object`,properties:{prompt:{type:`string`,description:`The task prompt for a single subagent. Required unless using parallel_agents for multi-agent fan-out.`},tools:{type:`array`,description:`Optional list of tool names to allow in the subagent. If omitted, the subagent inherits the current tool set (minus spawn_subagent to prevent recursion). If provided, only these tools are available to the subagent.`,items:{type:`string`}},profile:{type:`string`,enum:[`current`,`fast`,`smart`,`powerful`],description:`Optional model profile to run the subagent on. Use 'fast' for simple/cheap subtasks (e.g., text formatting, basic search), 'smart' for moderate reasoning, 'powerful' for deep thinking or complex coding, and 'current' to inherit the parent model. Defaults to 'current'.`},workspace_group_id:{type:`string`,description:`Optional workspace group id override for subagent file/tool scope. Use 'parent' to reuse the parent workspace in automatic mode. When omitted, subagents use an isolated workspace by default.`},system_prompt:{type:`string`,description:`Optional system prompt override for the subagent. Defaults to the current system prompt.`},parallel_agents:{type:`array`,description:`Optional list of subagent specifications to run in parallel. When provided, all agents are launched concurrently and their results are combined. Note: There is a configurable maximum limit on parallel subagents (default 5). Each entry can specify a prompt, optional tools list, optional profile, and optional system_prompt.`,items:{type:`object`,properties:{prompt:{type:`string`,description:`The task prompt for this subagent.`},tools:{type:`array`,description:`Optional tool names for this subagent.`,items:{type:`string`}},profile:{type:`string`,enum:[`current`,`fast`,`smart`,`powerful`],description:`Optional model profile for this subagent. Defaults to 'current'.`},workspace_group_id:{type:`string`,description:`Optional workspace group id for this subagent. Use 'parent' for parent workspace in automatic mode.`},system_prompt:{type:`string`,description:`Optional system prompt override for this subagent.`}},required:[`prompt`]}}},required:[`prompt`]}}})),G5e,K5e=R((()=>{G5e={name:`get_current_time`,description:`Get the current date and time. Returns an ISO 8601 string representing the current date and time. Use this tool whenever you need to know the current time, instead of relying on shell tools which may be unavailable.`,input_schema:{type:`object`,properties:{timezone:{type:`string`,description:`Optional timezone to format the time in (e.g. 'America/New_York'). If omitted, returns UTC.`}}}}})),q5e,J5e,Y5e,X5e,Z5e,Q5e,$5e,e7e,t7e,n7e,r7e,i7e,a7e,o7e=R((()=>{q5e={name:`attach_file_to_chat`,description:`Prepare a workspace file for chat delivery by generating an exact markdown attachment snippet. Validates the file path and returns markdown that works for inline image rendering in ShadowClaw and attachment upload in external channels like Telegram/iMessage.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`},alt:{type:`string`,description:`Optional alt/caption text to use in the generated markdown`}},required:[`path`]}},J5e={name:`copy_file`,description:`Copy a file or directory in the group workspace to a new destination path. Supports copying single files or nested directories. Optionally supports copying between different conversation workspaces via source_group_id or target_group_id.`,input_schema:{type:`object`,properties:{source_path:{type:`string`,description:`Source file or directory path relative to workspace root`},target_path:{type:`string`,description:`Destination file or directory path relative to workspace root`},source_group_id:{type:`string`,description:`Optional source conversation group ID (defaults to current workspace)`},target_group_id:{type:`string`,description:`Optional target conversation group ID (defaults to current workspace)`}},required:[`source_path`,`target_path`]}},Y5e={name:`create_directory`,description:`Create a new directory (and any missing parent directories) in the group workspace.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`Directory path relative to the group workspace root`}},required:[`path`]}},X5e={name:`delete_file`,description:`Delete a file or directory from the group workspace. If the target path is a directory, it will be recursively deleted.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File or directory path relative to the group workspace root`}},required:[`path`]}},Z5e={name:`diff_files`,description:`Compare two files in the workspace and output the differences. Useful for comparing generated code, checking before patching, or finding changes outside of git repositories.`,input_schema:{type:`object`,properties:{path_a:{type:`string`,description:`Path to the first file relative to the group workspace root.`},path_b:{type:`string`,description:`Path to the second file relative to the group workspace root.`}},required:[`path_a`,`path_b`]}},Q5e={name:`list_files`,description:`List files and directories in the group workspace. Directory names end with /. Returns sorted entries.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`Directory path relative to workspace root (default: root)`}}}},$5e={name:`move_file`,description:`Move or rename a file or directory in the group workspace to a target path. Supports moving single files or nested directories. Optionally supports moving between different conversation workspaces via source_group_id or target_group_id.`,input_schema:{type:`object`,properties:{source_path:{type:`string`,description:`Source file or directory path relative to workspace root`},target_path:{type:`string`,description:`Destination file or directory path relative to workspace root`},source_group_id:{type:`string`,description:`Optional source conversation group ID (defaults to current workspace)`},target_group_id:{type:`string`,description:`Optional target conversation group ID (defaults to current workspace)`}},required:[`source_path`,`target_path`]}},e7e={name:`open_file`,description:`Open a file from the group workspace in the UI file viewer dialog. Use this only when the user explicitly asks to inspect a file visually with preview support. Do not use this tool to send or attach files in chat responses.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`}},required:[`path`]}},t7e={name:`patch_file`,description:`Make a targeted text replacement in a file. Finds the single occurrence of old_string and replaces it with new_string. Fails if old_string is not found or matches more than once. Use this instead of write_file when you only need to change part of a file — it is safer and works well with large files. Include enough surrounding context in old_string to make the match unique. IMPORTANT: You must provide 'path', 'old_string', and 'new_string' parameters.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`},old_string:{type:`string`,description:`The exact text to find in the file. Must match exactly once. Include 2-3 lines of surrounding context to ensure a unique match.`},new_string:{type:`string`,description:`The replacement text. Can be empty to delete old_string.`}},required:[`path`,`old_string`,`new_string`]}},n7e={name:`read_file`,description:`Read the contents of one or more files from the group workspace. IMPORTANT: You must specify either the 'path' parameter (for a single file) or the 'paths' parameter (an array of file paths for multiple files). When paths is provided, returns all file contents concatenated with --- filename --- headers. Prefer paths to batch reads in a single call. Image files (png, jpg, gif, webp, etc.) are returned as native image content that the model can see directly. Other binary files will be detected and an error returned suggesting alternative tools.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`Single file path relative to the group workspace root`},paths:{type:`array`,items:{type:`string`},description:`Array of file paths relative to the group workspace root. Use this to read multiple files in a single tool call.`}}}},r7e={name:`search_files`,description:`Search for a pattern (regex or exact text) in files across the workspace. Useful for finding code references, function definitions, or specific content without needing to rely on a shell environment.`,input_schema:{type:`object`,properties:{pattern:{type:`string`,description:`The text or regular expression to search for.`},path:{type:`string`,description:`Optional directory path to restrict the search to (e.g. 'src/'). Defaults to workspace root.`},file_glob:{type:`string`,description:`Optional simple glob to filter files (e.g. '*.ts'). Supports * as wildcard.`},is_regex:{type:`boolean`,description:`Set to true to parse the pattern as a regular expression.`}},required:[`pattern`]}},i7e={name:`send_file`,description:`Send a workspace file directly to connected peer(s) over the P2P (PeerJS/WebRTC) data channel. Use this when the user is in a peer conversation or room, or specify peer_id to send to a remote peer directly. The file is read from the current workspace and transferred over WebRTC in binary chunks so there is no size limit.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`},peer_id:{type:`string`,description:`Optional target PeerJS peer ID (or peer: groupId). If omitted, sends to the current peer/room conversation.`}},required:[`path`]}},a7e={name:`write_file`,description:`Write content to a file in the group workspace. Creates the file and any intermediate directories if they don't exist. Overwrites the file if it already exists. IMPORTANT: You must provide both the 'path' and 'content' parameters when calling this tool.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`},content:{type:`string`,description:`Content to write to the file`}},required:[`path`,`content`]}}})),s7e,c7e,l7e,u7e,d7e,f7e,p7e,m7e,h7e,g7e,_7e,v7e,y7e,b7e,x7e,S7e,C7e,w7e,T7e,E7e,D7e,O7e,k7e,A7e,j7e=R((()=>{s7e={name:`git_add`,description:`Stage files in a cloned repo. Accepts an array of filepaths. If omitted or empty, stages the repo root.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},filepaths:{type:`array`,items:{type:`string`},description:`Array of file paths to stage (relative to repo root). Pass a single item for one file.`}},required:[`repo`]}},c7e={name:`git_branch`,description:`Create a new branch in a cloned repo. Optionally switch to it immediately (like git checkout -b).`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name (returned by git_clone)`},name:{type:`string`,description:`Name for the new branch`},checkout:{type:`boolean`,description:`Switch to the new branch after creating it (default: false)`},start_point:{type:`string`,description:`Branch, tag, or commit SHA to branch from (default: HEAD)`}},required:[`repo`,`name`]}},l7e={name:`git_branches`,description:`List branches in a cloned repo. Current branch is marked with *.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},remote:{type:`boolean`,description:`List remote-tracking branches instead (default: false)`}},required:[`repo`]}},u7e={name:`git_checkout`,description:`Checkout a branch, tag, or commit SHA in a cloned repo.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name (returned by git_clone)`},ref:{type:`string`,description:`Branch name, tag, or commit SHA to checkout`}},required:[`repo`,`ref`]}},d7e={name:`git_clone`,description:`Clone a git repository into browser-persistent OPFS storage. Files are stored directly under repos/<repo-name>/ in the workspace and are immediately accessible to other git_* tools without any extra sync step. Works with public and private repos (GitHub, GitLab, GitHub Enterprise, etc.). If a Git PAT is configured in Settings, it is used automatically for authentication. Uses a CORS proxy. Returns the short repo name used for subsequent git_* operations.`,input_schema:{type:`object`,properties:{url:{type:`string`,description:`Full HTTPS repo URL (e.g. https://github.com/user/repo)`},name:{type:`string`,description:`Optional short repo name to use for the clone directory; defaults to the repository name parsed from the URL.`},branch:{type:`string`,description:`Branch to clone (default: default branch)`},depth:{type:`number`,description:`Shallow clone depth (default: 20)`}},required:[`url`]}},f7e={name:`git_commit`,description:`Stage all changes and create a commit in a cloned repo. Uses configured git author name/email or defaults.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},message:{type:`string`,description:`Commit message`},author_name:{type:`string`,description:`Author name (optional, uses configured default)`},author_email:{type:`string`,description:`Author email (optional, uses configured default)`}},required:[`repo`,`message`]}},p7e={name:`git_config`,description:`Get or set a git config value for a repo (e.g. user.name, user.email). Persistent per-repo identity avoids specifying author on every commit.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},command:{type:`string`,enum:[`get`,`set`],description:`Operation: get or set a config value`},key:{type:`string`,description:`Config key path (e.g. user.name, user.email, core.autocrlf)`},value:{type:`string`,description:`Value to set — required when command is set`}},required:[`repo`,`command`,`key`]}},m7e={name:`git_delete_branch`,description:`Delete a local branch from a cloned repo.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},name:{type:`string`,description:`Name of the branch to delete`}},required:[`repo`,`name`]}},h7e={name:`git_delete_repo`,description:"Delete the git metadata for a cloned repository while leaving the working tree files in place. Use this to clean up corrupted or stale repos that fail to re-clone. The repo directory remains under repos/<repo>, but the `.git/` metadata is removed.",input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name (as returned by git_clone or git_list_repos)`}},required:[`repo`]}},g7e={name:`git_diff`,description:`Show changed files between HEAD and working tree, or between two refs.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref1:{type:`string`,description:`First ref (default: HEAD)`},ref2:{type:`string`,description:`Second ref (if omitted, diffs HEAD vs workdir)`}},required:[`repo`]}},_7e={name:`git_fetch`,description:`Fetch commits from the remote without merging. Safe for inspecting remote state before deciding to merge or rebase.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},branch:{type:`string`,description:`Remote branch to fetch (default: default branch)`},remote:{type:`string`,description:`Remote name (default: origin)`}},required:[`repo`]}},v7e={name:`git_init`,description:`Initialize a new empty git repository in browser storage. Use this to create a new project from scratch before using git_push to push to a remote.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short name for the new repo (used for all subsequent git_ operations)`}},required:[`repo`]}},y7e={name:`git_list_repos`,description:`List all git repositories currently cloned in browser storage.`,input_schema:{type:`object`,properties:{}}},b7e={name:`git_log`,description:`Show the commit log for a cloned repo. Returns commit SHA, date, author, and message.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref:{type:`string`,description:`Ref to log from (default: HEAD)`},depth:{type:`number`,description:`Number of commits to show (default: 10)`}},required:[`repo`]}},x7e={name:`git_merge`,description:`Merge a branch or ref into the current branch. Supports fast-forward and three-way merges. If the merge has conflicts, a detailed report is returned with the conflicted files and their conflict regions inline. To resolve: use read_file on each conflicted file, then write_file with the complete resolved content (no conflict markers). After all files are resolved, use git_add for each, then git_commit. Do NOT use bash/sed for conflict resolution.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},theirs:{type:`string`,description:`Branch name, tag, or commit SHA to merge into the current branch`},author_name:{type:`string`,description:`Author name (optional, uses configured default)`},author_email:{type:`string`,description:`Author email (optional, uses configured default)`}},required:[`repo`,`theirs`]}},S7e={name:`git_pull`,description:`Fetch and merge commits from the remote repository. Uses configured git author name/email for merge commits if needed.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},branch:{type:`string`,description:`Branch to pull (default: current branch)`},author_name:{type:`string`,description:`Author name (optional, uses configured default)`},author_email:{type:`string`,description:`Author email (optional, uses configured default)`}},required:[`repo`]}},C7e={name:`git_push`,description:`Push commits to the remote repository. Requires a GitHub personal access token (PAT) to be configured. The token is loaded from the encrypted credential store.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},branch:{type:`string`,description:`Local branch to push (default: current branch)`},remote_ref:{type:`string`,description:`Remote branch name to push to, if different from local branch. Example: push local 'feature-rebased' to remote 'feature/original'.`},force:{type:`boolean`,description:`Force push (default: false)`},tags:{type:`boolean`,description:`Also push all local tags to the remote (default: false)`}},required:[`repo`]}},w7e={name:`git_read_file_at_ref`,description:`Read a file's contents at a specific ref (branch, tag, or commit SHA) without checking it out. Useful for code review across branches.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref:{type:`string`,description:`Branch name, tag, or commit SHA`},filepath:{type:`string`,description:`File path relative to the repo root`}},required:[`repo`,`ref`,`filepath`]}},T7e={name:`git_remote`,description:`Manage git remotes: list, add, or remove a remote in a cloned repo.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},command:{type:`string`,enum:[`list`,`add`,`remove`],description:`Operation to perform`},remote:{type:`string`,description:`Remote name (e.g. origin, upstream) — required for add/remove`},url:{type:`string`,description:`Remote URL — required for add`}},required:[`repo`,`command`]}},E7e={name:`git_reset`,description:`Reset the current branch HEAD to a specific ref or commit SHA. Updates the branch pointer and checks out the target, discarding local changes. Equivalent to 'git reset --hard <ref>'.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref:{type:`string`,description:`Branch name, tag, or commit SHA to reset to`}},required:[`repo`,`ref`]}},D7e={name:`git_show`,description:`Show the metadata and diff of a specific commit. Returns author, date, message, and a unified diff against the parent commit.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref:{type:`string`,description:`Commit SHA, branch, or tag to inspect (default: HEAD)`}},required:[`repo`,`ref`]}},O7e={name:`git_status`,description:`Show the working tree status of a cloned repo. Reports modified, added, deleted, and unstaged files.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`}},required:[`repo`]}},k7e={name:`git_tag`,description:`Create a lightweight or annotated tag at HEAD. Use git_push with tags=true to push tags to the remote.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},tag:{type:`string`,description:`Tag name (e.g. v1.2.3)`},message:{type:`string`,description:`Annotation message — if provided, creates an annotated tag; otherwise lightweight`},author_name:{type:`string`,description:`Tagger name (optional, uses configured default)`},author_email:{type:`string`,description:`Tagger email (optional, uses configured default)`}},required:[`repo`,`tag`]}},A7e={name:`git_unstage`,description:`Remove one or more staged files from the index without touching the working tree. The inverse of git_add — use to undo accidental staging.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},filepath:{type:`string`,description:`File path or array of file paths to unstage (relative to repo root)`}},required:[`repo`,`filepath`]}}})),M7e,N7e,P7e,F7e,I7e,L7e,R7e,z7e=R((()=>{M7e={name:`create_task`,description:`Create a scheduled recurring task. The task will run automatically on the specified schedule and send the result back to this group. Uses cron expressions (minute hour day-of-month month day-of-week).`,input_schema:{type:`object`,properties:{schedule:{type:`string`,description:`Cron expression, e.g. "0 9 * * 1-5" for 9am weekdays`},prompt:{type:`string`,description:`The prompt/instruction to execute on each run (used if type is 'prompt')`},type:{type:`string`,enum:[`prompt`,`tools`],description:`The type of task to create. Defaults to 'prompt'.`},tools:{type:`array`,description:`A list of tools to execute sequentially (used if type is 'tools')`,items:{type:`object`,properties:{name:{type:`string`},input:{type:`object`}},required:[`name`,`input`]}},name:{type:`string`,description:`The optional title/name for the task, helping to identify its purpose.`}},required:[`prompt`,`type`]}},N7e={name:`list_tasks`,description:`List all scheduled recurring tasks for this group. Returns a list of tasks with their IDs, schedules, and prompts.`,input_schema:{type:`object`,properties:{}}},P7e={name:`update_task`,description:`Update an existing scheduled task's schedule or prompt.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to update`},schedule:{type:`string`,description:`Standard cron expression (e.g. '0 9 * * *'). Leave empty for an unscheduled task.`},prompt:{type:`string`,description:`New prompt/instruction (optional)`},type:{type:`string`,enum:[`prompt`,`tools`],description:`New task type (optional)`},tools:{type:`array`,description:`New list of tools (optional)`,items:{type:`object`,properties:{name:{type:`string`},input:{type:`object`}},required:[`name`,`input`]}},enabled:{type:`boolean`,description:`Whether the task is enabled (optional)`},name:{type:`string`,description:`New name/title for the task (optional).`}},required:[`id`]}},F7e={name:`delete_task`,description:`Delete a scheduled task by its ID.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to delete`}},required:[`id`]}},I7e={name:`enable_task`,description:`Enable a scheduled task so it runs on its schedule.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to enable`}},required:[`id`]}},L7e={name:`disable_task`,description:`Disable a scheduled task so it stops running.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to disable`}},required:[`id`]}},R7e={name:`run_task`,description:`Immediately trigger a scheduled task by its ID, outside of its normal cron schedule. Use this to manually fire a task on demand. Use list_tasks to find the task ID first.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to run immediately`}},required:[`id`]}}})),B7e,V7e,H7e,U7e,W7e=R((()=>{B7e={name:`create_room`,description:`Create a new multi-party room (a shared PeerJS conversation) hosted by this device. Other agents or humans can then be invited to participate. Returns the room so you can share or invite peers into it.`,input_schema:{type:`object`,properties:{name:{type:`string`,description:`A human-readable name for the room.`}},required:[`name`]}},V7e={name:`invite_to_room`,description:`Invite a peer (another agent or human, identified by their PeerJS peer ID) into a room so they can join the shared conversation. If room_id is omitted and the current conversation is a room, that room is used.`,input_schema:{type:`object`,properties:{peer_id:{type:`string`,description:`The PeerJS peer ID of the participant to invite.`},room_id:{type:`string`,description:`The room id to invite into. Defaults to the current room conversation.`}},required:[`peer_id`]}},H7e={name:`leave_room`,description:`Leave a room. If you are the host, the room is disbanded for all members. If room_id is omitted and the current conversation is a room, that room is used.`,input_schema:{type:`object`,properties:{room_id:{type:`string`,description:`The room id to leave. Defaults to the current room conversation.`}}}},U7e={name:`list_room_members`,description:`List the participants (humans and agents) currently in a room. If room_id is omitted and the current conversation is a room, that room is used.`,input_schema:{type:`object`,properties:{room_id:{type:`string`,description:`The room id to inspect. Defaults to the current room conversation.`}}}}})),G7e,K7e,q7e,J7e,Y7e,X7e,Z7e=R((()=>{G7e={name:`summarize_text`,description:`Summarize text using Web Platform's Summarizer API (or polyfill fallback). Produces key points, TLDR, teaser, or headline.`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text content to summarize.`},type:{type:`string`,enum:[`key-points`,`tldr`,`teaser`,`headline`],description:`The summary type (default: key-points).`},format:{type:`string`,enum:[`plain-text`,`markdown`],description:`Output format (default: markdown).`},length:{type:`string`,enum:[`short`,`medium`,`long`],description:`Summary length (default: short).`},preference:{type:`string`,enum:[`capability`,`speed`,`auto`],description:`Summarizer performance preference (default: auto).`},context:{type:`string`,description:`Optional background context for summarization.`},outputLanguage:{type:`string`,description:`Optional target language code (e.g. 'en', 'es').`},sharedContext:{type:`string`,description:`Optional shared context passed to the underlying model.`},overridePrompt:{type:`string`,description:`Optional custom system prompt overriding default summarization instructions.`}},required:[`text`]}},K7e={name:`write_text`,description:`Generate or draft text using Web Platform's Writer API (or polyfill fallback).`,input_schema:{type:`object`,properties:{prompt:{type:`string`,description:`The prompt or writing instructions.`},tone:{type:`string`,enum:[`formal`,`neutral`,`casual`],description:`Tone for drafting (default: neutral).`},format:{type:`string`,enum:[`plain-text`,`markdown`],description:`Output format (default: plain-text).`},length:{type:`string`,enum:[`short`,`medium`,`long`],description:`Target length (default: short).`},context:{type:`string`,description:`Optional background context for writing.`},outputLanguage:{type:`string`,description:`Optional target language code (e.g. 'en', 'es').`},sharedContext:{type:`string`,description:`Optional shared context passed to the underlying model.`}},required:[`prompt`]}},q7e={name:`rewrite_text`,description:`Rewrite or rephrase text using Web Platform's Rewriter API (or polyfill fallback). Can adjust tone or length.`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text to rewrite.`},tone:{type:`string`,enum:[`as-is`,`more-formal`,`more-casual`],description:`Tone adjustment (default: as-is).`},format:{type:`string`,enum:[`as-is`,`plain-text`,`markdown`],description:`Format adjustment (default: as-is).`},length:{type:`string`,enum:[`as-is`,`shorter`,`longer`],description:`Length adjustment (default: as-is).`},context:{type:`string`,description:`Optional background context for rewriting.`},outputLanguage:{type:`string`,description:`Optional target language code (e.g. 'en', 'es').`},sharedContext:{type:`string`,description:`Optional shared context passed to the underlying model.`}},required:[`text`]}},J7e={name:`proofread_text`,description:`Proofread and correct grammar, spelling, and phrasing errors using Web Platform's Proofreader API (or polyfill fallback).`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text to proofread.`},context:{type:`string`,description:`Optional background context for proofreading.`}},required:[`text`]}},Y7e={name:`detect_language`,description:`Detect the language of input text using Web Platform's Language Detector API (or polyfill fallback).`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text to analyze for language detection.`}},required:[`text`]}},X7e={name:`translate_text`,description:`Translate text using Web Platform's Translator API (or polyfill fallback).`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text to translate.`},sourceLanguage:{type:`string`,description:`Source language BCP 47 code (e.g. 'en', 'es', 'ja').`},targetLanguage:{type:`string`,description:`Target language BCP 47 code (e.g. 'en', 'es', 'ja').`}},required:[`text`,`sourceLanguage`,`targetLanguage`]}}})),xO,SO,Q7e=R((()=>{xO={name:`prompt_peer`,description:`Send a prompt or message directly to another connected ShadowClaw peer or agent over WebRTC, triggering their orchestration loop and returning their answer. Use this to ask another agent to perform a task, answer a question, or analyze data.`,input_schema:{type:`object`,properties:{peer_id:{type:`string`,description:`The PeerJS peer ID or client ID of the target agent to prompt.`},prompt:{type:`string`,description:`The prompt, question, or instruction for the peer agent.`},timeout_seconds:{type:`number`,description:`Optional timeout in seconds to wait for the peer agent's response (default: 120).`}},required:[`peer_id`,`prompt`]}},SO={name:`list_peers`,description:`List the currently connected peers or clients available over WebRTC and the control plane. Returns peer IDs and device labels so you know which peers you can prompt or collaborate with.`,input_schema:{type:`object`,properties:{}}}})),$7e,e9e=R((()=>{$7e={name:`activate_skill`,description:`Load the full instructions for a workspace skill when its description matches the current task.`,input_schema:{type:`object`,properties:{name:{type:`string`,description:`The exact skill name from the available skills catalog.`}},required:[`name`]}}})),t9e=/* @__PURE__ */ pt({TOOL_DEFINITIONS:()=>CO,activate_skill:()=>$7e,list_peers:()=>SO,prompt_peer:()=>xO}),CO,wO=R((()=>{m5e(),_5e(),x5e(),T5e(),D5e(),A5e(),N5e(),F5e(),R5e(),H5e(),W5e(),K5e(),o7e(),j7e(),z7e(),W7e(),Z7e(),Q7e(),e9e(),CO=[g5e,q5e,p5e,h5e,J5e,Y5e,B7e,M7e,X5e,F7e,Y7e,Z5e,L7e,y5e,b5e,I7e,C5e,S5e,G5e,s7e,c7e,l7e,u7e,d7e,f7e,p7e,m7e,h7e,g7e,_7e,v7e,y7e,b7e,x7e,S7e,C7e,w7e,T7e,E7e,D7e,O7e,k7e,A7e,V7e,E5e,H7e,B5e,Q5e,SO,U7e,N7e,M5e,v5e,j5e,$5e,e7e,t7e,xO,J7e,n7e,k5e,O5e,V5e,q7e,R7e,r7e,i7e,L5e,I5e,U5e,G7e,X7e,P5e,P7e,w5e,a7e,K7e]})),TO=R((()=>{wO()})),EO,DO=R((()=>{EO={id:`__builtin_default`,name:`Default`,providerId:`prompt_api`,enabledToolNames:[`javascript`,`list_files`,`open_file`,`read_file`,`write_file`],customTools:[],systemPromptOverride:"You are a helpful coding assistant.\nContent intended to be rendered as a `Page` (HTML or Markdown) SHOULD include frontmatter (title, created, updated, and slug).\nHTML content intended to be rendered as a `Page` SHOULD USE `<article><h2>${subTitle}</h2>...</article>` for its main body content."}}));function n9e(e,t){if(!t||typeof t!=`object`)throw Error(`Tool at ${e} must be a JSON object`);let n=t,r=typeof n.name==`string`?n.name.trim():``,i=typeof n.description==`string`?n.description.trim():``,a=n.input_schema??n.parameters,o=n.execution??n.evaluation;if(!kO.test(r))throw Error(`Tool name is invalid: ${r||`(missing)`}`);if(!i)throw Error(`Tool ${r} requires a description`);if(!a||typeof a!=`object`)throw Error(`Tool ${r} requires input_schema`);if(!o||typeof o!=`object`)throw Error(`Tool ${r} requires execution`);let s=o,c=s.type;if(c!==`bash`&&c!==`javascript`&&c!==`tool`)throw Error(`Tool ${r} execution type must be bash, javascript, or tool`);if(c===`tool`){if(typeof s.name!=`string`||!kO.test(s.name))throw Error(`Tool ${r} execution requires a valid tool name`);return{name:r,description:i,input_schema:a,execution:{type:c,name:s.name,...s.input&&typeof s.input==`object`?{input:s.input}:{}},path:e}}let l=c===`bash`?`command`:`code`,u=s[l]??s.expression;if(typeof u!=`string`||u.trim()===``)throw Error(`Tool ${r} execution requires ${l}`);return{name:r,description:i,input_schema:a,execution:{type:c,[l]:u},path:e}}async function OO(e,t=un){let n=[],r=[],i=t===`br:main`?[un]:[t,un];for(let t of i)try{let i=await Cp(e,t),a=[];async function o(e,t){for await(let[n,r]of e.entries()){let e=`${t}/${n}`;r.kind===`directory`?await o(r,e):n.endsWith(`.json`)&&e.startsWith(`.agents/tools/`)&&a.push(e)}}try{await o(await(await i.getDirectoryHandle(`.agents`)).getDirectoryHandle(`tools`),`.agents/tools`)}catch{continue}for(let i of a.sort())try{let r=n9e(i,JSON.parse(await Dp(e,t,i)));n.some(e=>e.name===r.name)||n.push(r)}catch(e){r.push(e instanceof Error?e.message:String(e))}}catch{}return{tools:n,diagnostics:r}}async function r9e(e,t=un,n){try{let{tools:r}=await OO(e,t),i=r.find(e=>e.name===n)||null;if(!i)return null;let a=await va(e,V.DECLARATIVE_TOOLS_ENABLED);return Array.isArray(a)&&!a.includes(n)?null:i}catch{return null}}var kO,AO=R((()=>{An(),ya(),wp(),Op(),kO=/^[a-z][a-z0-9_]{0,63}$/}));async function i9e(e){if(typeof e==`string`)return new TextEncoder().encode(e).buffer;if(typeof Blob<`u`&&e instanceof Blob)return e.arrayBuffer();if(e instanceof ArrayBuffer)return e.slice(0);if(ArrayBuffer.isView(e)){let{buffer:t,byteOffset:n,byteLength:r}=e;return t.slice(n,n+r)}return/* @__PURE__ */ new ArrayBuffer(0)}function a9e(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function o9e(e){let t=await i9e(e),r=globalThis.crypto?.subtle??globalThis.window?.crypto?.subtle??(n===void 0?void 0:(await import(`node:crypto`)).webcrypto?.subtle);if(!r)throw Error(`crypto.subtle is not available in current environment`);return a9e(await r.digest(`SHA-256`,t))}var s9e=R((()=>{})),c9e=/* @__PURE__ */ pt({fetchDiscoveryManifest:()=>PO,resolveDiscoveryUrl:()=>jO,resolveManifestRelativeUrl:()=>MO,resolveManifestUrls:()=>l9e,verifySha256Digest:()=>NO});function jO(e){let t=e.trim();if(!t)throw Error(`URL cannot be empty`);let n=t;if(!n.startsWith(`http://`)&&!n.startsWith(`https://`)&&(n=`https://${n}`),n=n.replace(/\/+$/,``),n.endsWith(FO)){let e=n.slice(0,-35).replace(/\/+$/,``);return{baseUrl:e,siteUrl:e,manifestUrl:n}}return{baseUrl:n,siteUrl:n,manifestUrl:`${n}/${FO}`}}function MO(e,t){if(!e)return``;try{return new URL(e,t).href}catch{return e}}function l9e(e,t){let n=JSON.parse(JSON.stringify(e));return Array.isArray(n.tools)&&(n.tools=n.tools.map(e=>({...e,url:MO(e.url,t)}))),Array.isArray(n.scripts)&&(n.scripts=n.scripts.map(e=>({...e,url:MO(e.url,t)}))),Array.isArray(n.skills)&&(n.skills=n.skills.map(e=>({...e,url:MO(e.url,t),tools:Array.isArray(e.tools)?e.tools.map(e=>({...e,url:e.url?MO(e.url,t):void 0})):void 0,scripts:Array.isArray(e.scripts)?e.scripts.map(e=>({...e,url:e.url?MO(e.url,t):void 0})):void 0}))),n}async function NO(e,t){if(!t||!t.startsWith(`sha256:`))return!0;let n=t.slice(7).trim().toLowerCase();return!n||(await o9e(typeof e==`string`?new TextEncoder().encode(e):e)).toLowerCase()===n}async function PO(e,t=globalThis.fetch){let{baseUrl:n,manifestUrl:r}=jO(e),i=await t(r,{headers:{Accept:`application/json`}});if(!i.ok)throw Error(`Failed to fetch discovery manifest: HTTP ${i.status} ${i.statusText}`.trim());let a=await i.json();if(!a||typeof a!=`object`)throw Error(`Invalid discovery manifest: expected a JSON object`);return{manifest:l9e(a,r),siteUrl:n,manifestUrl:r}}var FO,IO=R((()=>{s9e(),FO=`.well-known/agent-skills/index.json`})),u9e=/* @__PURE__ */ pt({importRemoteArtifacts:()=>VO,importRemoteScript:()=>zO,importRemoteSkill:()=>BO,importRemoteTool:()=>RO});function LO(e){return e?.targetSubdir?e.targetSubdir:e?.siteSlug?`imported/${e.siteSlug}`:`main`}async function RO(e,t=un,n,r){let i=(n.name||``).trim();if(d9e.has(i))return{name:i,path:``,status:`failed`,error:`Cannot shadow built-in tool: ${i}`};if(!f9e.test(i))return{name:i,path:``,status:`failed`,error:`Invalid tool name: ${i}`};let a=`.agents/tools/${LO(r)}/${i}.json`;try{if(await wD(e,t,a)&&!r?.overwrite)return{name:i,path:a,status:`skipped`};let o=await(r?.fetchFn||globalThis.fetch)(n.url);if(!o.ok)return{name:i,path:a,status:`failed`,error:`HTTP ${o.status} ${o.statusText}`};let s=await o.text();if(n.digest&&!await NO(s,n.digest))return{name:i,path:a,status:`failed`,error:`Integrity verification failed for tool definition`};let c;try{c=JSON.parse(s)}catch{return{name:i,path:a,status:`failed`,error:`Downloaded tool definition is not valid JSON`}}if(n9e(a,c),await yD(e,t,a,JSON.stringify(c,null,2)),r?.autoEnable){let t=await va(e,V.DECLARATIVE_TOOLS_ENABLED),n=new Set(Array.isArray(t)?t:[]);n.add(i),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,Array.from(n))}return{name:i,path:a,status:`imported`}}catch(e){return{name:i,path:a,status:`failed`,error:e instanceof Error?e.message:String(e)}}}async function zO(e,t=un,n,r){let i=(n.name||``).trim(),a=`.agents/scripts/${LO(r)}/${i.endsWith(`.js`)||i.endsWith(`.mjs`)?i:`${i}.js`}`;try{if(await wD(e,t,a)&&!r?.overwrite)return{name:i,path:a,status:`skipped`};let o=await(r?.fetchFn||globalThis.fetch)(n.url);if(!o.ok)return{name:i,path:a,status:`failed`,error:`HTTP ${o.status} ${o.statusText}`};let s=await o.text();return n.digest&&!await NO(s,n.digest)?{name:i,path:a,status:`failed`,error:`Integrity verification failed for script`}:(await yD(e,t,a,s),{name:i,path:a,status:`imported`})}catch(e){return{name:i,path:a,status:`failed`,error:e instanceof Error?e.message:String(e)}}}async function BO(e,t=un,n,r){let i=(n.name||``).trim(),a=`.agents/skills/${LO(r)}/${i}/SKILL.md`;try{if(await wD(e,t,a)&&!r?.overwrite)return{name:i,path:a,status:`skipped`};let o=await(r?.fetchFn||globalThis.fetch)(n.url);if(!o.ok)return{name:i,path:a,status:`failed`,error:`HTTP ${o.status} ${o.statusText}`};let s=await o.text();return n.digest&&!await NO(s,n.digest)?{name:i,path:a,status:`failed`,error:`Integrity verification failed for skill`}:(Ap(a,s),await yD(e,t,a,s),{name:i,path:a,status:`imported`})}catch(e){return{name:i,path:a,status:`failed`,error:e instanceof Error?e.message:String(e)}}}async function VO(e,t=un,n,r,i){let a={tools:[],skills:[],scripts:[],diagnostics:[]},o=new Set(r.toolNames||[]),s=new Set(r.skillNames||[]),c=new Set(r.scriptNames||[]),l=n.tools||[],u=n.skills||[],d=n.scripts||[];for(let e of u)if(s.has(e.name)){if(Array.isArray(e.tools))for(let t of e.tools)o.add(t.name);if(Array.isArray(e.scripts))for(let t of e.scripts)c.add(t.name)}for(let n of d)if(c.has(n.name)){let r=await zO(e,t,n,i);a.scripts.push(r),r.status===`failed`&&r.error&&a.diagnostics.push(`Script ${n.name}: ${r.error}`)}for(let n of l)if(o.has(n.name)){let r=await RO(e,t,n,i);a.tools.push(r),r.status===`failed`&&r.error&&a.diagnostics.push(`Tool ${n.name}: ${r.error}`)}for(let n of u)if(s.has(n.name)){let r=await BO(e,t,n,i);a.skills.push(r),r.status===`failed`&&r.error&&a.diagnostics.push(`Skill ${n.name}: ${r.error}`)}return a}var d9e,f9e,HO=R((()=>{An(),ya(),SD(),bD(),TD(),AO(),TO(),Vwe(),IO(),d9e=new Set(CO.map(e=>e.name)),f9e=/^[a-z][a-z0-9_]{0,63}$/})),p9e,UO,WO=R((()=>{QD(),An(),ya(),SD(),TO(),DO(),AO(),IO(),HO(),p9e=class{_activeProfile;_activeProfileId;_allTools;_customTools;_declarativeTools;_declarativeToolNamesEnabled;_enabledDeclarativeTools;_enabledToolNames;_enabledTools;_profiles;_systemPromptOverride;_webSearchProxyUrl;_webSearchUrl;_webSearchUseProxy;_searchFilesMaxFileBytes;_searchFilesMaxFilesVisited;_searchFilesSkipDirs;constructor(){this._enabledToolNames=new ZD.State(new Set(EO.enabledToolNames)),this._customTools=new ZD.State([]),this._declarativeTools=new ZD.State([]),this._declarativeToolNamesEnabled=new ZD.State(null),this._systemPromptOverride=new ZD.State(``),this._profiles=new ZD.State([]),this._activeProfileId=new ZD.State(EO.id),this._webSearchUseProxy=new ZD.State(!1),this._webSearchProxyUrl=new ZD.State(`/proxy`),this._webSearchUrl=new ZD.State(`https://html.duckduckgo.com/html/?q={query}`),this._searchFilesMaxFileBytes=new ZD.State(524288),this._searchFilesMaxFilesVisited=new ZD.State(1e3),this._searchFilesSkipDirs=new ZD.State(`.git,node_modules,dist,dist-electron,.cache,.nx,.turbo,__pycache__,.venv,venv`),this._allTools=new ZD.Computed(()=>[...CO,...this._customTools.get()]),this._enabledTools=new ZD.Computed(()=>{let e=this._enabledToolNames.get();return this._allTools.get().filter(t=>e.has(t.name))}),this._enabledDeclarativeTools=new ZD.Computed(()=>{let e=this._declarativeTools.get(),t=this._declarativeToolNamesEnabled.get();return t===null?e:e.filter(e=>t.has(e.name))}),this._activeProfile=new ZD.Computed(()=>{let e=this._activeProfileId.get();return e?EO.id===e?EO:this._profiles.get().find(t=>t.id===e)||null:null})}get activeProfile(){return this._activeProfile.get()}get activeProfileId(){return this._activeProfileId.get()}get allTools(){return this._allTools.get()}get customTools(){return this._customTools.get()}get declarativeTools(){return this._declarativeTools.get()}get declarativeToolNamesEnabled(){return this._declarativeToolNamesEnabled.get()}get enabledDeclarativeTools(){return this._enabledDeclarativeTools.get()}get enabledToolNames(){return this._enabledToolNames.get()}get enabledTools(){return this._enabledTools.get()}isDeclarativeToolEnabled(e){let t=this._declarativeToolNamesEnabled.get();return t===null||t.has(e)}async refreshDeclarativeTools(e,t){try{let n=await OO(e,t||`br:main`),r=this.allTools,i=(n?.tools||[]).filter(e=>!r.some(t=>t.name===e.name)),a=this._declarativeTools.get();return a.length===i.length&&a.every((e,t)=>e.name===i[t].name&&e.description===i[t].description&&JSON.stringify(e.execution)===JSON.stringify(i[t].execution))||this._declarativeTools.set(i),i}catch{return this._declarativeTools.get().length>0&&this._declarativeTools.set([]),[]}}async setDeclarativeToolEnabled(e,t,n){let r=this._declarativeToolNamesEnabled.get(),i=this._declarativeTools.get(),a=new Set(r===null?i.map(e=>e.name):r);n?a.add(t):a.delete(t),this._declarativeToolNamesEnabled.set(a),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,Array.from(a))}async setAllDeclarativeEnabled(e,t){let n=new Set(t);this._declarativeToolNamesEnabled.set(n),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,t)}async fetchRemoteDiscoveryManifest(e){return await PO(e)}async importFromRemoteSite(e,t,n,r){let i=r?.groupId||`br:main`,a=await VO(e,i,t,n,r);return await this.refreshDeclarativeTools(e,i),a}exportBackup(){return JSON.stringify({enabledTools:[...this._enabledToolNames.get()],customTools:this._customTools.get(),declarativeToolsEnabled:this._declarativeToolNamesEnabled.get()?Array.from(this._declarativeToolNamesEnabled.get()):null,systemPromptOverride:this._systemPromptOverride.get(),profiles:this._profiles.get(),activeProfileId:this._activeProfileId.get(),webSearchUseProxy:this._webSearchUseProxy.get(),webSearchProxyUrl:this._webSearchProxyUrl.get(),webSearchUrl:this._webSearchUrl.get(),searchFilesMaxFileBytes:this._searchFilesMaxFileBytes.get(),searchFilesMaxFilesVisited:this._searchFilesMaxFilesVisited.get(),searchFilesSkipDirs:this._searchFilesSkipDirs.get()},null,2)}findProfilesForProvider(e,t){return this.profiles.filter(n=>!(n.providerId&&n.providerId!==e||n.model&&n.model!==t))}get profiles(){return[EO,...this._profiles.get()]}get systemPromptOverride(){return this._systemPromptOverride.get()}get webSearchProxyUrl(){return this._webSearchProxyUrl.get()}get webSearchUrl(){return this._webSearchUrl.get()}get webSearchUseProxy(){return this._webSearchUseProxy.get()}get searchFilesMaxFileBytes(){return this._searchFilesMaxFileBytes.get()}get searchFilesMaxFilesVisited(){return this._searchFilesMaxFilesVisited.get()}get searchFilesSkipDirs(){return this._searchFilesSkipDirs.get()}get searchFilesSkipDirsSet(){return new Set(this._searchFilesSkipDirs.get().split(`,`).map(e=>e.trim()).filter(Boolean))}async activateProfile(e,t){let n=this.profiles.find(e=>e.id===t);n&&(this._activeProfileId.set(t),this._enabledToolNames.set(new Set(n.enabledToolNames)),this._customTools.set(n.customTools),this._systemPromptOverride.set(n.systemPromptOverride||``),await Promise.all([xD(e,V.ACTIVE_TOOL_PROFILE,t),xD(e,V.ENABLED_TOOLS,n.enabledToolNames),xD(e,V.CUSTOM_TOOLS,n.customTools),xD(e,V.SYSTEM_PROMPT_OVERRIDE,n.systemPromptOverride||``)]))}async addCustomTool(e,t){let n=[...this._customTools.get(),t];this._customTools.set(n);let r=new Set(this._enabledToolNames.get());r.add(t.name),this._enabledToolNames.set(r),await Promise.all([xD(e,V.CUSTOM_TOOLS,n),xD(e,V.ENABLED_TOOLS,[...r])])}async addProfile(e,t){let n=[...this._profiles.get(),t];this._profiles.set(n),await xD(e,V.TOOL_PROFILES,n)}async cloneTool(e,t,n,r){let i=this.allTools.find(e=>e.name===t);if(!i||this.allTools.some(e=>e.name===n))return!1;let a={name:n,description:r||i.description,input_schema:JSON.parse(JSON.stringify(i.input_schema))};return await this.addCustomTool(e,a),!0}async deactivateProfile(e){this._activeProfileId.set(null),await xD(e,V.ACTIVE_TOOL_PROFILE,null)}async deleteProfile(e,t){if(t===EO.id)return;let n=this._profiles.get().filter(e=>e.id!==t);this._profiles.set(n),this._activeProfileId.get()===t&&(this._activeProfileId.set(null),await xD(e,V.ACTIVE_TOOL_PROFILE,null)),await xD(e,V.TOOL_PROFILES,n)}async importBackup(e,t){let n=JSON.parse(t);Array.isArray(n.enabledTools)&&(this._enabledToolNames.set(new Set(n.enabledTools)),await xD(e,V.ENABLED_TOOLS,n.enabledTools)),Array.isArray(n.customTools)&&(this._customTools.set(n.customTools),await xD(e,V.CUSTOM_TOOLS,n.customTools)),typeof n.systemPromptOverride==`string`&&(this._systemPromptOverride.set(n.systemPromptOverride),await xD(e,V.SYSTEM_PROMPT_OVERRIDE,n.systemPromptOverride)),Array.isArray(n.profiles)&&(this._profiles.set(n.profiles),await xD(e,V.TOOL_PROFILES,n.profiles)),(typeof n.activeProfileId==`string`||n.activeProfileId===null)&&(this._activeProfileId.set(n.activeProfileId),await xD(e,V.ACTIVE_TOOL_PROFILE,n.activeProfileId)),typeof n.webSearchUseProxy==`boolean`&&(this._webSearchUseProxy.set(n.webSearchUseProxy),await xD(e,V.WEB_SEARCH_USE_PROXY,n.webSearchUseProxy?`true`:`false`)),typeof n.webSearchProxyUrl==`string`&&(this._webSearchProxyUrl.set(n.webSearchProxyUrl),await xD(e,V.WEB_SEARCH_PROXY_URL,n.webSearchProxyUrl)),typeof n.webSearchUrl==`string`&&(this._webSearchUrl.set(n.webSearchUrl),await xD(e,V.WEB_SEARCH_URL,n.webSearchUrl)),typeof n.searchFilesMaxFileBytes==`number`&&n.searchFilesMaxFileBytes>0&&(this._searchFilesMaxFileBytes.set(n.searchFilesMaxFileBytes),await xD(e,V.SEARCH_FILES_MAX_FILE_BYTES,String(n.searchFilesMaxFileBytes))),typeof n.searchFilesMaxFilesVisited==`number`&&n.searchFilesMaxFilesVisited>0&&(this._searchFilesMaxFilesVisited.set(n.searchFilesMaxFilesVisited),await xD(e,V.SEARCH_FILES_MAX_FILES_VISITED,String(n.searchFilesMaxFilesVisited))),typeof n.searchFilesSkipDirs==`string`&&(this._searchFilesSkipDirs.set(n.searchFilesSkipDirs),await xD(e,V.SEARCH_FILES_SKIP_DIRS,n.searchFilesSkipDirs)),Array.isArray(n.declarativeToolsEnabled)?(this._declarativeToolNamesEnabled.set(new Set(n.declarativeToolsEnabled)),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,n.declarativeToolsEnabled)):n.declarativeToolsEnabled===null&&(this._declarativeToolNamesEnabled.set(null),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,null))}async load(e){let[t,n,r,i,a,o,s,c,l,u,d,f]=await Promise.all([va(e,V.ENABLED_TOOLS),va(e,V.CUSTOM_TOOLS),va(e,V.SYSTEM_PROMPT_OVERRIDE),va(e,V.TOOL_PROFILES),va(e,V.ACTIVE_TOOL_PROFILE),va(e,V.WEB_SEARCH_USE_PROXY),va(e,V.WEB_SEARCH_PROXY_URL),va(e,V.WEB_SEARCH_URL),va(e,V.SEARCH_FILES_MAX_FILE_BYTES),va(e,V.SEARCH_FILES_MAX_FILES_VISITED),va(e,V.SEARCH_FILES_SKIP_DIRS),va(e,V.DECLARATIVE_TOOLS_ENABLED)]);if(Array.isArray(t)&&this._enabledToolNames.set(new Set(t)),Array.isArray(n)&&this._customTools.set(n),Array.isArray(f)&&this._declarativeToolNamesEnabled.set(new Set(f)),typeof r==`string`&&this._systemPromptOverride.set(r),Array.isArray(i)&&this._profiles.set(i),typeof a==`string`&&this._activeProfileId.set(a),o!=null){let e=String(o).toLowerCase();this._webSearchUseProxy.set(e===`true`||e===`1`)}if(typeof s==`string`&&s.trim().length>0&&this._webSearchProxyUrl.set(s.trim()),typeof c==`string`&&c.trim().length>0&&this._webSearchUrl.set(c.trim()),l!=null){let e=Number(l);Number.isFinite(e)&&e>0&&this._searchFilesMaxFileBytes.set(e)}if(u!=null){let e=Number(u);Number.isFinite(e)&&e>0&&this._searchFilesMaxFilesVisited.set(e)}typeof d==`string`&&d.trim().length>0&&this._searchFilesSkipDirs.set(d.trim())}async setWebSearchProxyUrl(e,t){let n=t.trim()||`/proxy`;this._webSearchProxyUrl.set(n),await xD(e,V.WEB_SEARCH_PROXY_URL,n)}async setWebSearchUrl(e,t){let n=t.trim()||`https://html.duckduckgo.com/html/?q={query}`;this._webSearchUrl.set(n),await xD(e,V.WEB_SEARCH_URL,n)}async setWebSearchUseProxy(e,t){let n=!!t;this._webSearchUseProxy.set(n),await xD(e,V.WEB_SEARCH_USE_PROXY,n?`true`:`false`)}async setSearchFilesMaxFileBytes(e,t){let n=Math.max(1,Math.round(t));this._searchFilesMaxFileBytes.set(n),await xD(e,V.SEARCH_FILES_MAX_FILE_BYTES,String(n))}async setSearchFilesMaxFilesVisited(e,t){let n=Math.max(1,Math.round(t));this._searchFilesMaxFilesVisited.set(n),await xD(e,V.SEARCH_FILES_MAX_FILES_VISITED,String(n))}async setSearchFilesSkipDirs(e,t){let n=t.trim();this._searchFilesSkipDirs.set(n),await xD(e,V.SEARCH_FILES_SKIP_DIRS,n)}async removeCustomTool(e,t){let n=this._customTools.get().filter(e=>e.name!==t);this._customTools.set(n);let r=new Set(this._enabledToolNames.get());r.delete(t),this._enabledToolNames.set(r),await Promise.all([xD(e,V.CUSTOM_TOOLS,n),xD(e,V.ENABLED_TOOLS,[...r])])}async saveToActiveProfile(e){let t=this._activeProfileId.get();if(!t)return;let n=this._profiles.get().find(e=>e.id===t);if(!n)return;let r={...n,enabledToolNames:[...this._enabledToolNames.get()],customTools:[...this._customTools.get()],systemPromptOverride:this._systemPromptOverride.get()};await this.updateProfile(e,r)}async setAllEnabled(e,t){this._enabledToolNames.set(new Set(t));let n=[xD(e,V.ENABLED_TOOLS,t)];this._activeProfileId.get()&&(this._activeProfileId.set(null),n.push(xD(e,V.ACTIVE_TOOL_PROFILE,null))),await Promise.all(n)}async setSystemPromptOverride(e,t){this._systemPromptOverride.set(t),await xD(e,V.SYSTEM_PROMPT_OVERRIDE,t)}async setToolEnabled(e,t,n){let r=new Set(this._enabledToolNames.get());n?r.add(t):r.delete(t),this._enabledToolNames.set(r);let i=[xD(e,V.ENABLED_TOOLS,[...r])];this._activeProfileId.get()&&(this._activeProfileId.set(null),i.push(xD(e,V.ACTIVE_TOOL_PROFILE,null))),await Promise.all(i)}async updateProfile(e,t){let n=this._profiles.get().map(e=>e.id===t.id?t:e);this._profiles.set(n),await xD(e,V.TOOL_PROFILES,n)}},UO=new p9e}));function m9e(e){for(let t of KO)if(t.test(e))return!0;return!1}function h9e(e){let t=String(e||``),n=t;for(let e of KO)t=t.replace(e,``);return t!==n&&(t=t.replace(/^[ \t]+$/gm,``),t=t.replace(/\n{3,}/g,`
|
|
3831
|
+
deleteSurface — remove the surface from the chat`,input_schema:{type:`object`,properties:{action:{type:`string`,enum:[`createSurface`,`updateComponents`,`updateDataModel`,`deleteSurface`],description:`The A2UI operation to perform`},surfaceId:{type:`string`,description:`Unique identifier for this surface. Use a stable ID so you can update it later.`},components:{type:`array`,description:`Flat array of component objects (required for createSurface/updateComponents). Each object MUST have an 'id' field and a 'component' field. The component with id 'root' is the tree root (required for createSurface). Component field values: Text | Row | Column | Button | TextField | Image | Icon | Video | AudioPlayer | List | Card | Tabs | Modal | Divider | CheckBox | ChoicePicker | Slider | DateTimeInput. Put all properties at the TOP LEVEL alongside 'component' and 'id'. DO NOT nest properties under a 'properties' key. Children arrays contain other component ID strings, not nested objects.`,items:{type:`object`,additionalProperties:!0}},dataModel:{type:`object`,description:`Initial data model for the surface (used with createSurface). Components can reference values via { "path": "/key" }.`,properties:{},additionalProperties:!0},path:{type:`string`,description:`JSON Pointer path to update (required for updateDataModel). Examples: "/result", "/user/name", "/count". Use "/" to replace the entire data model.`},value:{type:`string`,description:`New value to set at the specified path (used with updateDataModel). Omit to delete the key at the given path.`},surfaceProperties:{type:`object`,description:`Optional display/branding properties for this surface (e.g. agentDisplayName).`,properties:{},additionalProperties:!0}},required:[`action`,`surfaceId`]}}})),U5e,W5e=R((()=>{U5e={name:`spawn_subagent`,description:`Spawn one or more independent agent loops to work on subtasks in parallel and collect their results. Each subagent has its own tool-use loop, inherits the current API key, and can optionally override provider/model. and runs concurrently with other subagents via Promise.all. Use spawn_subagent when a task has independent parallel workstreams — for example: researching multiple topics simultaneously, processing a list of items in parallel, or delegating isolated subtasks to specialized agents. Do NOT use spawn_subagent for sequential tasks where step 2 depends on step 1's output — just do those steps directly. Do NOT use spawn_subagent for simple single-step work that takes one tool call. Use the parallel_agents field to fan out multiple subagents in a single call.`,input_schema:{type:`object`,properties:{prompt:{type:`string`,description:`The task prompt for a single subagent. Required unless using parallel_agents for multi-agent fan-out.`},tools:{type:`array`,description:`Optional list of tool names to allow in the subagent. If omitted, the subagent inherits the current tool set (minus spawn_subagent to prevent recursion). If provided, only these tools are available to the subagent.`,items:{type:`string`}},profile:{type:`string`,enum:[`current`,`fast`,`smart`,`powerful`],description:`Optional model profile to run the subagent on. Use 'fast' for simple/cheap subtasks (e.g., text formatting, basic search), 'smart' for moderate reasoning, 'powerful' for deep thinking or complex coding, and 'current' to inherit the parent model. Defaults to 'current'.`},workspace_group_id:{type:`string`,description:`Optional workspace group id override for subagent file/tool scope. Use 'parent' to reuse the parent workspace in automatic mode. When omitted, subagents use an isolated workspace by default.`},system_prompt:{type:`string`,description:`Optional system prompt override for the subagent. Defaults to the current system prompt.`},parallel_agents:{type:`array`,description:`Optional list of subagent specifications to run in parallel. When provided, all agents are launched concurrently and their results are combined. Note: There is a configurable maximum limit on parallel subagents (default 5). Each entry can specify a prompt, optional tools list, optional profile, and optional system_prompt.`,items:{type:`object`,properties:{prompt:{type:`string`,description:`The task prompt for this subagent.`},tools:{type:`array`,description:`Optional tool names for this subagent.`,items:{type:`string`}},profile:{type:`string`,enum:[`current`,`fast`,`smart`,`powerful`],description:`Optional model profile for this subagent. Defaults to 'current'.`},workspace_group_id:{type:`string`,description:`Optional workspace group id for this subagent. Use 'parent' for parent workspace in automatic mode.`},system_prompt:{type:`string`,description:`Optional system prompt override for this subagent.`}},required:[`prompt`]}}},required:[`prompt`]}}})),G5e,K5e=R((()=>{G5e={name:`get_current_time`,description:`Get the current date and time. Returns an ISO 8601 string representing the current date and time. Use this tool whenever you need to know the current time, instead of relying on shell tools which may be unavailable.`,input_schema:{type:`object`,properties:{timezone:{type:`string`,description:`Optional timezone to format the time in (e.g. 'America/New_York'). If omitted, returns UTC.`}}}}})),q5e,J5e,Y5e,X5e,Z5e,Q5e,$5e,e7e,t7e,n7e,r7e,i7e,a7e,o7e=R((()=>{q5e={name:`attach_file_to_chat`,description:`Prepare a workspace file for chat delivery by generating an exact markdown attachment snippet. Validates the file path and returns markdown that works for inline image rendering in ShadowClaw and attachment upload in external channels like Telegram/iMessage.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`},alt:{type:`string`,description:`Optional alt/caption text to use in the generated markdown`}},required:[`path`]}},J5e={name:`copy_file`,description:`Copy a file or directory in the group workspace to a new destination path. Supports copying single files or nested directories. Optionally supports copying between different conversation workspaces via source_group_id or target_group_id.`,input_schema:{type:`object`,properties:{source_path:{type:`string`,description:`Source file or directory path relative to workspace root`},target_path:{type:`string`,description:`Destination file or directory path relative to workspace root`},source_group_id:{type:`string`,description:`Optional source conversation group ID (defaults to current workspace)`},target_group_id:{type:`string`,description:`Optional target conversation group ID (defaults to current workspace)`}},required:[`source_path`,`target_path`]}},Y5e={name:`create_directory`,description:`Create a new directory (and any missing parent directories) in the group workspace.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`Directory path relative to the group workspace root`}},required:[`path`]}},X5e={name:`delete_file`,description:`Delete a file or directory from the group workspace. If the target path is a directory, it will be recursively deleted.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File or directory path relative to the group workspace root`}},required:[`path`]}},Z5e={name:`diff_files`,description:`Compare two files in the workspace and output the differences. Useful for comparing generated code, checking before patching, or finding changes outside of git repositories.`,input_schema:{type:`object`,properties:{path_a:{type:`string`,description:`Path to the first file relative to the group workspace root.`},path_b:{type:`string`,description:`Path to the second file relative to the group workspace root.`}},required:[`path_a`,`path_b`]}},Q5e={name:`list_files`,description:`List files and directories in the group workspace. Directory names end with /. Returns sorted entries.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`Directory path relative to workspace root (default: root)`}}}},$5e={name:`move_file`,description:`Move or rename a file or directory in the group workspace to a target path. Supports moving single files or nested directories. Optionally supports moving between different conversation workspaces via source_group_id or target_group_id.`,input_schema:{type:`object`,properties:{source_path:{type:`string`,description:`Source file or directory path relative to workspace root`},target_path:{type:`string`,description:`Destination file or directory path relative to workspace root`},source_group_id:{type:`string`,description:`Optional source conversation group ID (defaults to current workspace)`},target_group_id:{type:`string`,description:`Optional target conversation group ID (defaults to current workspace)`}},required:[`source_path`,`target_path`]}},e7e={name:`open_file`,description:`Open a file from the group workspace in the UI file viewer dialog. Use this only when the user explicitly asks to inspect a file visually with preview support. Do not use this tool to send or attach files in chat responses.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`}},required:[`path`]}},t7e={name:`patch_file`,description:`Make a targeted text replacement in a file. Finds the single occurrence of old_string and replaces it with new_string. Fails if old_string is not found or matches more than once. Use this instead of write_file when you only need to change part of a file — it is safer and works well with large files. Include enough surrounding context in old_string to make the match unique. IMPORTANT: You must provide 'path', 'old_string', and 'new_string' parameters.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`},old_string:{type:`string`,description:`The exact text to find in the file. Must match exactly once. Include 2-3 lines of surrounding context to ensure a unique match.`},new_string:{type:`string`,description:`The replacement text. Can be empty to delete old_string.`}},required:[`path`,`old_string`,`new_string`]}},n7e={name:`read_file`,description:`Read the contents of one or more files from the group workspace. IMPORTANT: You must specify either the 'path' parameter (for a single file) or the 'paths' parameter (an array of file paths for multiple files). When paths is provided, returns all file contents concatenated with --- filename --- headers. Prefer paths to batch reads in a single call. Image files (png, jpg, gif, webp, etc.) are returned as native image content that the model can see directly. Other binary files will be detected and an error returned suggesting alternative tools.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`Single file path relative to the group workspace root`},paths:{type:`array`,items:{type:`string`},description:`Array of file paths relative to the group workspace root. Use this to read multiple files in a single tool call.`}}}},r7e={name:`search_files`,description:`Search for a pattern (regex or exact text) in files across the workspace. Useful for finding code references, function definitions, or specific content without needing to rely on a shell environment.`,input_schema:{type:`object`,properties:{pattern:{type:`string`,description:`The text or regular expression to search for.`},path:{type:`string`,description:`Optional directory path to restrict the search to (e.g. 'src/'). Defaults to workspace root.`},file_glob:{type:`string`,description:`Optional simple glob to filter files (e.g. '*.ts'). Supports * as wildcard.`},is_regex:{type:`boolean`,description:`Set to true to parse the pattern as a regular expression.`}},required:[`pattern`]}},i7e={name:`send_file`,description:`Send a workspace file directly to connected peer(s) over the P2P (PeerJS/WebRTC) data channel. Use this when the user is in a peer conversation or room, or specify peer_id to send to a remote peer directly. The file is read from the current workspace and transferred over WebRTC in binary chunks so there is no size limit.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`},peer_id:{type:`string`,description:`Optional target PeerJS peer ID (or peer: groupId). If omitted, sends to the current peer/room conversation.`}},required:[`path`]}},a7e={name:`write_file`,description:`Write content to a file in the group workspace. Creates the file and any intermediate directories if they don't exist. Overwrites the file if it already exists. IMPORTANT: You must provide both the 'path' and 'content' parameters when calling this tool.`,input_schema:{type:`object`,properties:{path:{type:`string`,description:`File path relative to the group workspace root`},content:{type:`string`,description:`Content to write to the file`}},required:[`path`,`content`]}}})),s7e,c7e,l7e,u7e,d7e,f7e,p7e,m7e,h7e,g7e,_7e,v7e,y7e,b7e,x7e,S7e,C7e,w7e,T7e,E7e,D7e,O7e,k7e,A7e,j7e=R((()=>{s7e={name:`git_add`,description:`Stage files in a cloned repo. Accepts an array of filepaths. If omitted or empty, stages the repo root.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},filepaths:{type:`array`,items:{type:`string`},description:`Array of file paths to stage (relative to repo root). Pass a single item for one file.`}},required:[`repo`]}},c7e={name:`git_branch`,description:`Create a new branch in a cloned repo. Optionally switch to it immediately (like git checkout -b).`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name (returned by git_clone)`},name:{type:`string`,description:`Name for the new branch`},checkout:{type:`boolean`,description:`Switch to the new branch after creating it (default: false)`},start_point:{type:`string`,description:`Branch, tag, or commit SHA to branch from (default: HEAD)`}},required:[`repo`,`name`]}},l7e={name:`git_branches`,description:`List branches in a cloned repo. Current branch is marked with *.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},remote:{type:`boolean`,description:`List remote-tracking branches instead (default: false)`}},required:[`repo`]}},u7e={name:`git_checkout`,description:`Checkout a branch, tag, or commit SHA in a cloned repo.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name (returned by git_clone)`},ref:{type:`string`,description:`Branch name, tag, or commit SHA to checkout`}},required:[`repo`,`ref`]}},d7e={name:`git_clone`,description:`Clone a git repository into browser-persistent OPFS storage. Files are stored directly under repos/<repo-name>/ in the workspace and are immediately accessible to other git_* tools without any extra sync step. Works with public and private repos (GitHub, GitLab, GitHub Enterprise, etc.). If a Git PAT is configured in Settings, it is used automatically for authentication. Uses a CORS proxy. Returns the short repo name used for subsequent git_* operations.`,input_schema:{type:`object`,properties:{url:{type:`string`,description:`Full HTTPS repo URL (e.g. https://github.com/user/repo)`},name:{type:`string`,description:`Optional short repo name to use for the clone directory; defaults to the repository name parsed from the URL.`},branch:{type:`string`,description:`Branch to clone (default: default branch)`},depth:{type:`number`,description:`Shallow clone depth (default: 20)`}},required:[`url`]}},f7e={name:`git_commit`,description:`Stage all changes and create a commit in a cloned repo. Uses configured git author name/email or defaults.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},message:{type:`string`,description:`Commit message`},author_name:{type:`string`,description:`Author name (optional, uses configured default)`},author_email:{type:`string`,description:`Author email (optional, uses configured default)`}},required:[`repo`,`message`]}},p7e={name:`git_config`,description:`Get or set a git config value for a repo (e.g. user.name, user.email). Persistent per-repo identity avoids specifying author on every commit.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},command:{type:`string`,enum:[`get`,`set`],description:`Operation: get or set a config value`},key:{type:`string`,description:`Config key path (e.g. user.name, user.email, core.autocrlf)`},value:{type:`string`,description:`Value to set — required when command is set`}},required:[`repo`,`command`,`key`]}},m7e={name:`git_delete_branch`,description:`Delete a local branch from a cloned repo.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},name:{type:`string`,description:`Name of the branch to delete`}},required:[`repo`,`name`]}},h7e={name:`git_delete_repo`,description:"Delete the git metadata for a cloned repository while leaving the working tree files in place. Use this to clean up corrupted or stale repos that fail to re-clone. The repo directory remains under repos/<repo>, but the `.git/` metadata is removed.",input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name (as returned by git_clone or git_list_repos)`}},required:[`repo`]}},g7e={name:`git_diff`,description:`Show changed files between HEAD and working tree, or between two refs.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref1:{type:`string`,description:`First ref (default: HEAD)`},ref2:{type:`string`,description:`Second ref (if omitted, diffs HEAD vs workdir)`}},required:[`repo`]}},_7e={name:`git_fetch`,description:`Fetch commits from the remote without merging. Safe for inspecting remote state before deciding to merge or rebase.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},branch:{type:`string`,description:`Remote branch to fetch (default: default branch)`},remote:{type:`string`,description:`Remote name (default: origin)`}},required:[`repo`]}},v7e={name:`git_init`,description:`Initialize a new empty git repository in browser storage. Use this to create a new project from scratch before using git_push to push to a remote.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short name for the new repo (used for all subsequent git_ operations)`}},required:[`repo`]}},y7e={name:`git_list_repos`,description:`List all git repositories currently cloned in browser storage.`,input_schema:{type:`object`,properties:{}}},b7e={name:`git_log`,description:`Show the commit log for a cloned repo. Returns commit SHA, date, author, and message.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref:{type:`string`,description:`Ref to log from (default: HEAD)`},depth:{type:`number`,description:`Number of commits to show (default: 10)`}},required:[`repo`]}},x7e={name:`git_merge`,description:`Merge a branch or ref into the current branch. Supports fast-forward and three-way merges. If the merge has conflicts, a detailed report is returned with the conflicted files and their conflict regions inline. To resolve: use read_file on each conflicted file, then write_file with the complete resolved content (no conflict markers). After all files are resolved, use git_add for each, then git_commit. Do NOT use bash/sed for conflict resolution.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},theirs:{type:`string`,description:`Branch name, tag, or commit SHA to merge into the current branch`},author_name:{type:`string`,description:`Author name (optional, uses configured default)`},author_email:{type:`string`,description:`Author email (optional, uses configured default)`}},required:[`repo`,`theirs`]}},S7e={name:`git_pull`,description:`Fetch and merge commits from the remote repository. Uses configured git author name/email for merge commits if needed.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},branch:{type:`string`,description:`Branch to pull (default: current branch)`},author_name:{type:`string`,description:`Author name (optional, uses configured default)`},author_email:{type:`string`,description:`Author email (optional, uses configured default)`}},required:[`repo`]}},C7e={name:`git_push`,description:`Push commits to the remote repository. Requires a GitHub personal access token (PAT) to be configured. The token is loaded from the encrypted credential store.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},branch:{type:`string`,description:`Local branch to push (default: current branch)`},remote_ref:{type:`string`,description:`Remote branch name to push to, if different from local branch. Example: push local 'feature-rebased' to remote 'feature/original'.`},force:{type:`boolean`,description:`Force push (default: false)`},tags:{type:`boolean`,description:`Also push all local tags to the remote (default: false)`}},required:[`repo`]}},w7e={name:`git_read_file_at_ref`,description:`Read a file's contents at a specific ref (branch, tag, or commit SHA) without checking it out. Useful for code review across branches.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref:{type:`string`,description:`Branch name, tag, or commit SHA`},filepath:{type:`string`,description:`File path relative to the repo root`}},required:[`repo`,`ref`,`filepath`]}},T7e={name:`git_remote`,description:`Manage git remotes: list, add, or remove a remote in a cloned repo.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},command:{type:`string`,enum:[`list`,`add`,`remove`],description:`Operation to perform`},remote:{type:`string`,description:`Remote name (e.g. origin, upstream) — required for add/remove`},url:{type:`string`,description:`Remote URL — required for add`}},required:[`repo`,`command`]}},E7e={name:`git_reset`,description:`Reset the current branch HEAD to a specific ref or commit SHA. Updates the branch pointer and checks out the target, discarding local changes. Equivalent to 'git reset --hard <ref>'.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref:{type:`string`,description:`Branch name, tag, or commit SHA to reset to`}},required:[`repo`,`ref`]}},D7e={name:`git_show`,description:`Show the metadata and diff of a specific commit. Returns author, date, message, and a unified diff against the parent commit.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},ref:{type:`string`,description:`Commit SHA, branch, or tag to inspect (default: HEAD)`}},required:[`repo`,`ref`]}},O7e={name:`git_status`,description:`Show the working tree status of a cloned repo. Reports modified, added, deleted, and unstaged files.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`}},required:[`repo`]}},k7e={name:`git_tag`,description:`Create a lightweight or annotated tag at HEAD. Use git_push with tags=true to push tags to the remote.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},tag:{type:`string`,description:`Tag name (e.g. v1.2.3)`},message:{type:`string`,description:`Annotation message — if provided, creates an annotated tag; otherwise lightweight`},author_name:{type:`string`,description:`Tagger name (optional, uses configured default)`},author_email:{type:`string`,description:`Tagger email (optional, uses configured default)`}},required:[`repo`,`tag`]}},A7e={name:`git_unstage`,description:`Remove one or more staged files from the index without touching the working tree. The inverse of git_add — use to undo accidental staging.`,input_schema:{type:`object`,properties:{repo:{type:`string`,description:`Short repo name`},filepath:{type:`string`,description:`File path or array of file paths to unstage (relative to repo root)`}},required:[`repo`,`filepath`]}}})),M7e,N7e,P7e,F7e,I7e,L7e,R7e,z7e=R((()=>{M7e={name:`create_task`,description:`Create a scheduled recurring task. The task will run automatically on the specified schedule and send the result back to this group. Uses cron expressions (minute hour day-of-month month day-of-week).`,input_schema:{type:`object`,properties:{schedule:{type:`string`,description:`Cron expression, e.g. "0 9 * * 1-5" for 9am weekdays`},prompt:{type:`string`,description:`The prompt/instruction to execute on each run (used if type is 'prompt')`},type:{type:`string`,enum:[`prompt`,`tools`],description:`The type of task to create. Defaults to 'prompt'.`},tools:{type:`array`,description:`A list of tools to execute sequentially (used if type is 'tools')`,items:{type:`object`,properties:{name:{type:`string`},input:{type:`object`}},required:[`name`,`input`]}},name:{type:`string`,description:`The optional title/name for the task, helping to identify its purpose.`}},required:[`prompt`,`type`]}},N7e={name:`list_tasks`,description:`List all scheduled recurring tasks for this group. Returns a list of tasks with their IDs, schedules, and prompts.`,input_schema:{type:`object`,properties:{}}},P7e={name:`update_task`,description:`Update an existing scheduled task's schedule or prompt.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to update`},schedule:{type:`string`,description:`Standard cron expression (e.g. '0 9 * * *'). Leave empty for an unscheduled task.`},prompt:{type:`string`,description:`New prompt/instruction (optional)`},type:{type:`string`,enum:[`prompt`,`tools`],description:`New task type (optional)`},tools:{type:`array`,description:`New list of tools (optional)`,items:{type:`object`,properties:{name:{type:`string`},input:{type:`object`}},required:[`name`,`input`]}},enabled:{type:`boolean`,description:`Whether the task is enabled (optional)`},name:{type:`string`,description:`New name/title for the task (optional).`}},required:[`id`]}},F7e={name:`delete_task`,description:`Delete a scheduled task by its ID.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to delete`}},required:[`id`]}},I7e={name:`enable_task`,description:`Enable a scheduled task so it runs on its schedule.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to enable`}},required:[`id`]}},L7e={name:`disable_task`,description:`Disable a scheduled task so it stops running.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to disable`}},required:[`id`]}},R7e={name:`run_task`,description:`Immediately trigger a scheduled task by its ID, outside of its normal cron schedule. Use this to manually fire a task on demand. Use list_tasks to find the task ID first.`,input_schema:{type:`object`,properties:{id:{type:`string`,description:`The unique ID of the task to run immediately`}},required:[`id`]}}})),B7e,V7e,H7e,U7e,W7e=R((()=>{B7e={name:`create_room`,description:`Create a new multi-party room (a shared PeerJS conversation) hosted by this device. Other agents or humans can then be invited to participate. Returns the room so you can share or invite peers into it.`,input_schema:{type:`object`,properties:{name:{type:`string`,description:`A human-readable name for the room.`}},required:[`name`]}},V7e={name:`invite_to_room`,description:`Invite a peer (another agent or human, identified by their PeerJS peer ID) into a room so they can join the shared conversation. If room_id is omitted and the current conversation is a room, that room is used.`,input_schema:{type:`object`,properties:{peer_id:{type:`string`,description:`The PeerJS peer ID of the participant to invite.`},room_id:{type:`string`,description:`The room id to invite into. Defaults to the current room conversation.`}},required:[`peer_id`]}},H7e={name:`leave_room`,description:`Leave a room. If you are the host, the room is disbanded for all members. If room_id is omitted and the current conversation is a room, that room is used.`,input_schema:{type:`object`,properties:{room_id:{type:`string`,description:`The room id to leave. Defaults to the current room conversation.`}}}},U7e={name:`list_room_members`,description:`List the participants (humans and agents) currently in a room. If room_id is omitted and the current conversation is a room, that room is used.`,input_schema:{type:`object`,properties:{room_id:{type:`string`,description:`The room id to inspect. Defaults to the current room conversation.`}}}}})),G7e,K7e,q7e,J7e,Y7e,X7e,Z7e=R((()=>{G7e={name:`summarize_text`,description:`Summarize text using Web Platform's Summarizer API (or polyfill fallback). Produces key points, TLDR, teaser, or headline.`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text content to summarize.`},type:{type:`string`,enum:[`key-points`,`tldr`,`teaser`,`headline`],description:`The summary type (default: key-points).`},format:{type:`string`,enum:[`plain-text`,`markdown`],description:`Output format (default: markdown).`},length:{type:`string`,enum:[`short`,`medium`,`long`],description:`Summary length (default: short).`},preference:{type:`string`,enum:[`capability`,`speed`,`auto`],description:`Summarizer performance preference (default: auto).`},context:{type:`string`,description:`Optional background context for summarization.`},outputLanguage:{type:`string`,description:`Optional target language code (e.g. 'en', 'es').`},sharedContext:{type:`string`,description:`Optional shared context passed to the underlying model.`},overridePrompt:{type:`string`,description:`Optional custom system prompt overriding default summarization instructions.`}},required:[`text`]}},K7e={name:`write_text`,description:`Generate or draft text using Web Platform's Writer API (or polyfill fallback).`,input_schema:{type:`object`,properties:{prompt:{type:`string`,description:`The prompt or writing instructions.`},tone:{type:`string`,enum:[`formal`,`neutral`,`casual`],description:`Tone for drafting (default: neutral).`},format:{type:`string`,enum:[`plain-text`,`markdown`],description:`Output format (default: plain-text).`},length:{type:`string`,enum:[`short`,`medium`,`long`],description:`Target length (default: short).`},context:{type:`string`,description:`Optional background context for writing.`},outputLanguage:{type:`string`,description:`Optional target language code (e.g. 'en', 'es').`},sharedContext:{type:`string`,description:`Optional shared context passed to the underlying model.`}},required:[`prompt`]}},q7e={name:`rewrite_text`,description:`Rewrite or rephrase text using Web Platform's Rewriter API (or polyfill fallback). Can adjust tone or length.`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text to rewrite.`},tone:{type:`string`,enum:[`as-is`,`more-formal`,`more-casual`],description:`Tone adjustment (default: as-is).`},format:{type:`string`,enum:[`as-is`,`plain-text`,`markdown`],description:`Format adjustment (default: as-is).`},length:{type:`string`,enum:[`as-is`,`shorter`,`longer`],description:`Length adjustment (default: as-is).`},context:{type:`string`,description:`Optional background context for rewriting.`},outputLanguage:{type:`string`,description:`Optional target language code (e.g. 'en', 'es').`},sharedContext:{type:`string`,description:`Optional shared context passed to the underlying model.`}},required:[`text`]}},J7e={name:`proofread_text`,description:`Proofread and correct grammar, spelling, and phrasing errors using Web Platform's Proofreader API (or polyfill fallback).`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text to proofread.`},context:{type:`string`,description:`Optional background context for proofreading.`}},required:[`text`]}},Y7e={name:`detect_language`,description:`Detect the language of input text using Web Platform's Language Detector API (or polyfill fallback).`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text to analyze for language detection.`}},required:[`text`]}},X7e={name:`translate_text`,description:`Translate text using Web Platform's Translator API (or polyfill fallback).`,input_schema:{type:`object`,properties:{text:{type:`string`,description:`The text to translate.`},sourceLanguage:{type:`string`,description:`Source language BCP 47 code (e.g. 'en', 'es', 'ja').`},targetLanguage:{type:`string`,description:`Target language BCP 47 code (e.g. 'en', 'es', 'ja').`}},required:[`text`,`sourceLanguage`,`targetLanguage`]}}})),xO,SO,Q7e=R((()=>{xO={name:`prompt_peer`,description:`Send a prompt or message directly to another connected ShadowClaw peer or agent over WebRTC, triggering their orchestration loop and returning their answer. Use this to ask another agent to perform a task, answer a question, or analyze data.`,input_schema:{type:`object`,properties:{peer_id:{type:`string`,description:`The PeerJS peer ID or client ID of the target agent to prompt.`},prompt:{type:`string`,description:`The prompt, question, or instruction for the peer agent.`},timeout_seconds:{type:`number`,description:`Optional timeout in seconds to wait for the peer agent's response (default: 120).`}},required:[`peer_id`,`prompt`]}},SO={name:`list_peers`,description:`List the currently connected peers or clients available over WebRTC and the control plane. Returns peer IDs and device labels so you know which peers you can prompt or collaborate with.`,input_schema:{type:`object`,properties:{}}}})),$7e,e9e=R((()=>{$7e={name:`activate_skill`,description:`Load the full instructions for a workspace skill when its description matches the current task.`,input_schema:{type:`object`,properties:{name:{type:`string`,description:`The exact skill name from the available skills catalog.`}},required:[`name`]}}})),t9e=/* @__PURE__ */ pt({TOOL_DEFINITIONS:()=>CO,activate_skill:()=>$7e,list_peers:()=>SO,prompt_peer:()=>xO}),CO,wO=R((()=>{m5e(),_5e(),x5e(),T5e(),D5e(),A5e(),N5e(),F5e(),R5e(),H5e(),W5e(),K5e(),o7e(),j7e(),z7e(),W7e(),Z7e(),Q7e(),e9e(),CO=[g5e,q5e,p5e,h5e,J5e,Y5e,B7e,M7e,X5e,F7e,Y7e,Z5e,L7e,y5e,b5e,I7e,C5e,S5e,G5e,s7e,c7e,l7e,u7e,d7e,f7e,p7e,m7e,h7e,g7e,_7e,v7e,y7e,b7e,x7e,S7e,C7e,w7e,T7e,E7e,D7e,O7e,k7e,A7e,V7e,E5e,H7e,B5e,Q5e,SO,U7e,N7e,M5e,v5e,j5e,$5e,e7e,t7e,xO,J7e,n7e,k5e,O5e,V5e,q7e,R7e,r7e,i7e,L5e,I5e,U5e,G7e,X7e,P5e,P7e,w5e,a7e,K7e]})),TO=R((()=>{wO()})),EO,DO=R((()=>{EO={id:`__builtin_default`,name:`Default`,providerId:`prompt_api`,enabledToolNames:[`javascript`,`list_files`,`open_file`,`read_file`,`write_file`],customTools:[],systemPromptOverride:"You are a helpful coding assistant.\nContent intended to be rendered as a `Page` (HTML or Markdown) SHOULD include frontmatter (title, created, updated, and slug).\nHTML content intended to be rendered as a `Page` SHOULD USE `<article><h2>${subTitle}</h2>...</article>` for its main body content."}}));function n9e(e,t){if(!t||typeof t!=`object`)throw Error(`Tool at ${e} must be a JSON object`);let n=t,r=typeof n.name==`string`?n.name.trim():``,i=typeof n.description==`string`?n.description.trim():``,a=n.input_schema??n.parameters,o=n.execution??n.evaluation;if(!kO.test(r))throw Error(`Tool name is invalid: ${r||`(missing)`}`);if(!i)throw Error(`Tool ${r} requires a description`);if(!a||typeof a!=`object`)throw Error(`Tool ${r} requires input_schema`);if(!o||typeof o!=`object`)throw Error(`Tool ${r} requires execution`);let s=o,c=s.type;if(c!==`bash`&&c!==`javascript`&&c!==`tool`)throw Error(`Tool ${r} execution type must be bash, javascript, or tool`);if(c===`tool`){if(typeof s.name!=`string`||!kO.test(s.name))throw Error(`Tool ${r} execution requires a valid tool name`);return{name:r,description:i,input_schema:a,execution:{type:c,name:s.name,...s.input&&typeof s.input==`object`?{input:s.input}:{}},path:e}}let l=c===`bash`?`command`:`code`,u=s[l]??s.expression;if(typeof u!=`string`||u.trim()===``)throw Error(`Tool ${r} execution requires ${l}`);return{name:r,description:i,input_schema:a,execution:{type:c,[l]:u},path:e}}async function OO(e,t=un){let n=[],r=[],i=t===`br:main`?[un]:[t,un];for(let t of i)try{let i=await Cp(e,t),a=[];async function o(e,t){for await(let[n,r]of e.entries()){let e=`${t}/${n}`;r.kind===`directory`?await o(r,e):n.endsWith(`.json`)&&e.startsWith(`.agents/tools/`)&&a.push(e)}}try{await o(await(await i.getDirectoryHandle(`.agents`)).getDirectoryHandle(`tools`),`.agents/tools`)}catch{continue}for(let i of a.sort())try{let r=n9e(i,JSON.parse(await Dp(e,t,i)));n.some(e=>e.name===r.name)||n.push(r)}catch(e){r.push(e instanceof Error?e.message:String(e))}}catch{}return{tools:n,diagnostics:r}}async function r9e(e,t=un,n){try{let{tools:r}=await OO(e,t),i=r.find(e=>e.name===n)||null;if(!i)return null;let a=await va(e,V.DECLARATIVE_TOOLS_ENABLED);return Array.isArray(a)&&!a.includes(n)?null:i}catch{return null}}var kO,AO=R((()=>{An(),ya(),wp(),Op(),kO=/^[a-z][a-z0-9_]{0,63}$/}));async function i9e(e){if(typeof e==`string`)return new TextEncoder().encode(e).buffer;if(typeof Blob<`u`&&e instanceof Blob)return e.arrayBuffer();if(e instanceof ArrayBuffer)return e.slice(0);if(ArrayBuffer.isView(e)){let{buffer:t,byteOffset:n,byteLength:r}=e;return t.slice(n,n+r)}return/* @__PURE__ */ new ArrayBuffer(0)}function a9e(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function o9e(e){let t=await i9e(e),r=globalThis.crypto?.subtle??globalThis.window?.crypto?.subtle??(n===void 0?void 0:(await import(`node:crypto`)).webcrypto?.subtle);if(!r)throw Error(`crypto.subtle is not available in current environment`);return a9e(await r.digest(`SHA-256`,t))}var s9e=R((()=>{})),c9e=/* @__PURE__ */ pt({fetchDiscoveryManifest:()=>PO,resolveDiscoveryUrl:()=>jO,resolveManifestRelativeUrl:()=>MO,resolveManifestUrls:()=>l9e,verifySha256Digest:()=>NO});function jO(e){let t=e.trim();if(!t)throw Error(`URL cannot be empty`);let n=t;if(!n.startsWith(`http://`)&&!n.startsWith(`https://`)&&(n=`https://${n}`),n=n.replace(/\/+$/,``),n.endsWith(FO)){let e=n.slice(0,-35).replace(/\/+$/,``);return{baseUrl:e,siteUrl:e,manifestUrl:n}}return{baseUrl:n,siteUrl:n,manifestUrl:`${n}/${FO}`}}function MO(e,t){if(!e)return``;try{return new URL(e,t).href}catch{return e}}function l9e(e,t){let n=JSON.parse(JSON.stringify(e));return Array.isArray(n.tools)&&(n.tools=n.tools.map(e=>({...e,url:MO(e.url,t)}))),Array.isArray(n.scripts)&&(n.scripts=n.scripts.map(e=>({...e,url:MO(e.url,t)}))),Array.isArray(n.skills)&&(n.skills=n.skills.map(e=>({...e,url:MO(e.url,t),tools:Array.isArray(e.tools)?e.tools.map(e=>({...e,url:e.url?MO(e.url,t):void 0})):void 0,scripts:Array.isArray(e.scripts)?e.scripts.map(e=>({...e,url:e.url?MO(e.url,t):void 0})):void 0}))),n}async function NO(e,t){if(!t||!t.startsWith(`sha256:`))return!0;let n=t.slice(7).trim().toLowerCase();return!n||(await o9e(typeof e==`string`?new TextEncoder().encode(e):e)).toLowerCase()===n}async function PO(e,t=globalThis.fetch){let{baseUrl:n,manifestUrl:r}=jO(e),i=await t(r,{headers:{Accept:`application/json`}});if(!i.ok)throw Error(`Failed to fetch discovery manifest: HTTP ${i.status} ${i.statusText}`.trim());let a=await i.json();if(!a||typeof a!=`object`)throw Error(`Invalid discovery manifest: expected a JSON object`);return{manifest:l9e(a,r),siteUrl:n,manifestUrl:r}}var FO,IO=R((()=>{s9e(),FO=`.well-known/agent-skills/index.json`})),u9e=/* @__PURE__ */ pt({importRemoteArtifacts:()=>VO,importRemoteScript:()=>zO,importRemoteSkill:()=>BO,importRemoteTool:()=>RO});function LO(e){return e?.targetSubdir?e.targetSubdir:e?.siteSlug?`imported/${e.siteSlug}`:`main`}async function RO(e,t=un,n,r){let i=(n.name||``).trim();if(d9e.has(i))return{name:i,path:``,status:`failed`,error:`Cannot shadow built-in tool: ${i}`};if(!f9e.test(i))return{name:i,path:``,status:`failed`,error:`Invalid tool name: ${i}`};let a=`.agents/tools/${LO(r)}/${i}.json`;try{if(await wD(e,t,a)&&!r?.overwrite)return{name:i,path:a,status:`skipped`};let o=await(r?.fetchFn||globalThis.fetch)(n.url);if(!o.ok)return{name:i,path:a,status:`failed`,error:`HTTP ${o.status} ${o.statusText}`};let s=await o.text();if(n.digest&&!await NO(s,n.digest))return{name:i,path:a,status:`failed`,error:`Integrity verification failed for tool definition`};let c;try{c=JSON.parse(s)}catch{return{name:i,path:a,status:`failed`,error:`Downloaded tool definition is not valid JSON`}}if(n9e(a,c),await yD(e,t,a,JSON.stringify(c,null,2)),r?.autoEnable){let t=await va(e,V.DECLARATIVE_TOOLS_ENABLED),n=new Set(Array.isArray(t)?t:[]);n.add(i),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,Array.from(n))}return{name:i,path:a,status:`imported`}}catch(e){return{name:i,path:a,status:`failed`,error:e instanceof Error?e.message:String(e)}}}async function zO(e,t=un,n,r){let i=(n.name||``).trim(),a=`.agents/scripts/${LO(r)}/${i.endsWith(`.js`)||i.endsWith(`.mjs`)?i:`${i}.js`}`;try{if(await wD(e,t,a)&&!r?.overwrite)return{name:i,path:a,status:`skipped`};let o=await(r?.fetchFn||globalThis.fetch)(n.url);if(!o.ok)return{name:i,path:a,status:`failed`,error:`HTTP ${o.status} ${o.statusText}`};let s=await o.text();return n.digest&&!await NO(s,n.digest)?{name:i,path:a,status:`failed`,error:`Integrity verification failed for script`}:(await yD(e,t,a,s),{name:i,path:a,status:`imported`})}catch(e){return{name:i,path:a,status:`failed`,error:e instanceof Error?e.message:String(e)}}}async function BO(e,t=un,n,r){let i=(n.name||``).trim(),a=`.agents/skills/${LO(r)}/${i}/SKILL.md`;try{if(await wD(e,t,a)&&!r?.overwrite)return{name:i,path:a,status:`skipped`};let o=await(r?.fetchFn||globalThis.fetch)(n.url);if(!o.ok)return{name:i,path:a,status:`failed`,error:`HTTP ${o.status} ${o.statusText}`};let s=await o.text();return n.digest&&!await NO(s,n.digest)?{name:i,path:a,status:`failed`,error:`Integrity verification failed for skill`}:(Ap(a,s),await yD(e,t,a,s),{name:i,path:a,status:`imported`})}catch(e){return{name:i,path:a,status:`failed`,error:e instanceof Error?e.message:String(e)}}}async function VO(e,t=un,n,r,i){let a={tools:[],skills:[],scripts:[],diagnostics:[]},o=new Set(r.toolNames||[]),s=new Set(r.skillNames||[]),c=new Set(r.scriptNames||[]),l=n.tools||[],u=n.skills||[],d=n.scripts||[];for(let e of u)if(s.has(e.name)){if(Array.isArray(e.tools))for(let t of e.tools)o.add(t.name);if(Array.isArray(e.scripts))for(let t of e.scripts)c.add(t.name)}for(let n of d)if(c.has(n.name)){let r=await zO(e,t,n,i);a.scripts.push(r),r.status===`failed`&&r.error&&a.diagnostics.push(`Script ${n.name}: ${r.error}`)}for(let n of l)if(o.has(n.name)){let r=await RO(e,t,n,i);a.tools.push(r),r.status===`failed`&&r.error&&a.diagnostics.push(`Tool ${n.name}: ${r.error}`)}for(let n of u)if(s.has(n.name)){let r=await BO(e,t,n,i);a.skills.push(r),r.status===`failed`&&r.error&&a.diagnostics.push(`Skill ${n.name}: ${r.error}`)}return a}var d9e,f9e,HO=R((()=>{An(),ya(),SD(),bD(),TD(),AO(),TO(),Vwe(),IO(),d9e=new Set(CO.map(e=>e.name)),f9e=/^[a-z][a-z0-9_]{0,63}$/})),p9e,UO,WO=R((()=>{QD(),An(),ya(),SD(),TO(),DO(),AO(),IO(),HO(),p9e=class{_activeProfile;_activeProfileId;_allTools;_customTools;_declarativeTools;_declarativeToolNamesEnabled;_enabledDeclarativeTools;_enabledToolNames;_enabledTools;_profiles;_systemPromptOverride;_webSearchProxyUrl;_webSearchUrl;_webSearchUseProxy;_searchFilesMaxFileBytes;_searchFilesMaxFilesVisited;_searchFilesSkipDirs;constructor(){this._enabledToolNames=new ZD.State(new Set(EO.enabledToolNames)),this._customTools=new ZD.State([]),this._declarativeTools=new ZD.State([]),this._declarativeToolNamesEnabled=new ZD.State(null),this._systemPromptOverride=new ZD.State(``),this._profiles=new ZD.State([]),this._activeProfileId=new ZD.State(EO.id),this._webSearchUseProxy=new ZD.State(!1),this._webSearchProxyUrl=new ZD.State(`/proxy`),this._webSearchUrl=new ZD.State(`https://html.duckduckgo.com/html/?q={query}`),this._searchFilesMaxFileBytes=new ZD.State(524288),this._searchFilesMaxFilesVisited=new ZD.State(1e3),this._searchFilesSkipDirs=new ZD.State(`.git,node_modules,dist,dist-electron,.cache,.nx,.turbo,__pycache__,.venv,venv`),this._allTools=new ZD.Computed(()=>[...CO,...this._customTools.get()]),this._enabledTools=new ZD.Computed(()=>{let e=this._enabledToolNames.get();return this._allTools.get().filter(t=>e.has(t.name))}),this._enabledDeclarativeTools=new ZD.Computed(()=>{let e=this._declarativeTools.get(),t=this._declarativeToolNamesEnabled.get();return!t||t.size===0?[]:e.filter(e=>t.has(e.name))}),this._activeProfile=new ZD.Computed(()=>{let e=this._activeProfileId.get();return e?EO.id===e?EO:this._profiles.get().find(t=>t.id===e)||null:null})}get activeProfile(){return this._activeProfile.get()}get activeProfileId(){return this._activeProfileId.get()}get allTools(){return this._allTools.get()}get customTools(){return this._customTools.get()}get declarativeTools(){return this._declarativeTools.get()}get declarativeToolNamesEnabled(){return this._declarativeToolNamesEnabled.get()}get enabledDeclarativeTools(){return this._enabledDeclarativeTools.get()}get enabledToolNames(){return this._enabledToolNames.get()}get enabledTools(){return this._enabledTools.get()}isDeclarativeToolEnabled(e){let t=this._declarativeToolNamesEnabled.get();return t?t.has(e):!1}async refreshDeclarativeTools(e,t){try{let n=await OO(e,t||`br:main`),r=this.allTools,i=(n?.tools||[]).filter(e=>!r.some(t=>t.name===e.name)),a=this._declarativeTools.get();return a.length===i.length&&a.every((e,t)=>e.name===i[t].name&&e.description===i[t].description&&JSON.stringify(e.execution)===JSON.stringify(i[t].execution))||this._declarativeTools.set(i),i}catch{return this._declarativeTools.get().length>0&&this._declarativeTools.set([]),[]}}async setDeclarativeToolEnabled(e,t,n){let r=this._declarativeToolNamesEnabled.get(),i=new Set(r===null?[]:r);n?i.add(t):i.delete(t),this._declarativeToolNamesEnabled.set(i),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,Array.from(i))}async setAllDeclarativeEnabled(e,t){let n=new Set(t);this._declarativeToolNamesEnabled.set(n),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,t)}async fetchRemoteDiscoveryManifest(e){return await PO(e)}async importFromRemoteSite(e,t,n,r){let i=r?.groupId||`br:main`,a=await VO(e,i,t,n,r);return await this.refreshDeclarativeTools(e,i),a}exportBackup(){return JSON.stringify({enabledTools:[...this._enabledToolNames.get()],customTools:this._customTools.get(),declarativeToolsEnabled:this._declarativeToolNamesEnabled.get()?Array.from(this._declarativeToolNamesEnabled.get()):null,systemPromptOverride:this._systemPromptOverride.get(),profiles:this._profiles.get(),activeProfileId:this._activeProfileId.get(),webSearchUseProxy:this._webSearchUseProxy.get(),webSearchProxyUrl:this._webSearchProxyUrl.get(),webSearchUrl:this._webSearchUrl.get(),searchFilesMaxFileBytes:this._searchFilesMaxFileBytes.get(),searchFilesMaxFilesVisited:this._searchFilesMaxFilesVisited.get(),searchFilesSkipDirs:this._searchFilesSkipDirs.get()},null,2)}findProfilesForProvider(e,t){return this.profiles.filter(n=>!(n.providerId&&n.providerId!==e||n.model&&n.model!==t))}get profiles(){return[EO,...this._profiles.get()]}get systemPromptOverride(){return this._systemPromptOverride.get()}get webSearchProxyUrl(){return this._webSearchProxyUrl.get()}get webSearchUrl(){return this._webSearchUrl.get()}get webSearchUseProxy(){return this._webSearchUseProxy.get()}get searchFilesMaxFileBytes(){return this._searchFilesMaxFileBytes.get()}get searchFilesMaxFilesVisited(){return this._searchFilesMaxFilesVisited.get()}get searchFilesSkipDirs(){return this._searchFilesSkipDirs.get()}get searchFilesSkipDirsSet(){return new Set(this._searchFilesSkipDirs.get().split(`,`).map(e=>e.trim()).filter(Boolean))}async activateProfile(e,t){let n=this.profiles.find(e=>e.id===t);n&&(this._activeProfileId.set(t),this._enabledToolNames.set(new Set(n.enabledToolNames)),this._customTools.set(n.customTools),this._systemPromptOverride.set(n.systemPromptOverride||``),await Promise.all([xD(e,V.ACTIVE_TOOL_PROFILE,t),xD(e,V.ENABLED_TOOLS,n.enabledToolNames),xD(e,V.CUSTOM_TOOLS,n.customTools),xD(e,V.SYSTEM_PROMPT_OVERRIDE,n.systemPromptOverride||``)]))}async addCustomTool(e,t){let n=[...this._customTools.get(),t];this._customTools.set(n);let r=new Set(this._enabledToolNames.get());r.add(t.name),this._enabledToolNames.set(r),await Promise.all([xD(e,V.CUSTOM_TOOLS,n),xD(e,V.ENABLED_TOOLS,[...r])])}async addProfile(e,t){let n=[...this._profiles.get(),t];this._profiles.set(n),await xD(e,V.TOOL_PROFILES,n)}async cloneTool(e,t,n,r){let i=this.allTools.find(e=>e.name===t);if(!i||this.allTools.some(e=>e.name===n))return!1;let a={name:n,description:r||i.description,input_schema:JSON.parse(JSON.stringify(i.input_schema))};return await this.addCustomTool(e,a),!0}async deactivateProfile(e){this._activeProfileId.set(null),await xD(e,V.ACTIVE_TOOL_PROFILE,null)}async deleteProfile(e,t){if(t===EO.id)return;let n=this._profiles.get().filter(e=>e.id!==t);this._profiles.set(n),this._activeProfileId.get()===t&&(this._activeProfileId.set(null),await xD(e,V.ACTIVE_TOOL_PROFILE,null)),await xD(e,V.TOOL_PROFILES,n)}async importBackup(e,t){let n=JSON.parse(t);Array.isArray(n.enabledTools)&&(this._enabledToolNames.set(new Set(n.enabledTools)),await xD(e,V.ENABLED_TOOLS,n.enabledTools)),Array.isArray(n.customTools)&&(this._customTools.set(n.customTools),await xD(e,V.CUSTOM_TOOLS,n.customTools)),typeof n.systemPromptOverride==`string`&&(this._systemPromptOverride.set(n.systemPromptOverride),await xD(e,V.SYSTEM_PROMPT_OVERRIDE,n.systemPromptOverride)),Array.isArray(n.profiles)&&(this._profiles.set(n.profiles),await xD(e,V.TOOL_PROFILES,n.profiles)),(typeof n.activeProfileId==`string`||n.activeProfileId===null)&&(this._activeProfileId.set(n.activeProfileId),await xD(e,V.ACTIVE_TOOL_PROFILE,n.activeProfileId)),typeof n.webSearchUseProxy==`boolean`&&(this._webSearchUseProxy.set(n.webSearchUseProxy),await xD(e,V.WEB_SEARCH_USE_PROXY,n.webSearchUseProxy?`true`:`false`)),typeof n.webSearchProxyUrl==`string`&&(this._webSearchProxyUrl.set(n.webSearchProxyUrl),await xD(e,V.WEB_SEARCH_PROXY_URL,n.webSearchProxyUrl)),typeof n.webSearchUrl==`string`&&(this._webSearchUrl.set(n.webSearchUrl),await xD(e,V.WEB_SEARCH_URL,n.webSearchUrl)),typeof n.searchFilesMaxFileBytes==`number`&&n.searchFilesMaxFileBytes>0&&(this._searchFilesMaxFileBytes.set(n.searchFilesMaxFileBytes),await xD(e,V.SEARCH_FILES_MAX_FILE_BYTES,String(n.searchFilesMaxFileBytes))),typeof n.searchFilesMaxFilesVisited==`number`&&n.searchFilesMaxFilesVisited>0&&(this._searchFilesMaxFilesVisited.set(n.searchFilesMaxFilesVisited),await xD(e,V.SEARCH_FILES_MAX_FILES_VISITED,String(n.searchFilesMaxFilesVisited))),typeof n.searchFilesSkipDirs==`string`&&(this._searchFilesSkipDirs.set(n.searchFilesSkipDirs),await xD(e,V.SEARCH_FILES_SKIP_DIRS,n.searchFilesSkipDirs)),Array.isArray(n.declarativeToolsEnabled)?(this._declarativeToolNamesEnabled.set(new Set(n.declarativeToolsEnabled)),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,n.declarativeToolsEnabled)):n.declarativeToolsEnabled===null&&(this._declarativeToolNamesEnabled.set(null),await xD(e,V.DECLARATIVE_TOOLS_ENABLED,null))}async load(e){let[t,n,r,i,a,o,s,c,l,u,d,f]=await Promise.all([va(e,V.ENABLED_TOOLS),va(e,V.CUSTOM_TOOLS),va(e,V.SYSTEM_PROMPT_OVERRIDE),va(e,V.TOOL_PROFILES),va(e,V.ACTIVE_TOOL_PROFILE),va(e,V.WEB_SEARCH_USE_PROXY),va(e,V.WEB_SEARCH_PROXY_URL),va(e,V.WEB_SEARCH_URL),va(e,V.SEARCH_FILES_MAX_FILE_BYTES),va(e,V.SEARCH_FILES_MAX_FILES_VISITED),va(e,V.SEARCH_FILES_SKIP_DIRS),va(e,V.DECLARATIVE_TOOLS_ENABLED)]);if(Array.isArray(t)&&this._enabledToolNames.set(new Set(t)),Array.isArray(n)&&this._customTools.set(n),Array.isArray(f)&&this._declarativeToolNamesEnabled.set(new Set(f)),typeof r==`string`&&this._systemPromptOverride.set(r),Array.isArray(i)&&this._profiles.set(i),typeof a==`string`&&this._activeProfileId.set(a),o!=null){let e=String(o).toLowerCase();this._webSearchUseProxy.set(e===`true`||e===`1`)}if(typeof s==`string`&&s.trim().length>0&&this._webSearchProxyUrl.set(s.trim()),typeof c==`string`&&c.trim().length>0&&this._webSearchUrl.set(c.trim()),l!=null){let e=Number(l);Number.isFinite(e)&&e>0&&this._searchFilesMaxFileBytes.set(e)}if(u!=null){let e=Number(u);Number.isFinite(e)&&e>0&&this._searchFilesMaxFilesVisited.set(e)}typeof d==`string`&&d.trim().length>0&&this._searchFilesSkipDirs.set(d.trim())}async setWebSearchProxyUrl(e,t){let n=t.trim()||`/proxy`;this._webSearchProxyUrl.set(n),await xD(e,V.WEB_SEARCH_PROXY_URL,n)}async setWebSearchUrl(e,t){let n=t.trim()||`https://html.duckduckgo.com/html/?q={query}`;this._webSearchUrl.set(n),await xD(e,V.WEB_SEARCH_URL,n)}async setWebSearchUseProxy(e,t){let n=!!t;this._webSearchUseProxy.set(n),await xD(e,V.WEB_SEARCH_USE_PROXY,n?`true`:`false`)}async setSearchFilesMaxFileBytes(e,t){let n=Math.max(1,Math.round(t));this._searchFilesMaxFileBytes.set(n),await xD(e,V.SEARCH_FILES_MAX_FILE_BYTES,String(n))}async setSearchFilesMaxFilesVisited(e,t){let n=Math.max(1,Math.round(t));this._searchFilesMaxFilesVisited.set(n),await xD(e,V.SEARCH_FILES_MAX_FILES_VISITED,String(n))}async setSearchFilesSkipDirs(e,t){let n=t.trim();this._searchFilesSkipDirs.set(n),await xD(e,V.SEARCH_FILES_SKIP_DIRS,n)}async removeCustomTool(e,t){let n=this._customTools.get().filter(e=>e.name!==t);this._customTools.set(n);let r=new Set(this._enabledToolNames.get());r.delete(t),this._enabledToolNames.set(r),await Promise.all([xD(e,V.CUSTOM_TOOLS,n),xD(e,V.ENABLED_TOOLS,[...r])])}async saveToActiveProfile(e){let t=this._activeProfileId.get();if(!t)return;let n=this._profiles.get().find(e=>e.id===t);if(!n)return;let r={...n,enabledToolNames:[...this._enabledToolNames.get()],customTools:[...this._customTools.get()],systemPromptOverride:this._systemPromptOverride.get()};await this.updateProfile(e,r)}async setAllEnabled(e,t){this._enabledToolNames.set(new Set(t));let n=[xD(e,V.ENABLED_TOOLS,t)];this._activeProfileId.get()&&(this._activeProfileId.set(null),n.push(xD(e,V.ACTIVE_TOOL_PROFILE,null))),await Promise.all(n)}async setSystemPromptOverride(e,t){this._systemPromptOverride.set(t),await xD(e,V.SYSTEM_PROMPT_OVERRIDE,t)}async setToolEnabled(e,t,n){let r=new Set(this._enabledToolNames.get());n?r.add(t):r.delete(t),this._enabledToolNames.set(r);let i=[xD(e,V.ENABLED_TOOLS,[...r])];this._activeProfileId.get()&&(this._activeProfileId.set(null),i.push(xD(e,V.ACTIVE_TOOL_PROFILE,null))),await Promise.all(i)}async updateProfile(e,t){let n=this._profiles.get().map(e=>e.id===t.id?t:e);this._profiles.set(n),await xD(e,V.TOOL_PROFILES,n)}},UO=new p9e}));function m9e(e){for(let t of KO)if(t.test(e))return!0;return!1}function h9e(e){let t=String(e||``),n=t;for(let e of KO)t=t.replace(e,``);return t!==n&&(t=t.replace(/^[ \t]+$/gm,``),t=t.replace(/\n{3,}/g,`
|
|
3832
3832
|
|
|
3833
3833
|
`)),t}function GO(e,t){let n=h9e(e);return n!==e&&m9e(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}var KO,qO=R((()=>{KO=[/<\|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 JO(e,t,n,r){return{type:`thinking-log`,payload:{groupId:e,level:t,timestamp:Date.now(),label:n,message:r||``}}}var YO=R((()=>{}));function XO(e,t,n){return{type:`tool-activity`,payload:{groupId:e,tool:t,status:n}}}var ZO=R((()=>{}));async function QO(e,t,n,r){let{dirs:i,filename:a}=Tp(n);for(let n=0;n<2;n++)try{let n=await Cp(e,t);for(let e of i)n=await n.getDirectoryHandle(e,{create:!0});let o=await n.getFileHandle(a,{create:!0});try{await gD(o,r);return}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await up(e)).type===`opfs`))throw t}let s=t.replace(/:/g,`-`);await _D([ap(),`groups`,s,...i,a],r);return}catch(e){if(n===0&&lp(e)){cp();continue}throw e}}var g9e=R((()=>{wp(),Ep(),fp(),vD()}));function _9e(){return new Promise((e,t)=>{let n=indexedDB.open(y9e,1);n.onupgradeneeded=()=>{n.result.createObjectStore(tk)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async function v9e(){let e=await _9e();if(!e)return null;let t=await new Promise((t,n)=>{let r=e.transaction(tk,`readonly`).objectStore(tk).get(b9e);r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)});if(t)return e.close(),t;let n=await crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);try{await new Promise((t,r)=>{let i=e.transaction(tk,`readwrite`);i.objectStore(tk).put(n,b9e),i.oncomplete=()=>t(),i.onerror=()=>r(i.error)})}finally{e.close()}return n}async function $O(e){let t=await v9e();if(!t)return null;let n=crypto.getRandomValues(new Uint8Array(nk)),r=await crypto.subtle.encrypt({name:`AES-GCM`,iv:n},t,new TextEncoder().encode(e)),i=new Uint8Array(n.length+new Uint8Array(r).length);return i.set(n),i.set(new Uint8Array(r),n.length),btoa(String.fromCharCode(...i))}async function ek(e){let t=await v9e();if(!t)return null;let n=Uint8Array.from(atob(e),e=>e.charCodeAt(0)),r=n.slice(0,nk),i=n.slice(nk),a=await crypto.subtle.decrypt({name:`AES-GCM`,iv:r},t,i);return new TextDecoder().decode(a)}var y9e,tk,b9e,nk,rk=R((()=>{y9e=`shadowclaw-keystore`,tk=`keys`,b9e=`api-key-encryption`,nk=12}));function x9e(e){return!e||e.authMode===`token`||e.authMode===`pat`?`token`:e.authMode===`basic`?`basic`:e.authMode===`oauth`||e.oauthProviderId||e.oauthClientId||e.oauthClientSecret||e.refreshToken||e.accessTokenExpiresAt||e.tokenType||e.oauthReauthRequired?`oauth`:`token`}var S9e=R((()=>{}));function ik(e){return x9e(e)}function C9e(e,t){return ik(e)!==`oauth`||e.oauthReauthRequired||!e.refreshToken||!e.oauthProviderId||!e.oauthClientId?!1:t.forceRefresh?!0:e.accessTokenExpiresAt?e.accessTokenExpiresAt<=Date.now()+k9e:!1}async function w9e(e,t,n){if(!n.refreshToken||!n.oauthProviderId||!n.oauthClientId)return n;let r=await ek(n.refreshToken);if(!r)return n;let i=n.oauthClientSecret?await ek(n.oauthClientSecret):void 0,a=async r=>{let i=t.findIndex(e=>e.id===n.id);i!==-1&&(t[i]=r,await xD(e,V.SERVICE_ACCOUNTS,t))},o=async()=>{let e=(n.oauthRefreshFailureCount||0)+1,t=e>=A9e,r={...n,oauthRefreshFailureCount:e,oauthReauthRequired:t,oauthReauthRequiredAt:t?n.oauthReauthRequiredAt||Date.now():void 0};return await a(r),r};try{let e=await fetch(`/oauth/refresh`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({providerId:n.oauthProviderId,clientId:n.oauthClientId,clientSecret:i,refreshToken:r,scope:n.scopes,tokenUrl:n.oauthCustomTokenUrl})});if(!e.ok)return o();let t=await e.json();if(!t.accessToken)return o();let s=await $O(t.accessToken);if(!s)return o();let c=n.refreshToken;if(t.refreshToken){let e=await $O(t.refreshToken);e&&(c=e)}let l={...n,token:s,refreshToken:c,accessTokenExpiresAt:t.expiresIn?Date.now()+t.expiresIn*1e3:n.accessTokenExpiresAt,tokenType:t.tokenType||n.tokenType,scopes:t.scope?t.scope.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):n.scopes,oauthRefreshFailureCount:0,oauthReauthRequired:!1,oauthReauthRequiredAt:void 0};return await a(l),l}catch{return o()}}function T9e(e,t){if(e.oauthProviderId){let t=Zt(e.oauthProviderId);if(t)return t}let n=[e.service,e.hostPattern,t].filter(e=>!!e).map(e=>e.toLowerCase());for(let e of Object.values(Sn))if([e.providerId,...e.aliases||[]].map(e=>e.toLowerCase()).some(e=>n.some(t=>t.includes(e))))return e;return null}function E9e(e,t){let n=ik(e),r=T9e(e,t);if(r){let e;return e=n===`oauth`?r.tokenAuth.oauth:n===`basic`&&r.tokenAuth.basic?r.tokenAuth.basic:r.tokenAuth.token,{headerName:e.headerName,headerPrefix:e.headerPrefix||``}}return{headerName:`Authorization`,headerPrefix:n===`basic`?`Basic `:`Bearer `}}function D9e(e,t){let n=[],r=-1,i=t.toLowerCase();for(let t of e){if(!t.hostPattern)continue;let e=t.hostPattern.toLowerCase();i.includes(e)&&(e.length>r?(r=e.length,n.length=0,n.push(t)):e.length===r&&n.push(t))}return n}function O9e(e,t){return e.length?t&&e.find(e=>ik(e)===t)||e[0]:void 0}async function ak(e,t,n={}){let r=await va(e,V.SERVICE_ACCOUNTS),i=Array.isArray(r)?r:[];if(i.length===0)return;let a;if(n.accountId&&(a=i.find(e=>e.id===n.accountId)),!a&&t){let e=D9e(i,t);a=n.authMode?O9e(e,n.authMode):O9e(e,e[0]?T9e(e[0],t)?.defaultMode:void 0)}if(!a){let t=await va(e,V.SERVICE_DEFAULT_ACCOUNT);t&&(a=i.find(e=>e.id===t))}if(!a&&n.authMode&&(a=O9e(i,n.authMode)),a||=i[0],!a)return;if(C9e(a,n)&&(a=await w9e(e,i,a)),ik(a)===`oauth`&&a.oauthReauthRequired)return{token:``,service:a.service,hostPattern:a.hostPattern,headerName:`Authorization`,headerValue:``,accountId:a.id,authMode:`oauth`,reauthRequired:!0};let o=``;a.token&&(o=await ek(a.token)??``);let{headerName:s,headerPrefix:c}=E9e(a,t),l=o;ik(a)===`basic`&&a.basicUsername&&(l=btoa(`${a.basicUsername}:${o}`));let u=c?`${c}${l}`:l;return{token:o,service:a.service,hostPattern:a.hostPattern,headerName:s,headerValue:u,accountId:a.id,authMode:ik(a)}}var k9e,A9e,j9e=R((()=>{An(),ya(),SD(),rk(),S9e(),k9e=6e4,A9e=3}));function ok(e){return x9e(e)}function M9e(e){switch(e){case`azure-devops`:return`azure_devops`;default:return e}}function N9e(e){if(!e)return`generic`;let t=e.toLowerCase();return t.includes(`github`)?`github`:t.includes(`dev.azure.com`)||t.includes(`visualstudio.com`)?`azure-devops`:t.includes(`gitlab`)?`gitlab`:`generic`}function P9e(e){if(e.reauthRequired)return{};let t=e.provider||N9e(e.hostPattern||``),n=M9e(t),r=e.authMode||`token`;if(e.token&&n===`azure_devops`&&Qt(n,r,`git_remote`)?.headerPrefix===`Basic `)return{Authorization:`Basic ${btoa(`:`+e.token)}`};if(t===`azure-devops`&&e.username&&e.password)return{Authorization:`Basic ${btoa(e.username+`:`+e.password)}`};if(e.token){let t=Qt(n,r,`git_remote`);return t?.headerName?{[t.headerName]:`${t.headerPrefix||``}${e.token}`}:{Authorization:`Bearer ${e.token}`}}return{}}function F9e(e){try{let t=new URL(e),n=t.pathname.replace(/\/+$/,``);return n?t.hostname+n:t.hostname}catch{return}}function I9e(e,t){let n=t.toLowerCase(),r=[],i=-1;for(let t of e){if(!t.hostPattern)continue;let e=t.hostPattern.toLowerCase();n.includes(e)&&(e.length>i?(i=e.length,r.length=0,r.push(t)):e.length===i&&r.push(t))}return r}function L9e(e,t){if(!e.length)return;if(!t)return e[0];let n=e.find(e=>ok(e)===t);if(n)return n;if(t===`token`){let t=e.find(e=>ok(e)===`token`&&!e.authMode);if(t)return t}return e[0]}async function sk(e){if(e)return await ek(e)??void 0}function R9e(e,t){return ok(e)!==`oauth`||e.oauthReauthRequired||!e.refreshToken||!e.oauthProviderId||!e.oauthClientId?!1:t.forceRefresh?!0:e.accessTokenExpiresAt?e.accessTokenExpiresAt<=Date.now()+H9e:!1}async function z9e(e,t,n){if(!n.refreshToken||!n.oauthProviderId||!n.oauthClientId)return n;let r=await sk(n.refreshToken);if(!r)return n;let i=n.oauthClientSecret?await sk(n.oauthClientSecret):void 0,a=async r=>{let i=t.findIndex(e=>e.id===n.id);i!==-1&&(t[i]=r,await xD(e,V.GIT_ACCOUNTS,t))},o=async()=>{let e=(n.oauthRefreshFailureCount||0)+1,t=e>=U9e,r={...n,oauthRefreshFailureCount:e,oauthReauthRequired:t,oauthReauthRequiredAt:t?n.oauthReauthRequiredAt||Date.now():void 0};return await a(r),r};try{let e=await fetch(`/oauth/refresh`,{body:JSON.stringify({clientId:n.oauthClientId,clientSecret:i,providerId:n.oauthProviderId,refreshToken:r,scope:n.scopes}),headers:{"content-type":`application/json`},method:`POST`});if(!e.ok)return o();let t=await e.json();if(!t.accessToken)return o();let s=await $O(t.accessToken);if(!s)return o();let c=n.refreshToken;if(t.refreshToken){let e=await $O(t.refreshToken);e&&(c=e)}let l={...n,token:s,refreshToken:c,accessTokenExpiresAt:t.expiresIn?Date.now()+t.expiresIn*1e3:n.accessTokenExpiresAt,tokenType:t.tokenType||n.tokenType,scopes:t.scope?t.scope.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):n.scopes,oauthRefreshFailureCount:0,oauthReauthRequired:!1,oauthReauthRequiredAt:void 0};return await a(l),l}catch{return o()}}async function ck(e,t,n={}){let r=await va(e,V.GIT_ACCOUNTS);return Array.isArray(r)&&r.length>0?B9e(e,r,t,n):V9e(e)}async function B9e(e,t,n,r={}){let i;if(r.accountId&&(i=t.find(e=>e.id===r.accountId)),!i&&n){let e=F9e(n);e&&(i=L9e(I9e(t,e),r.authMode))}if(!i){let r=await va(e,V.GIT_DEFAULT_ACCOUNT);if(r){let e=t.find(e=>e.id===r);if(e){if(!n)i=e;else{let t=F9e(n);if(t&&e.hostPattern){let n=t?.toLowerCase(),r=e.hostPattern.toLowerCase();n?.includes(r)&&(i=e)}}}}}if(!i&&!n&&r.authMode&&(i=L9e(t,r.authMode)),!i&&!n&&(i=t[0]),!i)return{authMode:`token`,authorEmail:void 0,authorName:void 0,password:void 0,provider:`generic`,token:void 0,username:void 0};R9e(i,r)&&(i=await z9e(e,t,i));let a=i.provider||N9e(i.hostPattern||``);return ok(i)===`oauth`&&i.oauthReauthRequired?{accountId:i.id,authMode:`oauth`,authorEmail:i.authorEmail||void 0,authorName:i.authorName||void 0,hostPattern:i.hostPattern||void 0,password:void 0,provider:a,reauthRequired:!0,token:void 0,username:i.username||void 0}:{accountId:i.id,authMode:ok(i),authorEmail:i.authorEmail||void 0,authorName:i.authorName||void 0,hostPattern:i.hostPattern||void 0,password:await sk(i.password),provider:a,token:await sk(i.token),username:i.username||void 0}}async function V9e(e){let t=await va(e,V.GIT_TOKEN),n=await va(e,V.GIT_PASSWORD);return{authMode:`token`,authorEmail:await va(e,V.GIT_AUTHOR_EMAIL)||void 0,authorName:await va(e,V.GIT_AUTHOR_NAME)||void 0,password:n?await sk(n):void 0,provider:`generic`,token:t?await sk(t):void 0,username:await va(e,V.GIT_USERNAME)||void 0}}var H9e,U9e,W9e=R((()=>{An(),S9e(),rk(),ya(),SD(),H9e=6e4,U9e=3}));function G9e(e){if(typeof e!=`string`||!e.trim())return!1;try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`}catch{return!1}}function K9e(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(!n.serviceType||!n.authType)return null;if(n.serviceType!==t)throw Error(`Credential ref serviceType must match connection serviceType`);return{serviceType:n.serviceType,authType:n.authType,providerId:n.providerId||void 0,accountId:n.accountId||void 0,gitAccountId:n.gitAccountId||void 0,headerName:n.headerName||void 0,encryptedValue:n.encryptedValue||void 0}}function q9e(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.id||!t.label||!t.serviceType||!t.transport||typeof t.enabled!=`boolean`||typeof t.createdAt!=`number`||typeof t.updatedAt!=`number`||!G9e(t.serverUrl)||t.serviceType!==`mcp_remote`&&t.serviceType!==`webmcp_local`||t.transport!==`streamable_http`&&t.transport!==`sse`&&t.transport!==`websocket`?null:{id:t.id,label:t.label,serviceType:t.serviceType,serverUrl:t.serverUrl,transport:t.transport,enabled:t.enabled,autoReconnectOAuth:t.autoReconnectOAuth===!0,createdAt:t.createdAt,updatedAt:t.updatedAt,credentialRef:K9e(t.credentialRef,t.serviceType)}}async function J9e(e){let t=await va(e,V.REMOTE_MCP_CONNECTIONS);if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=q9e(e);t&&n.push(t)}return n}async function Y9e(e){return J9e(e)}async function X9e(e,t){if(!t)return null;let n=await J9e(e);return n.find(e=>e.id===t)||n.find(e=>e.label.toLowerCase()===t.toLowerCase())||null}var lk=R((()=>{An(),ya(),SD()}));function Z9e(e){return e===`oauth`?`oauth`:`token`}async function Q9e(e,t,n={}){let r=await X9e(e,t);if(!r)return null;let i=r.credentialRef;if(!i||i.authType===`none`)return{connection:r,authType:`none`,headers:{}};if(i.authType===`custom_header`){if(!i.headerName||!i.encryptedValue)return{connection:r,authType:`custom_header`,headers:{}};let e=await ek(i.encryptedValue);return{connection:r,authType:`custom_header`,headers:e?{[i.headerName]:e}:{}}}let a=Z9e(i.authType);if(i.accountId){let t=await ak(e,r.serverUrl,{accountId:i.accountId,authMode:a,forceRefresh:n.forceRefresh});return t?t.reauthRequired?{connection:r,authType:i.authType,headers:{},reauthRequired:!0}:{connection:r,authType:i.authType,headers:t.headerValue?{[t.headerName]:t.headerValue}:{}}:{connection:r,authType:i.authType,headers:{}}}if(i.gitAccountId){let t=await ck(e,r.serverUrl,{accountId:i.gitAccountId,authMode:a,forceRefresh:n.forceRefresh});return t.reauthRequired?{connection:r,authType:i.authType,headers:{},reauthRequired:!0}:{connection:r,authType:i.authType,headers:P9e(t)}}return{connection:r,authType:i.authType,headers:{}}}var $9e=R((()=>{rk(),lk(),j9e(),W9e()}));function eet(e){return typeof e==`object`&&!!e&&`method`in e&&`id`in e&&!(`result`in e)&&!(`error`in e)}function tet(e){let t=(e.requestedSchema||{}).properties||{},n={};for(let[e,r]of Object.entries(t))`default`in r?n[e]=r.default:r.type===`boolean`&&(n[e]=!0);return n}function net(e,t){return!e.headers||typeof e.headers.get!=`function`?null:e.headers.get(t)}function ret(e){return/no valid session id provided/i.test(e)}function iet(e,t){let n=t&&`error`in t?t.error.message||`Remote MCP JSON-RPC error`:``;return ret(n)?new het(n):e.ok?Error(n||`Remote MCP JSON-RPC error`):new fk(e.status,n?`Remote MCP HTTP error: ${e.status} (${n})`:`Remote MCP HTTP error: ${e.status}`)}function aet(e){if(!e)return null;let t=null,n=e.split(/\r?\n/);for(let e of n){let n=e.trim();if(!n.startsWith(`data:`))continue;let r=n.slice(5).trim();if(r&&r!==`[DONE]`)try{let e=JSON.parse(r);e&&typeof e==`object`&&`jsonrpc`in e&&(t=e)}catch{}}return t}function oet(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}async function uk(e,t,n){let r=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`,...t},body:JSON.stringify(n)}),i=(net(r,`content-type`)||``).toLowerCase(),a=null;if(typeof r.text==`function`){let e=await r.text();a=i.includes(`text/event-stream`)?aet(e):oet(e)}else try{a=await r.json()}catch{a=null}return{response:r,payload:a}}async function set(e,t,n){let{response:r,payload:i}=await uk(e,{...t,"mcp-session-id":n},{jsonrpc:`2.0`,method:`notifications/initialized`,params:{}});if(!r.ok||i&&`error`in i)throw iet(r,i)}async function cet(e,t,n){let r=dk.get(e);if(r?.sessionId)return r;let{response:i,payload:a}=await uk(t,n,{jsonrpc:`2.0`,id:`initialize-${Date.now().toString(36)}`,method:`initialize`,params:{protocolVersion:`2025-03-26`,capabilities:{elicitation:{}},clientInfo:{name:`shadowclaw-remote-mcp-client`,version:`1.0.0`}}});if(!i.ok||a&&`error`in a)throw iet(i,a);let o=net(i,`mcp-session-id`)||`local-${Date.now()}-${Math.random().toString(36).slice(2)}`,s={sessionId:o,protocolVersion:net(i,`mcp-protocol-version`)||a?.result?.protocolVersion,lastUsedAt:Date.now()};return await set(t,n,o),dk.set(e,s),s}async function uet(e,t,n,r,i){let a=await cet(e,t,n),o=async e=>{let a={jsonrpc:`2.0`,id:Date.now().toString(),method:r,params:i||{}},o={...n,"mcp-session-id":e},{response:s,payload:c}=await uk(t,o,a),l=0;for(;eet(c)&&l<5&&(l++,c.method===`elicitation/create`);){let e=tet(c.params||{});({response:s,payload:c}=await uk(t,o,{jsonrpc:`2.0`,id:c.id,result:{action:`accept`,content:e}}))}if(eet(c))throw Error(`Unsupported server request: ${c.method}`);if(!s.ok||!c||`error`in c)throw iet(s,c);return c.result};try{let t=await o(a.sessionId);return a.lastUsedAt=Date.now(),dk.set(e,a),t}catch(r){if(!(r instanceof het))throw r;dk.delete(e),a=await cet(e,t,n);let i=await o(a.sessionId);return a.lastUsedAt=Date.now(),dk.set(e,a),i}}function det(e){e&&dk.delete(e)}async function fet(e,t,n,r){let i=await Q9e(e,t);if(!i)throw Error(`Remote MCP connection not found`);if(i.reauthRequired)throw new pk(t);let{connection:a,authType:o,headers:s}=i;if(a.transport!==`streamable_http`)throw Error(`Unsupported remote MCP transport`);try{return await uet(t,a.serverUrl,s,n,r)}catch(i){if(!(i instanceof fk)||i.status!==401||o!==`oauth`)throw i;det(t);let a=await Q9e(e,t,{forceRefresh:!0});if(!a||a.reauthRequired)throw new pk(t);try{return await uet(t,a.connection.serverUrl,a.headers,n,r)}catch(e){throw e instanceof fk&&e.status===401?new pk(t):e}}}async function pet(e,t){let n=await fet(e,t,`tools/list`);return Array.isArray(n.tools)?n.tools:[]}async function met(e,t,n,r={}){return fet(e,t,`tools/call`,{name:n,arguments:r})}var dk,het,fk,pk,get=R((()=>{$9e(),dk=/* @__PURE__ */ new Map,het=class extends Error{constructor(e){super(e),this.name=`InvalidRemoteMcpSessionError`}},fk=class extends Error{status;constructor(e,t){super(t),this.name=`HttpRemoteMcpError`,this.status=e}},pk=class extends Error{connectionId;constructor(e){super(`OAuth reconnect required for remote MCP connection`),this.name=`McpReauthRequiredError`,this.connectionId=e}}}));async function _et(e,t,n,r){let{dirs:i,filename:a}=Tp(n);for(let n=0;n<2;n++)try{let n=await Cp(e,t);for(let e of i)n=await n.getDirectoryHandle(e,{create:!0});let o=await n.getFileHandle(a,{create:!0});try{await gD(o,r);return}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await up(e)).type===`opfs`))throw t}let s=t.replace(/:/g,`-`);await _D([ap(),`groups`,s,...i,a],r);return}catch(e){if(n===0&&lp(e)){cp();continue}throw e}}var vet=R((()=>{wp(),Ep(),fp(),vD()}));function yet(){return[...bet].sort((e,t)=>e.id.localeCompare(t.id))}function mk(e){return e&&bet.find(t=>t.id===e)||null}var bet,xet=R((()=>{bet=[{id:`imap`,name:`IMAP Mail`,protocol:`imap`,description:`Read mailboxes and fetch message metadata/content.`,version:`0.1.0`,actions:[`messages.read`,`messages.send`],authTypes:[`basic_userpass`,`oauth`],serviceTypes:[`http_api`],configurableFields:[`host`,`port`,`secure`,`mailboxPath`,`smtpHost`,`smtpPort`,`smtpSecure`,`fromAddress`,`executionMode`,`pollIntervalSec`]}]}));function Cet(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.serviceType||!t.authType?null:{serviceType:t.serviceType,authType:t.authType,providerId:t.providerId||void 0,accountId:t.accountId||void 0,username:t.username||void 0,headerName:t.headerName||void 0,encryptedSecret:t.encryptedSecret||void 0}}function wet(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.id||!t.label||!t.pluginId||typeof t.enabled!=`boolean`||typeof t.createdAt!=`number`||typeof t.updatedAt!=`number`||!mk(t.pluginId)?null:{id:t.id,label:t.label,pluginId:t.pluginId,enabled:t.enabled,config:t.config&&typeof t.config==`object`?{...t.config}:{},credentialRef:Cet(t.credentialRef),createdAt:t.createdAt,updatedAt:t.updatedAt}}async function hk(e){let t=await va(e,V.INTEGRATION_CONNECTIONS);if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=wet(e);t&&n.push(t)}return n}async function gk(e,t){await xD(e,V.INTEGRATION_CONNECTIONS,t)}async function _k(e){return hk(e)}async function vk(e,t){if(!t)return null;let n=await hk(e);return n.find(e=>e.id===t)||n.find(e=>e.label.toLowerCase()===t.toLowerCase())||null}async function Tet(e,t){if(!t.label?.trim())throw Error(`Email connection label is required`);let n=mk(t.pluginId);if(!n)throw Error(`Unknown email plugin: ${t.pluginId}`);let r=await hk(e),i=Date.now();if(t.id){let a=r.findIndex(e=>e.id===t.id);if(a!==-1){let o=r[a],s={...o,label:t.label.trim(),pluginId:n.id,enabled:t.enabled??o.enabled,config:t.config?{...t.config}:o.config,updatedAt:i};return r[a]=s,await gk(e,r),s}}let a={id:t.id||Mf(),label:t.label.trim(),pluginId:n.id,enabled:t.enabled??!0,config:t.config?{...t.config}:{},credentialRef:null,createdAt:i,updatedAt:i};return r.push(a),await gk(e,r),a}async function Eet(e,t,n){if(!t)return null;let r=await hk(e),i=r.findIndex(e=>e.id===t);if(i===-1)return null;let a={...r[i],credentialRef:n?Cet(n):null,updatedAt:Date.now()};return r[i]=a,await gk(e,r),a}async function Det(e,t){if(!t)return!1;let n=await hk(e),r=n.filter(e=>e.id!==t);return r.length!==n.length&&(await gk(e,r),!0)}var Oet=R((()=>{An(),ya(),SD(),Lf(),xet()}));function ket(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n==`string`){let e=n.trim();e&&t.push({path:e});continue}if(!n||typeof n!=`object`)continue;let e=typeof n.path==`string`?n.path.trim():``;if(!e)continue;let r=typeof n.filename==`string`?n.filename.trim():``,i=typeof n.content_type==`string`?n.content_type.trim():``;t.push({path:e,filename:r||void 0,contentType:i||void 0})}return t}var Aet=R((()=>{}));function jet(e,t=`attachment.bin`){if(!e)return t;let n=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);return n[n.length-1]||t}function Met(e,t={}){let n=t.replacement??`_`,r=t.fallback??`attachment.bin`,i=e.trim();t.stripControlChars&&(i=i.replace(/[\u0000-\u001f\u007f]+/g,``)),t.stripLeadingDots&&(i=i.replace(/^\.+/,``));let a=t.stripControlChars?/[\\/:*?"<>|]/g:/[\\/:*?"<>|\x00-\x1f\u007f]/g;if(t.collapseReplacement&&n){let e=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);i=i.replace(t.stripControlChars?/[\\/:*?"<>|]+/g:/[\\/:*?"<>|\x00-\x1f\u007f]+/g,n),i=i.replace(RegExp(`${e}+`,`g`),n)}else i=i.replace(a,n);return i=i.trim(),t.stripLeadingDots&&(i=i.replace(/^\.+/,``).trim()),i||r}var Net=R((()=>{}));async function yk(e,t,n,r=!1){let i=(typeof n.username==`string`?n.username.trim():``)||t.credentialRef?.username||(typeof t.config.username==`string`?t.config.username:``);if(!i)return`Error: Integration connection ${t.id} is missing username credentials.`;if(t.credentialRef?.authType===`oauth`){let n=t.credentialRef.accountId;if(!n)return`Error: Integration connection ${t.id} is missing linked OAuth account.`;let a=await ak(e,void 0,{accountId:n,authMode:`oauth`,forceRefresh:r});if(!a||a.reauthRequired||!a.token){let e=t.credentialRef?.providerId||`the configured`;return`Error: OAuth account reconnect required for integration ${t.id}.\nOpen Settings -> Integrations, edit this email connection, and click Connect OAuth for ${e} to re-authorize.`}return{authType:`oauth`,username:i,accessToken:a.token}}let a=(typeof n.password==`string`?n.password.trim():``)||t.credentialRef?.encryptedSecret&&await ek(t.credentialRef.encryptedSecret)||``;return a?{authType:`basic_userpass`,username:i,password:a}:`Error: Integration connection ${t.id} is missing password credentials.`}var Pet=R((()=>{rk(),j9e()}));async function Fet(e,t,n,r){let i=Met(r),a=i.lastIndexOf(`.`),o=a>0?i.slice(0,a):i,s=a>0?i.slice(a):``,c=n.trim().replace(/^\/+|\/+$/g,``);for(let n=0;n<1e3;n++){let r=n===0?i:`${o}-${n+1}${s}`,a=c?`${c}/${r}`:r;if(!await wD(e,t,a))return a}return c?`${c}/${Mf()}-${i}`:`${Mf()}-${i}`}var Iet=R((()=>{TD(),Lf(),Net()}));async function Let(e,t,n){let r=typeof t.action==`string`?t.action.trim():``;if(!r)return`Error: manage_email requires action.`;if(r===`list_plugins`){let e=yet();return e.length?e.map(e=>`- ${e.id} (${e.protocol})\n Name: ${e.name}\n Actions: ${e.actions.join(`, `)}\n Auth: ${e.authTypes.join(`, `)}\n Fields: ${e.configurableFields.join(`, `)||`(none)`}`).join(`
|
|
3834
3834
|
|