shadow-claw 1.59.6 → 1.60.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 +6 -2
- package/dist/cli/build/build.js +1 -1
- package/dist/cli/chunk-3C5izdQW.js +1 -0
- package/dist/cli/chunk-B-75h9gX.js +1 -0
- package/dist/cli/{chunk-C9o6lXP3.js → chunk-B7Kn-otm.js} +1 -1
- package/dist/cli/{chunk-YX32FcN7.js → chunk-BBczgswQ.js} +1 -1
- package/dist/cli/{chunk-DcNxjqH6.js → chunk-BE-lYWcn.js} +1 -1
- package/dist/cli/{chunk-DJqHK-qS.js → chunk-BECr0WxI.js} +11 -11
- package/dist/cli/chunk-BEz1PD1_.js +1 -0
- package/dist/cli/chunk-BLzI1Fp2.js +1 -0
- package/dist/cli/{chunk-yiVdvGCJ.js → chunk-BVSC1MNQ.js} +11 -11
- package/dist/cli/{chunk-CX2itile.js → chunk-BdWcep6o.js} +1 -1
- package/dist/cli/{chunk-DLde6nuO.js → chunk-BfTpnSS4.js} +1 -1
- package/dist/cli/{chunk-D2_eAO83.js → chunk-BgvqTf7w.js} +1 -1
- package/dist/cli/chunk-BwsJfUT3.js +1 -0
- package/dist/cli/{chunk--PFY91kE.js → chunk-C9b4b7c_.js} +1 -1
- package/dist/cli/{chunk-D3y7h9Xe.js → chunk-CAw9XYFe.js} +1 -1
- package/dist/cli/chunk-CFCcbFs2.js +396 -0
- package/dist/cli/{chunk-Cnjb8Usu.js → chunk-CTarF4FC.js} +1 -1
- package/dist/cli/{chunk-DM4xsTry.js → chunk-Cbq5hpjb.js} +4 -4
- package/dist/cli/chunk-CjTjKy_v.js +310 -0
- package/dist/cli/chunk-Cjyu4cr_.js +36 -0
- package/dist/cli/{chunk-DUGZPka_.js → chunk-ClMKygjZ.js} +1 -1
- package/dist/cli/chunk-Cppnq1KF.js +1 -0
- package/dist/cli/{chunk-DvemF16v.js → chunk-D9QCNFMO.js} +1 -1
- package/dist/cli/chunk-DB21BMqt.js +7 -0
- package/dist/cli/{chunk-_Vo-o_e3.js → chunk-DHoIWvCc.js} +1 -1
- package/dist/cli/chunk-DZEN9T5y.js +1 -0
- package/dist/cli/{chunk-5rLO4DWS.js → chunk-Dl14OyYO.js} +9 -9
- package/dist/cli/chunk-Dl_vv0dI.js +1 -0
- package/dist/cli/chunk-Dpmfhlyl.js +1 -0
- package/dist/cli/{chunk-BrR1DOBS.js → chunk-Du7Xtucq.js} +1 -1
- package/dist/cli/{chunk-Bc_weULz.js → chunk-DxcDFUi_.js} +1 -1
- package/dist/cli/{chunk-Dt7-hzJU.js → chunk-DyyEWbV7.js} +1 -1
- package/dist/cli/chunk-N0x3mXU0.js +1 -0
- package/dist/cli/{chunk-CGoE4llV.js → chunk-V-w0Bata.js} +1 -1
- package/dist/cli/{chunk-C8DBACtx.js → chunk-ZxDxSSn-.js} +1 -1
- package/dist/cli/chunk-lPvFUkd5.js +7 -0
- package/dist/cli/{chunk-Ctg5L55n.js → chunk-n5s-sCdU.js} +1 -1
- package/dist/cli/{chunk-Dw8GndPD.js → chunk-nD9VPVMq.js} +1 -1
- package/dist/cli/{chunk-Cq_kQohv.js → chunk-rFuy8aS_.js} +1 -1
- package/dist/cli/{chunk-Bq38OubR.js → chunk-wjM6JXWa.js} +1 -1
- package/dist/cli/{chunk-3wTukVof.js → chunk-zcES9rut.js} +1 -1
- package/dist/cli/cli.js +3 -3
- package/dist/headless-agent.js +2 -2
- package/dist/lib/{app-routes-DJdIjp2V.js → app-routes-BXiRvlNl.js} +7 -25
- package/dist/lib/{app-routes-DJdIjp2V.js.map → app-routes-BXiRvlNl.js.map} +1 -1
- package/dist/lib/{attachment-capabilities-Dbb-4ZP5.js → attachment-capabilities-BjkEPip8.js} +2 -2
- package/dist/lib/{attachment-capabilities-Dbb-4ZP5.js.map → attachment-capabilities-BjkEPip8.js.map} +1 -1
- package/dist/lib/{channel-Dlru5ofR.js → channel-DB77spML.js} +3 -3
- package/dist/lib/{channel-Dlru5ofR.js.map → channel-DB77spML.js.map} +1 -1
- package/dist/lib/{chat-template-BuuLY8l7.js → chat-template-DPEKGJhB.js} +2 -2
- package/dist/lib/{chat-template-BuuLY8l7.js.map → chat-template-DPEKGJhB.js.map} +1 -1
- package/dist/lib/{compact-context-BtR55YPU.js → compact-context-Q9t9aL1e.js} +19 -19
- package/dist/lib/{compact-context-BtR55YPU.js.map → compact-context-Q9t9aL1e.js.map} +1 -1
- package/dist/lib/components/common/shadow-claw-provider-model-picker.js +1 -1
- package/dist/lib/components/index.js +27 -27
- package/dist/lib/components/settings/shadow-claw-accounts.js +1 -1
- package/dist/lib/components/settings/shadow-claw-channel-config.js +1 -1
- package/dist/lib/components/settings/shadow-claw-control-plane.js +1 -1
- package/dist/lib/components/settings/shadow-claw-git.js +1 -1
- package/dist/lib/components/settings/shadow-claw-integrations.js +1 -1
- package/dist/lib/components/settings/shadow-claw-llm.js +1 -1
- package/dist/lib/components/settings/shadow-claw-mcp-remote.js +1 -1
- package/dist/lib/components/settings/shadow-claw-networking.js +1 -1
- package/dist/lib/components/settings/shadow-claw-notifications.js +1 -1
- package/dist/lib/components/settings/shadow-claw-peerjs.js +1 -1
- package/dist/lib/components/settings/shadow-claw-storage.js +1 -1
- package/dist/lib/components/settings/shadow-claw-task-server.js +1 -1
- package/dist/lib/components/settings/shadow-claw-webvm.js +1 -1
- package/dist/lib/components/shadow-claw-a2ui.js +1 -1
- package/dist/lib/components/shadow-claw-accounts.js +1 -1
- package/dist/lib/components/shadow-claw-channel-config.js +1 -1
- package/dist/lib/components/shadow-claw-channels.js +1 -1
- package/dist/lib/components/shadow-claw-chat.js +1 -1
- package/dist/lib/components/shadow-claw-control-plane.js +1 -1
- package/dist/lib/components/shadow-claw-conversations.js +1 -1
- package/dist/lib/components/shadow-claw-file-viewer.js +1 -1
- package/dist/lib/components/shadow-claw-files.js +1 -1
- package/dist/lib/components/shadow-claw-git.js +1 -1
- package/dist/lib/components/shadow-claw-integrations.js +1 -1
- package/dist/lib/components/shadow-claw-llm.js +1 -1
- package/dist/lib/components/shadow-claw-mcp-remote.js +1 -1
- package/dist/lib/components/shadow-claw-networking.js +1 -1
- package/dist/lib/components/shadow-claw-notifications.js +1 -1
- package/dist/lib/components/shadow-claw-page-header.js +1 -1
- package/dist/lib/components/shadow-claw-pages.js +1 -1
- package/dist/lib/components/shadow-claw-peerjs.js +1 -1
- package/dist/lib/components/shadow-claw-provider-model-picker.js +1 -1
- package/dist/lib/components/shadow-claw-settings.js +1 -1
- package/dist/lib/components/shadow-claw-storage.js +1 -1
- package/dist/lib/components/shadow-claw-task-server.js +1 -1
- package/dist/lib/components/shadow-claw-tasks.js +1 -1
- package/dist/lib/components/shadow-claw-terminal.js +1 -1
- package/dist/lib/components/shadow-claw-tools.js +1 -1
- package/dist/lib/components/shadow-claw-webvm.js +1 -1
- package/dist/lib/components/shadow-claw.js +1 -1
- package/dist/lib/{config-DxNI3TlW.js → config-BrHR97zt.js} +2 -2
- package/dist/lib/{config-DxNI3TlW.js.map → config-BrHR97zt.js.map} +1 -1
- package/dist/lib/{configure-peer-js-ChDhOZU4.js → configure-peer-js-CgFiwoxY.js} +3 -3
- package/dist/lib/{configure-peer-js-ChDhOZU4.js.map → configure-peer-js-CgFiwoxY.js.map} +1 -1
- package/dist/lib/{connections-DC4NZkJE.js → connections-C1FWsBsE.js} +2 -2
- package/dist/lib/{connections-DC4NZkJE.js.map → connections-C1FWsBsE.js.map} +1 -1
- package/dist/lib/content/build-attachment-content-blocks.d.ts +2 -0
- package/dist/lib/{credentials-5vpz0XPk.js → credentials-CZbngHXW.js} +2 -2
- package/dist/lib/{credentials-5vpz0XPk.js.map → credentials-CZbngHXW.js.map} +1 -1
- package/dist/lib/{discover-skills-CD0sKvAI.js → discover-skills-CXyaWHKi.js} +13 -13
- package/dist/lib/{discover-skills-CD0sKvAI.js.map → discover-skills-CXyaWHKi.js.map} +1 -1
- package/dist/lib/{download-group-file-Dk3qaxhJ.js → download-group-file-D0wgg10Q.js} +2 -2
- package/dist/lib/{download-group-file-Dk3qaxhJ.js.map → download-group-file-D0wgg10Q.js.map} +1 -1
- package/dist/lib/{file-viewer-B4pRW-_G.js → file-viewer-DOfvX6yy.js} +5 -5
- package/dist/lib/{file-viewer-B4pRW-_G.js.map → file-viewer-DOfvX6yy.js.map} +1 -1
- package/dist/lib/{get-or-create-subscriber-id-HCcgDEPz.js → get-or-create-subscriber-id-wyzaML7Z.js} +2 -2
- package/dist/lib/{get-or-create-subscriber-id-HCcgDEPz.js.map → get-or-create-subscriber-id-wyzaML7Z.js.map} +1 -1
- package/dist/lib/{git-B3Q1euc5.js → git-CogDRlEz.js} +5 -5
- package/dist/lib/{git-B3Q1euc5.js.map → git-CogDRlEz.js.map} +1 -1
- package/dist/lib/{iframe-bridge-scripts-D8iuFhUk.js → iframe-bridge-scripts-Dx825LLG.js} +2 -2
- package/dist/lib/{iframe-bridge-scripts-D8iuFhUk.js.map → iframe-bridge-scripts-Dx825LLG.js.map} +1 -1
- package/dist/lib/index.js +28 -28
- package/dist/lib/{init-chat-split-resize-B0ODULx9.js → init-chat-split-resize-Cc0bd2z9.js} +2 -2
- package/dist/lib/{init-chat-split-resize-B0ODULx9.js.map → init-chat-split-resize-Cc0bd2z9.js.map} +1 -1
- package/dist/lib/{init-control-plane-C1FRRmjC.js → init-control-plane-CEGdzgWX.js} +15 -15
- package/dist/lib/{init-control-plane-C1FRRmjC.js.map → init-control-plane-CEGdzgWX.js.map} +1 -1
- package/dist/lib/{invoke-agent-CzN7sVh-.js → invoke-agent-cac3gCsj.js} +11 -11
- package/dist/lib/{invoke-agent-CzN7sVh-.js.map → invoke-agent-cac3gCsj.js.map} +1 -1
- package/dist/lib/{markdown-mbNo7cV3.js → markdown--6vTAPEH.js} +2 -2
- package/dist/lib/{markdown-mbNo7cV3.js.map → markdown--6vTAPEH.js.map} +1 -1
- package/dist/lib/{mcp-reconnect-3T7yWGEY.js → mcp-reconnect-BeqQvNWO.js} +3 -3
- package/dist/lib/{mcp-reconnect-3T7yWGEY.js.map → mcp-reconnect-BeqQvNWO.js.map} +1 -1
- package/dist/lib/{model-ranking-DGNSWYwN.js → model-ranking-BhsJV7vb.js} +2 -2
- package/dist/lib/{model-ranking-DGNSWYwN.js.map → model-ranking-BhsJV7vb.js.map} +1 -1
- package/dist/lib/{move-group-entry-NMTJ59M9.js → move-group-entry-D8dptMg0.js} +5 -5
- package/dist/lib/{move-group-entry-NMTJ59M9.js.map → move-group-entry-D8dptMg0.js.map} +1 -1
- package/dist/lib/{orchestrator-B8FV1V7x.js → orchestrator-BBAwy9Nm.js} +24 -24
- package/dist/lib/{orchestrator-B8FV1V7x.js.map → orchestrator-BBAwy9Nm.js.map} +1 -1
- package/dist/lib/{orchestrator-i_QJ-o22.js → orchestrator-cRBe3lhq.js} +11 -11
- package/dist/lib/orchestrator-cRBe3lhq.js.map +1 -0
- package/dist/lib/{parse-path-DPCn-HwI.js → parse-path-BOHQP_IQ.js} +3 -3
- package/dist/lib/{parse-path-DPCn-HwI.js.map → parse-path-BOHQP_IQ.js.map} +1 -1
- package/dist/lib/{peerjs-z5zeioPV.js → peerjs-BLg8aGUj.js} +8 -8
- package/dist/lib/{peerjs-z5zeioPV.js.map → peerjs-BLg8aGUj.js.map} +1 -1
- package/dist/lib/{process-peer-query-param-CJp7w7AU.js → process-peer-query-param-BnsVnxzH.js} +5 -5
- package/dist/lib/{process-peer-query-param-CJp7w7AU.js.map → process-peer-query-param-BnsVnxzH.js.map} +1 -1
- package/dist/lib/{process-pending-shared-payloads-B6_TlBFA.js → process-pending-shared-payloads-DBZfZOOa.js} +4 -4
- package/dist/lib/{process-pending-shared-payloads-B6_TlBFA.js.map → process-pending-shared-payloads-DBZfZOOa.js.map} +1 -1
- package/dist/lib/{process-room-query-param-C3FFGGn6.js → process-room-query-param-B8EYg_-r.js} +4 -4
- package/dist/lib/{process-room-query-param-C3FFGGn6.js.map → process-room-query-param-B8EYg_-r.js.map} +1 -1
- package/dist/lib/{provider-DcQZypu5.js → provider-BC9KPI14.js} +3 -3
- package/dist/lib/{provider-DcQZypu5.js.map → provider-BC9KPI14.js.map} +1 -1
- package/dist/lib/{push-client-Cx5rMs6J.js → push-client-CAm6UMvE.js} +5 -5
- package/dist/lib/{push-client-Cx5rMs6J.js.map → push-client-CAm6UMvE.js.map} +1 -1
- package/dist/lib/{read-group-file-bytes-CXOG_YyM.js → read-group-file-bytes-UQIk1eJG.js} +2 -2
- package/dist/lib/{read-group-file-bytes-CXOG_YyM.js.map → read-group-file-bytes-UQIk1eJG.js.map} +1 -1
- package/dist/lib/{rooms-CwlkYLDU.js → rooms-Dzphx3rK.js} +2 -2
- package/dist/lib/{rooms-CwlkYLDU.js.map → rooms-Dzphx3rK.js.map} +1 -1
- package/dist/lib/{shadow-claw-DoQ7fgl5.js → shadow-claw-CGl8tXtG.js} +17 -20
- package/dist/lib/shadow-claw-CGl8tXtG.js.map +1 -0
- package/dist/lib/{shadow-claw-a2ui-Br6qJMs1.js → shadow-claw-a2ui-lG0vQbW8.js} +2 -2
- package/dist/lib/{shadow-claw-a2ui-Br6qJMs1.js.map → shadow-claw-a2ui-lG0vQbW8.js.map} +1 -1
- package/dist/lib/{shadow-claw-accounts-BTDILfWw.js → shadow-claw-accounts-CkqyCxwp.js} +3 -3
- package/dist/lib/{shadow-claw-accounts-BTDILfWw.js.map → shadow-claw-accounts-CkqyCxwp.js.map} +1 -1
- package/dist/lib/{shadow-claw-channel-config-IKiL34tI.js → shadow-claw-channel-config-BNIWCdsL.js} +4 -4
- package/dist/lib/{shadow-claw-channel-config-IKiL34tI.js.map → shadow-claw-channel-config-BNIWCdsL.js.map} +1 -1
- package/dist/lib/{shadow-claw-channels-JgEzuHWK.js → shadow-claw-channels-C2QSn4Ew.js} +3 -3
- package/dist/lib/{shadow-claw-channels-JgEzuHWK.js.map → shadow-claw-channels-C2QSn4Ew.js.map} +1 -1
- package/dist/lib/{shadow-claw-chat-SGUDT31r.js → shadow-claw-chat-Wx3y9y6c.js} +15 -15
- package/dist/lib/{shadow-claw-chat-SGUDT31r.js.map → shadow-claw-chat-Wx3y9y6c.js.map} +1 -1
- package/dist/lib/{shadow-claw-control-plane-CRWFZ3vD.js → shadow-claw-control-plane-D5E4cFGu.js} +7 -7
- package/dist/lib/{shadow-claw-control-plane-CRWFZ3vD.js.map → shadow-claw-control-plane-D5E4cFGu.js.map} +1 -1
- package/dist/lib/{shadow-claw-conversations-D23GJ7qo.js → shadow-claw-conversations-BtDv7GRW.js} +7 -7
- package/dist/lib/{shadow-claw-conversations-D23GJ7qo.js.map → shadow-claw-conversations-BtDv7GRW.js.map} +1 -1
- package/dist/lib/{shadow-claw-file-viewer-C1V8WTiU.js → shadow-claw-file-viewer-CG40kwWV.js} +10 -10
- package/dist/lib/{shadow-claw-file-viewer-C1V8WTiU.js.map → shadow-claw-file-viewer-CG40kwWV.js.map} +1 -1
- package/dist/lib/{shadow-claw-files-DN7irmE1.js → shadow-claw-files-BOUULrlX.js} +11 -11
- package/dist/lib/{shadow-claw-files-DN7irmE1.js.map → shadow-claw-files-BOUULrlX.js.map} +1 -1
- package/dist/lib/{shadow-claw-git-D-1oIh65.js → shadow-claw-git-BeHV73_9.js} +6 -6
- package/dist/lib/{shadow-claw-git-D-1oIh65.js.map → shadow-claw-git-BeHV73_9.js.map} +1 -1
- package/dist/lib/{shadow-claw-integrations-CZjnm7cM.js → shadow-claw-integrations-RZZ-m-Id.js} +4 -4
- package/dist/lib/{shadow-claw-integrations-CZjnm7cM.js.map → shadow-claw-integrations-RZZ-m-Id.js.map} +1 -1
- package/dist/lib/{shadow-claw-llm-4Gefh5FN.js → shadow-claw-llm-KONyWKZM.js} +9 -9
- package/dist/lib/{shadow-claw-llm-4Gefh5FN.js.map → shadow-claw-llm-KONyWKZM.js.map} +1 -1
- package/dist/lib/{shadow-claw-mcp-remote-B9ssb3YV.js → shadow-claw-mcp-remote-BKFROurv.js} +4 -4
- package/dist/lib/{shadow-claw-mcp-remote-B9ssb3YV.js.map → shadow-claw-mcp-remote-BKFROurv.js.map} +1 -1
- package/dist/lib/{shadow-claw-networking-BN5BB4hb.js → shadow-claw-networking-Diy3JJkc.js} +2 -2
- package/dist/lib/{shadow-claw-networking-BN5BB4hb.js.map → shadow-claw-networking-Diy3JJkc.js.map} +1 -1
- package/dist/lib/{shadow-claw-notifications-71KARtkY.js → shadow-claw-notifications-C-upPa-4.js} +3 -3
- package/dist/lib/{shadow-claw-notifications-71KARtkY.js.map → shadow-claw-notifications-C-upPa-4.js.map} +1 -1
- package/dist/lib/{shadow-claw-page-header-DMGO-TSe.js → shadow-claw-page-header-C_Qr3xZM.js} +2 -2
- package/dist/lib/{shadow-claw-page-header-DMGO-TSe.js.map → shadow-claw-page-header-C_Qr3xZM.js.map} +1 -1
- package/dist/lib/{shadow-claw-pages-BiRM6qiA.js → shadow-claw-pages-CfAjUKgd.js} +11 -11
- package/dist/lib/{shadow-claw-pages-BiRM6qiA.js.map → shadow-claw-pages-CfAjUKgd.js.map} +1 -1
- package/dist/lib/{shadow-claw-peerjs-BZu7jNSe.js → shadow-claw-peerjs-t4YibS9s.js} +6 -6
- package/dist/lib/{shadow-claw-peerjs-BZu7jNSe.js.map → shadow-claw-peerjs-t4YibS9s.js.map} +1 -1
- package/dist/lib/{shadow-claw-provider-model-picker-BXYXEobD.js → shadow-claw-provider-model-picker-B-Ct4yW-.js} +2 -2
- package/dist/lib/{shadow-claw-provider-model-picker-BXYXEobD.js.map → shadow-claw-provider-model-picker-B-Ct4yW-.js.map} +1 -1
- package/dist/lib/{shadow-claw-settings-CcT5EK08.js → shadow-claw-settings-Cg5V0e9g.js} +7 -7
- package/dist/lib/{shadow-claw-settings-CcT5EK08.js.map → shadow-claw-settings-Cg5V0e9g.js.map} +1 -1
- package/dist/lib/{shadow-claw-storage-eTOpbvpi.js → shadow-claw-storage-C7tCnsSG.js} +5 -5
- package/dist/lib/{shadow-claw-storage-eTOpbvpi.js.map → shadow-claw-storage-C7tCnsSG.js.map} +1 -1
- package/dist/lib/{shadow-claw-task-server-DFImTUbw.js → shadow-claw-task-server-BObsRdf8.js} +2 -2
- package/dist/lib/{shadow-claw-task-server-DFImTUbw.js.map → shadow-claw-task-server-BObsRdf8.js.map} +1 -1
- package/dist/lib/{shadow-claw-tasks-BjaxsmUx.js → shadow-claw-tasks-B2EEqrcY.js} +9 -9
- package/dist/lib/{shadow-claw-tasks-BjaxsmUx.js.map → shadow-claw-tasks-B2EEqrcY.js.map} +1 -1
- package/dist/lib/{shadow-claw-terminal-C-4wreFe.js → shadow-claw-terminal-DSHfO2b9.js} +2 -2
- package/dist/lib/{shadow-claw-terminal-C-4wreFe.js.map → shadow-claw-terminal-DSHfO2b9.js.map} +1 -1
- package/dist/lib/{shadow-claw-tools-COdrGZJk.js → shadow-claw-tools-DwPBADua.js} +7 -7
- package/dist/lib/{shadow-claw-tools-COdrGZJk.js.map → shadow-claw-tools-DwPBADua.js.map} +1 -1
- package/dist/lib/{shadow-claw-webvm-sxqVjO0L.js → shadow-claw-webvm-CY4qGaMB.js} +3 -3
- package/dist/lib/{shadow-claw-webvm-sxqVjO0L.js.map → shadow-claw-webvm-CY4qGaMB.js.map} +1 -1
- package/dist/lib/{sync-web-mcp-registration-D4hdUwtv.js → sync-web-mcp-registration-BiOZvW-R.js} +6 -6
- package/dist/lib/{sync-web-mcp-registration-D4hdUwtv.js.map → sync-web-mcp-registration-BiOZvW-R.js.map} +1 -1
- package/dist/lib/{system-prompt-DT_KeYaL.js → system-prompt-CxJ3Nx4c.js} +9 -8
- package/dist/lib/system-prompt-CxJ3Nx4c.js.map +1 -0
- package/dist/lib/{tools-Beuyh8y1.js → tools-B8OJ4sMF.js} +4 -4
- package/dist/lib/{tools-Beuyh8y1.js.map → tools-B8OJ4sMF.js.map} +1 -1
- package/dist/lib/{transformers-DydnReu4.js → transformers-BMURofG6.js} +2 -2
- package/dist/lib/{transformers-DydnReu4.js.map → transformers-BMURofG6.js.map} +1 -1
- package/dist/lib/{trusted-types-CfwZl_rr.js → trusted-types-HwsGS5Nj.js} +19 -17
- package/dist/lib/{trusted-types-CfwZl_rr.js.map → trusted-types-HwsGS5Nj.js.map} +1 -1
- package/dist/lib/{upload-group-file-BbBzjTcN.js → upload-group-file-CJpoNjEb.js} +3 -3
- package/dist/lib/{upload-group-file-BbBzjTcN.js.map → upload-group-file-CJpoNjEb.js.map} +1 -1
- package/dist/lib/utils/index.js +1 -1
- package/dist/lib/utils/namespaced-storage.js +1 -1
- package/dist/lib/utils/runtime-assets.js +1 -1
- package/dist/lib/utils/utils.js +1 -1
- package/dist/lib/{webmcp-DCfAFiIO.js → webmcp-BoMTvgmX.js} +3 -3
- package/dist/lib/{webmcp-DCfAFiIO.js.map → webmcp-BoMTvgmX.js.map} +1 -1
- package/dist/lib/{write-group-file-bytes-Ccn-VFUU.js → write-group-file-bytes-CNT7DqOZ.js} +3 -3
- package/dist/lib/{write-group-file-bytes-Ccn-VFUU.js.map → write-group-file-bytes-CNT7DqOZ.js.map} +1 -1
- 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 -1
- package/dist/public/README.md +6 -2
- package/dist/public/agent.worker.js +1 -1
- package/dist/public/attachment-capabilities-AdwXt3--.js +1 -0
- package/dist/public/{channel-BylT3rJC.js → channel-DIpDQekL.js} +1 -1
- package/dist/public/{chat-template-DPHJy7tr.js → chat-template-CXKs8lFR.js} +1 -1
- package/dist/public/compact-context-BQ2ZXoAc.js +5 -0
- package/dist/public/{compact-context-BINQh64w.js → compact-context-dHitmPsV.js} +2 -2
- package/dist/public/config-C16fFWtP.js +1 -0
- package/dist/public/{configure-peer-js-DChhcOfe.js → configure-peer-js-DV1rqvFX.js} +1 -1
- package/dist/public/{connections-CHaw0VqP.js → connections-Dxwj8yK_.js} +1 -1
- package/dist/public/{create-model-cache-fetch-DQebkoPL.js → create-model-cache-fetch-B0mSCEk6.js} +1 -1
- package/dist/public/{credentials-CgVqS119.js → credentials-CJUQ5Ep2.js} +1 -1
- package/dist/public/{custom-element-security-kiDhPfb8.js → custom-element-security-B2daIE5r.js} +2 -2
- package/dist/public/{discover-skills-Cvmx5I9V.js → discover-skills-BWJB8HUA.js} +6 -6
- package/dist/public/docs/architecture/overview.md +1 -1
- package/dist/public/docs/example/article/index.html +29 -30
- package/dist/public/docs/example/article.html +29 -30
- package/dist/public/docs/publishing/index.html +29 -30
- package/dist/public/docs/publishing.html +29 -30
- package/dist/public/docs/skill-creator/index.html +29 -30
- package/dist/public/docs/skill-creator.html +29 -30
- package/dist/public/docs/subsystems/attachment-capabilities.md +14 -1
- package/dist/public/docs/subsystems/cli.md +95 -51
- package/dist/public/docs/subsystems/pages.md +5 -0
- package/dist/public/{download-group-file-BapoRgfU.js → download-group-file-BkMH-JKi.js} +1 -1
- package/dist/public/e2e/README.md +1 -1
- package/dist/public/{e2e-bridge-C0g8vZKr.js → e2e-bridge-lP2qqiv3.js} +1 -1
- package/dist/public/get-group-dir-D--BiEyk.js +1 -0
- package/dist/public/{get-or-create-subscriber-id-GvRZYXwA.js → get-or-create-subscriber-id-jVHnQfbr.js} +1 -1
- package/dist/public/{git-CaAAZfVd.js → git-DjmQ16rm.js} +2 -2
- package/dist/public/{iframe-bridge-scripts-BnqtKhE4.js → iframe-bridge-scripts-CO0izGjW.js} +1 -1
- package/dist/public/index.html +29 -30
- package/dist/public/index.js +1 -1
- package/dist/public/{init-chat-split-resize-Btonoy8u.js → init-chat-split-resize-C8AqCCiK.js} +1 -1
- package/dist/public/init-control-plane-Ctz7FI8M.js +1 -0
- package/dist/public/{invoke-agent-B3Osw6K7.js → invoke-agent-C_geruwq.js} +1 -1
- package/dist/public/llms.txt +1 -1
- package/dist/public/main/index.html +29 -30
- package/dist/public/main/memory/index.html +29 -30
- package/dist/public/main/memory.html +29 -30
- package/dist/public/main.html +29 -30
- package/dist/public/{markdown-CPbU4r1U.js → markdown-CDSb5Hrl.js} +1 -1
- package/dist/public/{mcp-reconnect-CzROVsXG.js → mcp-reconnect-iPZPihwX.js} +1 -1
- package/dist/public/{memory-storage-BkoMlxOr.js → memory-storage-2m7KZ-aP.js} +1 -1
- package/dist/public/{model-ranking-CK0iBo3Z.js → model-ranking-BgOSaNIy.js} +1 -1
- package/dist/public/{move-group-entry-CTxoq7lw.js → move-group-entry-QQ9Hkk54.js} +1 -1
- package/dist/public/{orchestrator-BrDjQbGf.js → orchestrator-C1kaTltu.js} +2 -2
- package/dist/public/orchestrator-Li1UAsv7.js +63 -0
- package/dist/public/{peerjs-CgF4Iz5W.js → peerjs-DbBryE-9.js} +1 -1
- package/dist/public/{process-peer-query-param-BL2k0Hu-.js → process-peer-query-param-DQIgr3KL.js} +1 -1
- package/dist/public/{process-pending-shared-payloads-C1AgGvn8.js → process-pending-shared-payloads-Ctb-TFqB.js} +1 -1
- package/dist/public/{process-room-query-param-DM0QCq3_.js → process-room-query-param-F-XnIVoZ.js} +1 -1
- package/dist/public/provider-YPZmsuHR.js +1 -0
- package/dist/public/{push-client-DJEOz7bi.js → push-client-DRx9Eggz.js} +1 -1
- package/dist/public/{rooms-C6LXIJl4.js → rooms-BurBI7is.js} +1 -1
- package/dist/public/service-worker/init.js +1 -1
- package/dist/public/service-worker.js +1 -1
- package/dist/public/shadow-claw-Bg9AQ5x_.js +1176 -0
- package/dist/public/{shadow-claw-accounts--4hd_oCz.js → shadow-claw-accounts-B3mjYI0M.js} +1 -1
- package/dist/public/{shadow-claw-card-IbNlZAdK.js → shadow-claw-card-tcXRS1GF.js} +1 -1
- package/dist/public/{shadow-claw-channels-Vq_pPGa2.js → shadow-claw-channels-BiSfLvWv.js} +1 -1
- package/dist/public/{shadow-claw-chat-D7_GS25e.js → shadow-claw-chat-N5jMsXZZ.js} +3 -3
- package/dist/public/{shadow-claw-control-plane-WTMEV8_p.js → shadow-claw-control-plane-DFVe_Xdq.js} +2 -2
- package/dist/public/{shadow-claw-conversations-CLQgU1IT.js → shadow-claw-conversations-wAR06_ya.js} +1 -1
- package/dist/public/{shadow-claw-empty-state-D4CrFGsN.js → shadow-claw-empty-state-CnPm3NVM.js} +1 -1
- package/dist/public/{shadow-claw-file-viewer-BhqiqLWQ.js → shadow-claw-file-viewer-sZN_FCDW.js} +4 -4
- package/dist/public/{shadow-claw-files-senDiG9l.js → shadow-claw-files-CnvkCbd4.js} +2 -2
- package/dist/public/{shadow-claw-git-DOOCqY23.js → shadow-claw-git-BBHfClGk.js} +2 -2
- package/dist/public/{shadow-claw-integrations-Bsvc3Agq.js → shadow-claw-integrations-DvdBqzRJ.js} +1 -1
- package/dist/public/{shadow-claw-llm-actYICAk.js → shadow-claw-llm-YfohG519.js} +2 -2
- package/dist/public/{shadow-claw-mcp-remote-BYUgrK3v.js → shadow-claw-mcp-remote-BAVbf5pi.js} +1 -1
- package/dist/public/{shadow-claw-networking-Dk3p5Ny_.js → shadow-claw-networking-CZ4LWPW7.js} +1 -1
- package/dist/public/{shadow-claw-notifications-CzPAlay8.js → shadow-claw-notifications-BHwyREkG.js} +1 -1
- package/dist/public/{shadow-claw-page-header-CjJpVkyL.js → shadow-claw-page-header-De6Qf6eY.js} +1 -1
- package/dist/public/{shadow-claw-page-header-action-button-2DH5O1TD.js → shadow-claw-page-header-action-button-FSOhTc9z.js} +1 -1
- package/dist/public/{shadow-claw-pages-3r5I-wI8.js → shadow-claw-pages-D_oPyDca.js} +6 -6
- package/dist/public/{shadow-claw-pdf-viewer-BiCEwsoY.js → shadow-claw-pdf-viewer-CrU4wqRq.js} +1 -1
- package/dist/public/{shadow-claw-settings-DgB9RSZN.js → shadow-claw-settings-DkUhvxVr.js} +2 -2
- package/dist/public/{shadow-claw-storage-JB_43nd8.js → shadow-claw-storage-D0o56Tjw.js} +1 -1
- package/dist/public/{shadow-claw-task-server-oi5UIxdA.js → shadow-claw-task-server-4rkroO9K.js} +1 -1
- package/dist/public/{shadow-claw-tasks-CnyiOt81.js → shadow-claw-tasks-BdP7lmvu.js} +3 -3
- package/dist/public/{shadow-claw-terminal-BC3RynHt.js → shadow-claw-terminal-DVHX7Fsu.js} +1 -1
- package/dist/public/{shadow-claw-toast-YjG--2Za.js → shadow-claw-toast-B9Y9tSkW.js} +1 -1
- package/dist/public/{shadow-claw-tools-Bbwk4vlT.js → shadow-claw-tools-BwwY53Lr.js} +1 -1
- package/dist/public/{shadow-claw-webvm-HZqzl2H5.js → shadow-claw-webvm-CXGdkCNM.js} +1 -1
- package/dist/public/{sync-web-mcp-registration-BaH2nAP0.js → sync-web-mcp-registration-DVK_IhXZ.js} +1 -1
- package/dist/public/{system-prompt-Dck3N8T0.js → system-prompt-BmswoQwF.js} +2 -2
- package/dist/public/{tools-DHA1dK2I.js → tools-D-52Zmfc.js} +1 -1
- package/dist/public/{transformers-C-DuTM2K.js → transformers-CQ9ss9rD.js} +1 -1
- package/dist/public/{upload-group-file-Cejr3zo1.js → upload-group-file-A8kB7lvO.js} +1 -1
- package/dist/public/{webmcp-CMRtu57-.js → webmcp-DIUZjVF5.js} +1 -1
- package/dist/public/{workbox-92eae37e.js → workbox-e4022e15.js} +1 -1
- package/dist/public/{write-group-file-CmJuVQNO.js → write-group-file-R67DjJ-q.js} +1 -1
- package/dist/public/{write-group-file-bytes-Cejr3zo1.js → write-group-file-bytes-A8kB7lvO.js} +1 -1
- package/dist/public/{zip-reader-CuQ13eLe.js → zip-reader-JHoTbATw.js} +1 -1
- package/dist/server.js +6 -6
- package/package.json +1 -1
- package/dist/cli/chunk-2gZFafgY.js +0 -1
- package/dist/cli/chunk-BFziiMKt.js +0 -7
- package/dist/cli/chunk-BM3llsxb.js +0 -1
- package/dist/cli/chunk-BUNoeMKY.js +0 -36
- package/dist/cli/chunk-Bj5qFsDi.js +0 -7
- package/dist/cli/chunk-Bj95zm-y.js +0 -1
- package/dist/cli/chunk-BpyP-esT.js +0 -1
- package/dist/cli/chunk-CX696s3_.js +0 -1
- package/dist/cli/chunk-DRxCrCAA.js +0 -139
- package/dist/cli/chunk-DjbCHa0h.js +0 -1
- package/dist/cli/chunk-Ds5-K-9o.js +0 -1
- package/dist/cli/chunk-DsQhAF31.js +0 -1
- package/dist/cli/chunk-VM-dECyG.js +0 -1
- package/dist/cli/chunk-gvNsvav0.js +0 -225
- package/dist/cli/chunk-heu2xRw1.js +0 -1
- package/dist/lib/orchestrator-i_QJ-o22.js.map +0 -1
- package/dist/lib/shadow-claw-DoQ7fgl5.js.map +0 -1
- package/dist/lib/system-prompt-DT_KeYaL.js.map +0 -1
- package/dist/public/app-routes-V_-URXc5.js +0 -1
- package/dist/public/attachment-capabilities-B6ibLwQB.js +0 -1
- package/dist/public/compact-context-CX4H8V57.js +0 -5
- package/dist/public/config-C-YdSFZB.js +0 -1
- package/dist/public/get-group-dir-DL44kvqW.js +0 -1
- package/dist/public/init-control-plane-BoJijVtf.js +0 -1
- package/dist/public/orchestrator-CaUpEVkQ.js +0 -63
- package/dist/public/provider-DNIL4-Hw.js +0 -1
- package/dist/public/shadow-claw-DdgeYPg5.js +0 -1176
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import{n as e}from"./rolldown-runtime-DBVvNlSN.js";import{C as t,S as n,l as r,t as i}from"./custom-element-security-B2daIE5r.js";import{H as a,Q as o,U as s,o as c,r as l,z as u}from"./config-C16fFWtP.js";import{n as d}from"./db-BUuJo1Gf.js";import{n as f,t as p}from"./tx-promise-DNVEN3Wa.js";import{t as m}from"./get-config-Bkvl__ZS.js";import{t as h}from"./dist-CeFyqf9k.js";import{t as g}from"./set-config-DSiuMe0k.js";import{t as _}from"./ulid-BSJxYh6W.js";import{c as v,o as y,s as b,t as x}from"./tools-D-52Zmfc.js";import{t as S}from"./get-or-create-subscriber-id-jVHnQfbr.js";import{a as C,o as w,r as ee,s as te,t as T}from"./get-group-dir-D--BiEyk.js";import{i as E,n as ne,r as re,t as D}from"./write-group-file-R67DjJ-q.js";import{t as ie}from"./dedent-eld_mRQx.js";import{a as ae,r as O}from"./toast-CtIuHprH.js";import{t as oe}from"./parse-boolean-config-BigJ9U46.js";function se(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 ce(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 k(){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))}function le(e,t=c){e.agentWorker?.postMessage({payload:{groupId:t},type:`vm-terminal-open`})}function ue(e,t=c){e.agentWorker?.postMessage({payload:{groupId:t},type:`vm-terminal-close`})}function de(e,t){e.agentWorker?.postMessage({payload:{data:t},type:`vm-terminal-input`})}function fe(e,t=c){e.agentWorker?.postMessage({payload:{groupId:t},type:`vm-workspace-sync`})}function pe(e,t=c){e.agentWorker?.postMessage({payload:{groupId:t},type:`vm-workspace-flush`})}function me(e,t,n){e.agentWorker?.postMessage({payload:{id:t,response:n},type:`ask-user-response`})}async function he(e,t,n,r=g){let i=n===`disabled`||n===`9p`||n===`ext2`||n===`auto`?n:`disabled`;e.vmBootMode=i,await r(t,l.VM_BOOT_MODE,i),e.agentWorker?.postMessage({payload:{mode:i},type:`set-vm-mode`})}async function ge(e,t,n,r=g){let i=typeof n==`string`?n.trim():``;await r(t,l.VM_BOOT_HOST,i),e.agentWorker?.postMessage({payload:{bootHost:i},type:`set-vm-mode`})}async function _e(e,t,n,r=g){let i=typeof n==`string`?n.trim():``;await r(t,l.VM_NETWORK_RELAY_URL,i),e.agentWorker?.postMessage({payload:{networkRelayUrl:i},type:`set-vm-mode`})}function ve(e){`serviceWorker`in navigator&&navigator.serviceWorker?.controller&&navigator.serviceWorker.controller.postMessage({type:`set-proxy-config`,payload:{useProxy:e.useProxy,proxyUrl:e.proxyUrl}})}async function ye(e,t,n,r=g){e.contextCompressionEnabled=!!n,await r(t,l.CONTEXT_COMPRESSION_ENABLED,e.contextCompressionEnabled?`true`:`false`)}async function be(e,t,n,r=g){e.gitProxyUrl=n||`/git-proxy`,await r(t,l.GIT_PROXY_URL,e.gitProxyUrl)}async function xe(e,t,n,r=g){e.maxIterations=n,await r(t,l.MAX_ITERATIONS,String(n))}async function Se(e,t,n,r=g){let i=Math.max(1,n);e.maxTokens=i,await r(t,l.MAX_TOKENS,String(i))}async function Ce(e,t,n,r=g){e.proxyUrl=n||`/proxy`,await r(t,l.PROXY_URL,e.proxyUrl),ve(e)}async function we(e,t,n,r=g){e.rateLimitAutoAdapt=!!n,await r(t,l.RATE_LIMIT_AUTO_ADAPT,e.rateLimitAutoAdapt?`true`:`false`)}async function Te(e,t,n,r=g){let i=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;e.rateLimitCallsPerMinute=i,await r(t,l.RATE_LIMIT_CALLS_PER_MINUTE,String(i))}async function Ee(e,t,n,r=g){e.reasoningEffort=(typeof n==`string`?n.trim().toLowerCase():`none`)||`none`,await r(t,l.REASONING_EFFORT,e.reasoningEffort)}async function De(e,t,n,r=g){e.streamingEnabled=!!n,await r(t,l.STREAMING_ENABLED,e.streamingEnabled?`true`:`false`)}async function Oe(e,t,n,r=g){e.taskServerEnabled=!!n,await r(t,l.TASK_SERVER_ENABLED,e.taskServerEnabled?`true`:`false`)}async function ke(e,t,n,r=g){e.taskServerUrl=n||`http://localhost:8888/schedule`,await r(t,l.TASK_SERVER_URL,e.taskServerUrl)}async function Ae(e,t,n,r=g){e.useProxy=!!n,await r(t,l.USE_PROXY,e.useProxy?`true`:`false`),ve(e)}async function je(e,t,n,r=g){e.vmBashFullInternetAccess=!!n,await r(t,l.VM_BASH_FULL_INTERNET_ACCESS,e.vmBashFullInternetAccess?`true`:`false`)}async function Me(e,t,n,r=g){let i=Math.min(Math.max(Math.floor(n),1),1800);await r(t,l.VM_BASH_TIMEOUT_SEC,String(i))}function Ne(e,t){let n=null,r;return typeof e==`string`?r=e:(n=e,r=t),n&&f(n)?(n.db.prepare(`DELETE FROM messages WHERE groupId = ?`).run(r),Promise.resolve()):new Promise((e,t)=>{try{let i=n?.transaction(`messages`,`readwrite`);if(!i)return t(/* @__PURE__ */ Error(`failed to get transaction, cannot clear group messages.`));let a=i.objectStore(`messages`).index(`by-group`).openCursor(r);a.onsuccess=()=>{let t=a.result;t?(t.delete(),t.continue()):e(void 0)},a.onerror=()=>t(a.error)}catch(e){t(e)}})}function Pe(e,t,n){if(e&&f(e)){let r=e.db,i=r.prepare(`SELECT * FROM messages WHERE groupId = ?`).all(t),a=r.prepare(`INSERT INTO messages
|
|
2
|
+
(id, groupId, timestamp, content, sender, channel, isFromMe, isTrigger, attachments, a2uiAction, a2uiEnvelopes, freshContext, subagent)
|
|
3
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);for(let e of i)a.run(_(),n,e.timestamp,e.content,e.sender,e.channel??`chat`,e.isFromMe,e.isTrigger,e.attachments,e.a2uiAction,e.a2uiEnvelopes,e.freshContext,e.subagent);return Promise.resolve(i.length)}return new Promise((r,i)=>{let a=e?.transaction(`messages`,`readwrite`);if(!a)throw Error(`failed to get transaction, cannot clone messages.`);let o=a.objectStore(`messages`),s=o.index(`by-group`).openCursor(t),c=0;s.onsuccess=()=>{let e=s.result;if(e){let t={...e.value,id:_(),groupId:n};o.put(t),c++,e.continue()}else r(c)},s.onerror=()=>i(s.error)})}function Fe(e,t,n){if(e&&f(e)){let r=e.db,i=r.prepare(`SELECT * FROM tasks WHERE groupId = ?`).all(t),a=r.prepare(`INSERT INTO tasks
|
|
4
|
+
(id, groupId, enabled, schedule, prompt, tools, lastRun, createdAt, type, freshContext, subagent, name, task_order, pushNotifications)
|
|
5
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);for(let e of i)a.run(_(),n,+!!e.enabled,e.schedule??null,e.prompt??``,e.tools??null,e.lastRun??null,e.createdAt,e.type??null,e.freshContext?1:null,e.subagent?1:null,e.name??null,e.task_order??null,e.pushNotifications?1:null);return Promise.resolve(i.length)}return new Promise((r,i)=>{let a=e?.transaction(`tasks`,`readwrite`);if(!a)throw Error(`failed to get transaction, cannot clone tasks.`);let o=a.objectStore(`tasks`),s=o.index(`by-group`).openCursor(t),c=0;s.onsuccess=()=>{let e=s.result;if(e){let t={...e.value,id:_(),groupId:n};o.put(t),c++,e.continue()}else r(c)},s.onerror=()=>i(s.error)})}function Ie(e,t){return p(e,`messages`,`readwrite`,e=>e.delete(t)).then(()=>void 0)}function Le(e,t){return t?p(e,`tasks`,`readwrite`,e=>e.delete(t)).then(()=>void 0):Promise.reject(/* @__PURE__ */ Error(`Task ID is required for deletion.`))}function Re(e,t,n){let r=null,i,a;return typeof e==`string`?(i=e,a=t):(r=e,i=t,a=n??50),r&&f(r)?Promise.resolve().then(()=>(r.db.prepare(`SELECT * FROM messages WHERE groupId = ? ORDER BY timestamp DESC LIMIT ?`).all(i,a)??[]).reverse().map(ze)):new Promise(async(e,t)=>{try{let n=r??await d();if(!n)return t(/* @__PURE__ */ Error(`failed to get transaction, cannot get recent messages.`));let o=n.transaction(`messages`,`readonly`);if(!o)return t(/* @__PURE__ */ Error(`failed to get transaction`));let s=o.objectStore(`messages`).index(`by-group-time`),c=IDBKeyRange.bound([i,0],[i,1/0]),l=s.openCursor(c,`prev`),u=[];l.onsuccess=()=>{let t=l.result;t&&u.length<a?(u.push(t.value),t.continue()):e(u.reverse())},l.onerror=()=>t(l.error)}catch(e){t(e)}})}function ze(e){return{...e,isFromMe:!!e.isFromMe,isTrigger:!!e.isTrigger,attachments:e.attachments?JSON.parse(e.attachments):void 0,a2uiAction:e.a2uiAction?JSON.parse(e.a2uiAction):void 0,a2uiEnvelopes:e.a2uiEnvelopes?JSON.parse(e.a2uiEnvelopes):void 0}}const Be=`group_metadata`;async function A(e){let t=await m(e,Be);if(!t)return[];try{return JSON.parse(t)}catch{return[]}}async function j(e,t){await g(e,Be,JSON.stringify(t))}async function Ve(e,t,n=`br:`,r){let i=await A(e),a={groupId:`${n}${r??_()}`,name:t,createdAt:Date.now()};return i.push(a),await j(e,i),a}async function He(e,t,n){let r=await A(e),i=r.find(e=>e.groupId===t);i&&(i.name=n),await j(e,r)}async function Ue(e,t,n){let r=await A(e),i=r.find(e=>e.groupId===t);i&&(n&&n.length>0?i.toolTags=n:delete i.toolTags),await j(e,r)}async function We(e,t){await j(e,(await A(e)).filter(e=>e.groupId!==t))}async function M(e){let t=await A(e);if(t.length===0){let t={groupId:c,name:`Main`,createdAt:0};return await j(e,[t]),[t]}return t}async function Ge(e,t){let n=await A(e),r=new Map(n.map(e=>[e.groupId,e])),i=[];for(let e of t){let t=r.get(e);t&&(i.push(t),r.delete(e))}for(let e of n)r.has(e.groupId)&&i.push(e);await j(e,i)}async function Ke(e,t){let n=await A(e),r=n.find(e=>e.groupId===t);if(!r)return null;let i=t.indexOf(`:`),a={groupId:`${i>=0?t.slice(0,i+1):`br:`}${_()}`,name:`${r.name} (copy)`,createdAt:Date.now(),pinnedMaxTokens:r.pinnedMaxTokens,providerRuntimeOverrides:r.providerRuntimeOverrides?JSON.parse(JSON.stringify(r.providerRuntimeOverrides)):void 0,subagentModelSelectionMode:r.subagentModelSelectionMode,subagentMaxTokens:r.subagentMaxTokens,subagentPinnedProvider:r.subagentPinnedProvider,subagentPinnedModel:r.subagentPinnedModel,subagentFastProvider:r.subagentFastProvider,subagentFastModel:r.subagentFastModel,subagentSmartProvider:r.subagentSmartProvider,subagentSmartModel:r.subagentSmartModel,subagentPowerfulProvider:r.subagentPowerfulProvider,subagentPowerfulModel:r.subagentPowerfulModel,toolTags:r.toolTags?[...r.toolTags]:void 0};return n.push(a),await j(e,n),a}async function qe(e,t,n,r,i){let a=await A(e),o=a.find(e=>e.groupId===t);o&&(n?o.pinnedProvider=n:delete o.pinnedProvider,r?o.pinnedModel=r:delete o.pinnedModel,typeof i==`number`&&Number.isFinite(i)&&i>0?o.pinnedMaxTokens=Math.floor(i):delete o.pinnedMaxTokens),await j(e,a)}async function Je(e,t,n,r,i,a){let o=await A(e),s=o.find(e=>e.groupId===t);s&&(s.subagentModelSelectionMode=n,n===`manual`?(r?s.subagentPinnedProvider=r:delete s.subagentPinnedProvider,i?s.subagentPinnedModel=i:delete s.subagentPinnedModel):(delete s.subagentPinnedProvider,delete s.subagentPinnedModel),typeof a==`number`&&Number.isFinite(a)&&a>0?s.subagentMaxTokens=Math.floor(a):delete s.subagentMaxTokens),await j(e,o)}async function Ye(e,t,n){let r=await A(e),i=r.find(e=>e.groupId===t);i&&(n&&Object.keys(n).length>0?i.providerRuntimeOverrides=JSON.parse(JSON.stringify(n)):delete i.providerRuntimeOverrides),await j(e,r)}function N(e,t){return p(e,`messages`,`readwrite`,e=>e.put(t)).then(()=>void 0)}function P(e,t){let n={...t,enabled:+!!t.enabled};return p(e,`tasks`,`readwrite`,e=>e.put(n)).then(()=>void 0)}function Xe(e,t,n){let r=null,i,a;return typeof e==`string`?(i=e,a=t):(r=e,i=t,a=n),r&&f(r)?Promise.resolve().then(()=>{r.db.prepare(`UPDATE tasks SET lastRun = ? WHERE id = ?`).run(a,i)}):new Promise(async(e,t)=>{try{let n=r??await d();if(!n)return t(/* @__PURE__ */ Error(`failed to get transaction, cannot update task last run.`));let o=n.transaction(`tasks`,`readwrite`);if(!o)return t(/* @__PURE__ */ Error(`failed to get transaction`));let s=o.objectStore(`tasks`),c=s.get(i);c.onsuccess=()=>{let n=c.result;if(!n){e();return}n.lastRun=a;let r=s.put(n);r.onsuccess=()=>e(),r.onerror=()=>t(r.error)},c.onerror=()=>t(c.error)}catch(e){t(e)}})}async function Ze(e,t,n){let r=(await v(e)).filter(e=>e.groupId===t),i=new Map(r.map(e=>[e.id,e])),a=[],o=0;for(let t of n){let n=i.get(t);n&&(n.order=o++,await P(e,n),a.push(n),i.delete(t))}let s=Array.from(i.values()).sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r});for(let t of s)t.order=o++,await P(e,t),a.push(t);return a}async function Qe(e,t,n,r){let i=await T(e,t),a=await T(e,n),o=r.replace(/\\/g,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean),s=i,c=a;for(let e of o)s=await s.getDirectoryHandle(e),c=await c.getDirectoryHandle(e,{create:!0});let l=n.replace(/:/g,`-`),u=[ee(),`groups`,l,...o];try{await $e(e,n,s,c,u)}catch(e){throw o.length>0&&await a.removeEntry(o[0],{recursive:!0}).catch(()=>void 0),e}}async function $e(e,t,n,r,i){for await(let[a,o]of n.entries()){if(o.kind===`directory`){await $e(e,t,o,await r.getDirectoryHandle(a,{create:!0}),[...i,a]);continue}let n=await o.getFile(),s=await r.getFileHandle(a,{create:!0});try{await re(s,n)}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await C(e)).type===`opfs`))throw t;await E([...i,a],n)}}}const F=`---
|
|
6
|
+
title: "ShadowClaw Pages"
|
|
7
|
+
created: "1970-01-01T00:00:00Z"
|
|
8
|
+
updated: "1970-01-01T00:00:00Z"
|
|
9
|
+
slug: "shadow-claw-pages"
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
<article>
|
|
13
|
+
<h2>Welcome to ShadowClaw Pages</h2>
|
|
14
|
+
<p>This is the default static page for your workspace.</p>
|
|
15
|
+
<h2 id="getting-started-with-shadowclaw">Getting started with ShadowClaw</h2>
|
|
16
|
+
<h3 id="what-is-memorymd">What is MEMORY.md?</h3>
|
|
17
|
+
<ul>
|
|
18
|
+
<li>
|
|
19
|
+
"<a href="/files/main/MEMORY.md">MEMORY.md</a>" is a per conversation, per
|
|
20
|
+
invocation, auto-loaded, persistent agent memory file.
|
|
21
|
+
</li>
|
|
22
|
+
<li>
|
|
23
|
+
It is designed to be a helpful scratchpad for agents to store important
|
|
24
|
+
information, notes, and context about the conversation.
|
|
25
|
+
</li>
|
|
26
|
+
</ul>
|
|
27
|
+
<h3 id="how-to-use-files">How to use Files</h3>
|
|
28
|
+
<ul>
|
|
29
|
+
<li>Open "<a href="/files/main">Files</a>" to browse your workspace.</li>
|
|
30
|
+
<li>
|
|
31
|
+
Edit and preview files with the file viewer:
|
|
32
|
+
<ul>
|
|
33
|
+
<li><a href="/files/main/index.html">index.html</a></li>
|
|
34
|
+
</ul>
|
|
35
|
+
</li>
|
|
36
|
+
</ul>
|
|
37
|
+
<h3 id="how-to-use-pages">How to use Pages</h3>
|
|
38
|
+
<ul>
|
|
39
|
+
<li>Use Set as Page on any markdown or HTML file to add it to Pages.</li>
|
|
40
|
+
<li>Remove a page anytime from the "<a href="/pages">Pages</a>" view.</li>
|
|
41
|
+
</ul>
|
|
42
|
+
<h3 id="how-to-use-chat">How to use Chat</h3>
|
|
43
|
+
<ul>
|
|
44
|
+
<li>
|
|
45
|
+
Open "<a href="/settings">Settings</a>" to configure your agent's system
|
|
46
|
+
prompt, tools, and more.
|
|
47
|
+
</li>
|
|
48
|
+
<li>
|
|
49
|
+
Open "<a href="/chat/main">Chat</a>" to start a conversation with your
|
|
50
|
+
agent.
|
|
51
|
+
</li>
|
|
52
|
+
</ul>
|
|
53
|
+
<h2 id="further-information">Further information</h2>
|
|
54
|
+
<ul>
|
|
55
|
+
<li>
|
|
56
|
+
<a href="https://github.com/xt-ml/shadow-claw#-shadowclaw"
|
|
57
|
+
>ShadowClaw Project</a
|
|
58
|
+
>
|
|
59
|
+
</li>
|
|
60
|
+
<li><a href="https://deepwiki.com/xt-ml/shadow-claw">Deep Wiki</a></li>
|
|
61
|
+
</ul>
|
|
62
|
+
</article>`;function et(){let e=u(`/static-main/index.html`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}async function tt(e){let t=await m(e,l.MAIN_GROUP_INDEX_SUPPRESSED);return t===!0||t===`true`}async function nt(e,t){await g(e,l.MAIN_GROUP_INDEX_SUPPRESSED,t)}async function I(e,t=c,n){try{if(await y(e,t,`index.html`)){if(t===`br:main`)try{let r=await b(e,t,`index.html`);typeof r==`string`&&(r.includes(`<shadow-claw`)||r.includes(`data-shadow-claw-dsd`))&&await D(e,t,`index.html`,n??F)}catch{}return!0}if(t===`br:main`&&await tt(e))return!1;let r=n;if(r===void 0&&typeof fetch==`function`)try{let e=await fetch(et());if(e.ok){let t=await e.text();!t.includes(`<shadow-claw`)&&!t.includes(`data-shadow-claw-dsd`)&&(r=t)}}catch{}return r??=F,await D(e,t,`index.html`,r),!0}catch(e){return console.warn(`Failed to ensure main workspace Memory:`,e),!1}}const L='---\ntitle: "Agent Memory"\ncreated: "1970-01-01T00:00:00Z"\nupdated: "1970-01-01T00:00:00Z"\nslug: "agent-memory"\n---\n\n## Memory\n\n### Workspace Layout & Skills Conventions\n\n- **Skills**: `.agents/skills/<skill-name>/SKILL.md` (canonical flat layout; legacy `.agents/skills/main/` supported for backward-compatible reads)\n- **Declarative Tools**: `.agents/tools/<tool-name>.json` (canonical flat layout; legacy `.agents/tools/main/` supported for backward-compatible reads)\n- **Skill Format**: Markdown file with YAML frontmatter AND a Markdown body (frontmatter is metadata only; always include a `# <Skill Title>` heading and human-readable description in the Markdown body so it renders in document previews):\n\n ```yaml\n ---\n name: <skill-name>\n description: <clear summary for model and slash command>\n user-invocable: true\n metadata:\n allowed-tools: <tool1> <tool2>\n execution:\n type: tools\n tools:\n - name: <tool1>\n input: { ... }\n - name: <tool2>\n input: { "$pipe": "prev" }\n ---\n # <Skill Title>\n\n <Overview and description of what the skill does, parameters, and usage instructions.>\n ```\n\n- **Declarative Tool Format**: JSON with `"name"`, `"description"`, `"executor": "javascript"`, `"inputSchema"`, and `"code"`.\n- **Open Agent Skills & Discovery**: Install community skills from [skills.sh](https://skills.sh) via `npx shadow-claw skills add <owner/repo>` (or `npx skills add`), search via `npx shadow-claw skills find <term>`, and publish RFC v0.2.0 discovery indexes via `npx shadow-claw skills:index` (`.well-known/agent-skills/index.json`).\n- **Authoring**: Use `create_directory` before writing new directories, then `write_file`.',rt=`MEMORY.md`;function it(){let e=u(`/static-main/MEMORY.md`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}async function R(e){let t=await m(e,l.MAIN_GROUP_README_SUPPRESSED);return t===!0||t===`true`}async function z(e,t){await g(e,l.MAIN_GROUP_README_SUPPRESSED,t)}async function B(e,t=c,n){try{if(await y(e,t,`MEMORY.md`)){if(t===`br:main`)try{let r=await b(e,t,rt);typeof r==`string`&&(r.includes(`<shadow-claw`)||r.includes(`data-shadow-claw-dsd`))&&await D(e,t,rt,n??L)}catch{}return!0}if(t===`br:main`&&await R(e))return!1;let r=n;if(r===void 0&&typeof fetch==`function`)try{let e=await fetch(it());if(e.ok){let t=await e.text();!t.includes(`<shadow-claw`)&&!t.includes(`data-shadow-claw-dsd`)&&(r=t)}}catch{}return r??=L,await D(e,t,rt,r),!0}catch(e){return console.warn(`Failed to ensure main workspace Memory:`,e),!1}}async function at(e,t,n=`.`){for(let r=0;r<2;r++)try{let r=await T(e,t);if(n&&n!==`.`){let e=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean);for(let t of e){let e=await r.getDirectoryHandle(t);if(typeof r.isSameEntry==`function`&&await r.isSameEntry(e))throw Error(`Directory navigation stuck at "${r.name}" for segment "${t}" — the stored directory handle may be stale.`);r=e}}let i=[];for await(let[e,t]of r.entries())i.push(t.kind===`directory`?`${e}/`:e);return i.sort()}catch(e){if(r===0&&te(e)){w();continue}throw e}return[]}function ot(e){if(!e||typeof e!=`object`)return!1;let t=globalThis.FileSystemDirectoryHandle;return t!==void 0&&e instanceof t||typeof e.getDirectoryHandle==`function`&&typeof e.getFileHandle==`function`&&typeof e.requestPermission==`function`}async function st(e){let t=await m(e,l.STORAGE_HANDLE);return!ot(t)||await t.requestPermission({mode:`readwrite`})===`granted`}function V(e){let t=s();return t?`shadowclaw:${t}:${e}`:e}function ct(e){if(typeof localStorage>`u`)return null;let t=V(e);try{let n=localStorage.getItem(t);if(n!==null)return n;if(t===e)return null;let r=localStorage.getItem(e);if(r!==null)return localStorage.setItem(t,r),r}catch(e){console.warn(`Unable to read from localStorage:`,e)}return null}function H(e,t){if(typeof localStorage>`u`)return;let n=V(e);try{localStorage.setItem(n,t)}catch(e){console.warn(`Unable to write to localStorage:`,e)}}function lt(e){if(typeof localStorage>`u`)return;let t=V(e);try{localStorage.removeItem(t)}catch(e){console.warn(`Unable to remove from localStorage:`,e)}}async function U(e,t){let n=await T(e,t);for await(let[e]of n.entries())await n.removeEntry(e,{recursive:!0})}async function W(e,t,n){let r=await T(e,t),{dirs:i,filename:a}=ne(n.replace(/\/$/,``)),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a,{recursive:!0})}function G(e,t){return`${e}:${t}`}async function ut(e){let t=await m(e,l.SUPPRESSED_PAGES_LIST);if(!t||typeof t!=`string`)return[];try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return[]}async function dt(e,t,n){let r=await ut(e),i=G(t,n);return r.some(e=>G(e.groupId,e.path)===i)}async function ft(e,t,n){let r=await ut(e),i=G(t,n);if(!r.some(e=>G(e.groupId,e.path)===i)){let i=[...r,{groupId:t,path:n}];await g(e,l.SUPPRESSED_PAGES_LIST,JSON.stringify(i))}}async function pt(e,t,n){let r=await ut(e),i=G(t,n),a=r.filter(e=>G(e.groupId,e.path)!==i);a.length!==r.length&&await g(e,l.SUPPRESSED_PAGES_LIST,JSON.stringify(a))}function K(e){return Array.from(new Set(e.map(e=>e.trim()).filter(Boolean)))}function mt(e){let t=e.trim().replace(/\\/g,`/`);return t===`/`||/^\/+$/.test(t)?`/`:t.replace(/^\/+/,``).replace(/\/+$/,``)}const ht=/\.(md|markdown|html|xhtml|txt)$/i;function q(e){return e===`/`?`/`:e.replace(ht,``)}function gt(e){let t=e.trim().replace(/\\/g,`/`);return t===`/`||/^\/+$/.test(t)?`/`:t.replace(/^\/+/,``).replace(/\/+$/,``)}function _t(e){return e?e.replace(/^br:/i,``).replace(/^br-/i,``).trim():`main`}function J(e,t){let n=gt(t);if(!n)return;e.add(n);let r=q(n);r&&r!==n&&e.add(r)}function vt(e,t,n){let r=/* @__PURE__ */ new Set;if(!e)return r;let i=_t(t);if(e===`/`){if(r.add(`/`),J(r,`index.html`),n){let e=mt(n);e&&e!==`/`&&J(r,`${e}/index.html`)}return J(r,`pages/index.html`),J(r,`pages/${i}/index.html`),J(r,`${i}/index.html`),r}if(J(r,e),n){let t=mt(n);t&&t!==`/`&&J(r,`${t}/${e}`)}if(e.startsWith(`pages/`)){let t=e.slice(6);J(r,t),t.startsWith(`${i}/`)?J(r,t.slice(`${i}/`.length)):J(r,t.replace(/^[^/]+\//,``))}else J(r,`pages/${e}`),J(r,`pages/${i}/${e}`),J(r,`${i}/${e}`);for(let e of Array.from(r)){let t=q(e);if(e===`index.html`||t===`index`){r.add(`/`);break}}return r}function yt(e,t){let n=t.toLowerCase(),r=q(t).toLowerCase(),i=n===r?[n]:[n,r];for(let t of e){let e=t.toLowerCase(),n=q(e);for(let t of i)if(t&&(e===t||n===t||t!==`/`&&(e.startsWith(`${t}/`)||n.startsWith(`${t}/`)||e.endsWith(`/${t}`)||n.endsWith(`/${t}`)||e.includes(`/${t}/`)||n.includes(`/${t}/`))))return!0}return!1}function bt(e,t){for(let n of t){let t=mt(n);if(t&&yt(e,t))return!0}return!1}function xt(e,t,n,r){if(!e||typeof e!=`string`)return!1;let i=gt(e);if(!i)return!1;let a=[],o=[],s,c;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t,n=e.allowList??e.allowlist??[],r=e.denyList??e.denylist??[];a=K(Array.from(n||[])),o=K(Array.from(r||[])),s=e.groupId,c=e.basePathPrefix}else a=K(Array.from(t||[])),o=K(Array.from(n||[])),s=r?.groupId,c=r?.basePathPrefix;let l=vt(i,s,c);return o.length>0&&bt(l,o)?!1:a.length>0?bt(l,a):!0}function St(e=c){return e===`br:main`?l.STATIC_MAIN_SITE_SEEDED:`${l.STATIC_MAIN_SITE_SEEDED}:${e}`}async function Ct(e,t=c){let n=St(t),r=await m(e,n);return r===!0||r===`true`}async function wt(e,t=c,n=!0){let r=St(t);await g(e,r,n)}function Tt(){let e=u(`/static-main-manifest.json`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}function Et(e){let t=e.replace(/^\/+/,``),n=`static-main`;if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);typeof t?.pages?.baseUrl==`string`&&(n=t.pages.baseUrl.replace(/^\/+/,``).replace(/\/+$/,``))}}catch{}let r=u(n?`/${n}/${t}`:`/${t}`);if(typeof window<`u`&&window.location?.origin)try{return new URL(r,window.location.origin).toString()}catch{return r}return r}async function Dt(){if(typeof fetch!=`function`)return null;try{let e=Tt(),t=await fetch(e);if(t.ok){if((t.headers?.get?.(`content-type`)||``).includes(`text/html`))return null;let e=await t.json();if(e&&Array.isArray(e.pages))return e}}catch{}return null}async function Ot(e){if(typeof fetch!=`function`)return null;try{let t=Et(e),n=await fetch(t);if(n.ok){let t=n.headers?.get?.(`content-type`)||``;if((e.endsWith(`.md`)||e.endsWith(`.markdown`)||e.endsWith(`.json`))&&t.includes(`text/html`))return null;let r=await n.text();return r.includes(`<shadow-claw`)||r.includes(`data-shadow-claw-dsd`)?null:r}}catch{}return null}function kt(e){if(typeof document>`u`)return null;let t=t=>{if(!t||!(t instanceof HTMLElement))return!1;if(!e)return!0;let n=t.getAttribute(`data-initial-path`)?.trim();return!n||n===e},n=document.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(n))return n;let r=document.querySelector(`shadow-claw`)?.shadowRoot,i=(r?.querySelector(`shadow-claw-pages`)?.shadowRoot)?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`)||r?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(i))return i;let a=document.querySelectorAll(`template`);for(let n of Array.from(a)){let r=n.content?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(r))return r;let i=n.content?.querySelectorAll(`template`);if(i)for(let n of Array.from(i)){let r=n.content?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(r))return r}}return null}function Y(e=`index.html`){let t=kt(e);if(!t)return null;let n=t.getAttribute(`data-initial-path`)?.trim();if(n&&n!==e)return null;let r=t.querySelector(`[data-markdown-frontmatter]`),i=null;if(r){let e=r.getAttribute(`data-frontmatter`);if(e)try{i=JSON.parse(e)}catch{}}let a=t.cloneNode(!0),o=a.querySelector(`[data-markdown-frontmatter]`);o&&o.remove();let s=a.innerHTML.trim();if(!s&&!i)return null;if(i&&Object.keys(i).length>0){let e=[`---`];for(let[t,n]of Object.entries(i))typeof n==`string`?e.push(`${t}: ${JSON.stringify(n)}`):typeof n==`number`||typeof n==`boolean`?e.push(`${t}: ${n}`):e.push(`${t}: ${JSON.stringify(n)}`);return e.push(`---`,``),`${e.join(`
|
|
63
|
+
`)}\n${s}`}return s}async function At(e={}){let t=()=>{let e=null;if(typeof document<`u`){let t=document.getElementById(`shadow-claw-static-manifest`);if(t&&t.textContent)try{let n=JSON.parse(t.textContent);n&&Array.isArray(n.pages)&&(e={...n,pages:[...n.pages]})}catch(e){console.warn(`Failed to parse embedded static main manifest:`,e)}let n=document.querySelectorAll(`script[type="text/markdown"][data-shadow-claw-page]`);if(n.length>0){e||={pages:[]};for(let t of Array.from(n)){let n=t.getAttribute(`data-shadow-claw-page`)?.trim();if(n){let r=t.textContent||``;r=ie(r),!r.trim()&&/^memory\.(md|markdown)$/iu.test(n)&&(r=L),!r.trim()&&(n===`index.html`||/^index\.(html?|xhtml)$/iu.test(n))&&(r=Y(n)??F);let i=e.pages.findIndex(e=>e.displayPath===n);i>=0?e.pages[i].content=r:e.pages.push({displayPath:n,content:r})}}}let r=document.getElementById(`shadow-claw-site-config`);if(r?.textContent)try{let t=JSON.parse(r.textContent);if(Array.isArray(t?.pages?.files)){e||={pages:[]};for(let n of t.pages.files)if(typeof n==`string`&&n.trim()){let t=n.trim(),r=``;/^memory\.(md|markdown)$/iu.test(t)?r=L:(t===`index.html`||/^index\.(html?|xhtml)$/iu.test(t))&&(r=Y(t)??F),e.pages.some(e=>e.displayPath===t)||e.pages.push({displayPath:t,content:r})}}}catch{}let i=kt();if(i){e||={pages:[]};let t=i.getAttribute(`data-initial-path`)?.trim()||`index.html`;if(!e.pages.some(e=>e.displayPath===t)){let n=Y(t)??F;e.pages.push({displayPath:t,content:n})}e.pages.some(e=>/^memory\.(md|markdown)$/iu.test(e.displayPath))||e.pages.push({displayPath:`MEMORY.md`,content:L})}}return e};if(e.preferEmbedded!==!1){let e=t();if(e&&e.pages.length>0)return e}if(e.fetchFallback!==!1){let e=await Dt();if(e&&e.pages.length>0)return e}if(e.preferEmbedded===!1){let e=t();if(e&&e.pages.length>0)return e}return{pages:[{displayPath:`index.html`,content:F},{displayPath:`MEMORY.md`,content:L}]}}async function jt(e){if(typeof document<`u`){let t=document.getElementById(`shadow-claw-static-manifest`);if(t&&t.textContent)try{let n=JSON.parse(t.textContent);if(n&&Array.isArray(n.pages)){let t=n.pages.find(t=>t.displayPath===e);if(t&&typeof t.content==`string`&&t.content.trim())return t.content}}catch{}let n=document.querySelectorAll(`script[type="text/markdown"][data-shadow-claw-page]`);for(let t of Array.from(n))if(t.getAttribute(`data-shadow-claw-page`)?.trim()===e){let e=t.textContent||``;if(e.trim())return e}let r=Y(e);if(typeof r==`string`&&r.trim())return r;if(/^memory\.(md|markdown)$/iu.test(e))return L;if(e===`index.html`||/^index\.(html?|xhtml)$/iu.test(e))return F}let t=await Ot(e);if(typeof t==`string`)return t;let n=await Dt();if(n&&Array.isArray(n.pages)){let t=n.pages.find(t=>t.displayPath===e);if(t&&typeof t.content==`string`)return t.content}return null}async function Mt(e,t,n=[]){for(let[r,i]of Object.entries(t))if(r===`purgePreRenderedStaticPages`&&i===!0){if(n.length>0){let t=n[0],r=n.slice(1).join(`/`);try{r?await W(e,t,r):await U(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await Mt(e,i,[...n,r])}function Nt(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t?.pages?.sortOrder===`desc`)return`desc`;if(t?.pages?.sortOrder===`asc`)return`asc`}}catch{}return`desc`}function Pt(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent)?.pages?.defaultPinnedPage;if(typeof t==`string`&&t.trim().length>0)return t.trim()}}catch{}return null}function Ft(){let e=`ShadowClaw`,t,n;if(typeof document<`u`){try{let r=document.getElementById(`shadow-claw-site-config`);if(r?.textContent){let i=JSON.parse(r.textContent);i?.site?.title&&(e=String(i.site.title).trim()),(i?.site?.titleSeparator??i?.site?.sep)&&(t=String(i.site.titleSeparator??i.site.sep)),i?.site?.titleTemplate&&(n=String(i.site.titleTemplate))}}catch{}if(e===`ShadowClaw`&&document.title){let t=document.title.split(/\s*[-|—•·]\s*/),n=t[t.length-1]?.trim();n&&(e=n)}}return{siteTitle:e,separator:t,titleTemplate:n}}function It(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);return{allowList:K(t?.pages?.allowList??t?.pages?.allowlist??t?.allowList??t?.allowlist??[]),denyList:K(t?.pages?.denyList??t?.pages?.denylist??t?.denyList??t?.denylist??[])}}}catch{}return{allowList:[],denyList:[]}}function Lt(e,t){let n=t??Nt();return[...e].sort((e,t)=>{let r=e.path,i=t.path,a=r.split(`/`).pop()||``,o=i.split(`/`).pop()||``,s=/^index\.(html?|xhtml)$/iu.test(a),c=/^index\.(html?|xhtml)$/iu.test(o);if(s&&!c)return-1;if(!s&&c)return 1;let l=/^memory\.(md|markdown)$/iu.test(a),u=/^memory\.(md|markdown)$/iu.test(o);return l&&!u?1:!l&&u?-1:n===`asc`?r.localeCompare(i,void 0,{numeric:!0,sensitivity:`base`}):i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})})}async function Rt(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(ct(n)===i)return!0}catch{}try{if(await m(e,r)===i){try{H(n,i)}catch{}return!0}await g(e,r,i);try{H(n,i)}catch{}}catch{try{H(n,i)}catch{}}return!1}async function zt(e,t=c,n=[],r={}){await I(e,t);let i=await At(r),a=!1;i.preRenderedStaticPages&&(await Rt(e,i.purgeId)||(a=!0,await Mt(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await Rt(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await W(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}try{await W(e,t,`.agents/tools/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}}for(let n of i.pages)if(n.content?.includes(`slug: "shadow-claw--purge-pages"`)){!a&&!await Rt(e,i.purgeId)&&(a=!0,await U(e,t));break}let s=t===`br:main`&&await R(e),l=new Set(i.pages.map(e=>G(t,e.displayPath))),u=a?n.filter(e=>e.groupId!==t||l.has(G(e.groupId,e.path))):[...n],{allowList:d,denyList:f}=It(),p=0;for(let n of i.pages)if(p++,p%5==0&&await new Promise(e=>setTimeout(e,0)),!n.content?.includes(`slug: "shadow-claw--purge-pages"`)&&xt(n.displayPath,{allowList:d,denyList:f,groupId:t})){if(/^memory\.(md|markdown)$/iu.test(n.displayPath)){if(s)continue;let r=typeof n.content==`string`&&n.content.trim().length>0&&n.content!==L?n.content:void 0;if(r===void 0?await B(e,t):await B(e,t,r)){let e=G(t,n.displayPath);u.some(t=>G(t.groupId,t.path)===e)||u.push({groupId:t,path:n.displayPath})}}else if(!await dt(e,t,n.displayPath))try{if(!await y(e,t,n.displayPath)){let r=n.content;(typeof r!=`string`||!r.trim())&&(r=n.displayPath===`index.html`?Y(`index.html`)??F:await Ot(n.displayPath)??``),await D(e,t,n.displayPath,r)}let r=G(t,n.displayPath);u.some(e=>G(e.groupId,e.path)===r)||u.push({groupId:t,path:n.displayPath})}catch(e){console.warn(`Failed to seed static page file ${n.displayPath}:`,e)}}if(t===`br:main`){for(let n of i.skills||[]){let r=`.agents/skills/main/${n.displayPath}`;try{await y(e,t,r)||await D(e,t,r,n.content)}catch(e){console.warn(`Failed to seed skill file ${r}:`,e)}}for(let n of i.tools||[]){let r=`.agents/tools/main/${n.displayPath}`;try{(o||!await y(e,t,r))&&await D(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let m=typeof document<`u`&&(document.getElementById(`shadow-claw-static-manifest`)!==null||document.querySelector(`script[type="text/markdown"][data-shadow-claw-page]`)!==null||kt()!==null);r.preferEmbedded!==!1&&m||await wt(e,t,!0);let h=u.filter(e=>xt(e.path,{allowList:d,denyList:f,groupId:e.groupId}));return Object.defineProperty(h,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(h,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),Lt(h)}var Bt=class{_events;_handlers=[];_runs=/* @__PURE__ */ new Map;constructor(e){this._events=e}start(){this._listen(`streaming-start`,this._onStreamingStart),this._listen(`streaming-chunk`,this._onStreamingChunk),this._listen(`streaming-end`,this._onStreamingEnd),this._listen(`streaming-done`,this._onStreamingDone),this._listen(`streaming-error`,this._onStreamingError),this._listen(`tool-activity`,this._onToolActivity)}stop(){for(let{event:e,handler:t}of this._handlers)this._events.off(e,t);this._handlers=[],this._runs.clear()}_emit(e,t){window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{groupId:e,event:t}}))}_listen(e,t){this._events.on(e,t),this._handlers.push({event:e,handler:t})}_onStreamingChunk=({groupId:e,text:t})=>{let n=this._runs.get(e);n&&n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_CONTENT`,messageId:n.messageId,delta:t,timestamp:Date.now()})};_onStreamingDone=({groupId:e})=>{let t=this._runs.get(e);t&&(t.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_FINISHED`,threadId:t.threadId,runId:t.runId,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingEnd=({groupId:e})=>{let t=this._runs.get(e);t&&t.messageId&&(this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),t.messageId=null)};_onStreamingError=({groupId:e,error:t})=>{let n=this._runs.get(e);n&&(n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:n.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_ERROR`,message:t||`Unknown streaming error`,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingStart=({groupId:e})=>{let t=_(),n=e,r=_();this._runs.set(e,{runId:t,threadId:n,messageId:r,activeToolCallIds:/* @__PURE__ */ new Set}),this._emit(e,{type:`RUN_STARTED`,threadId:n,runId:t,timestamp:Date.now()}),this._emit(e,{type:`TEXT_MESSAGE_START`,messageId:r,role:`assistant`,timestamp:Date.now()})};_onToolActivity=({groupId:e,tool:t,status:n})=>{let r=this._runs.get(e);if(r){if(n===`running`){let n=_();r.activeToolCallIds.add(n),this._emit(e,{type:`TOOL_CALL_START`,toolCallId:n,toolCallName:t,timestamp:Date.now()}),r._lastToolCallId=n}else if(n===`done`||n===`error`){let t=r._lastToolCallId;t&&(r.activeToolCallIds.delete(t),this._emit(e,{type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()}))}}}};function Vt(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)Ht(n,e);return n}function Ht(e,t){let{op:n,path:r,value:i}=t;if(!r||!r.startsWith(`/`))return;let a=r.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),o=a.pop();if(o===void 0)return;let s=e;for(let e of a){if(typeof s!=`object`||!s)return;s=s[e]}typeof s==`object`&&s&&(Array.isArray(s)?Ut(s,o,n,i):Wt(s,o,n,i))}function Ut(e,t,n,r){if(n===`add`){if(t===`-`)e.push(r);else{let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<=e.length&&e.splice(n,0,r)}}else if(n===`replace`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&(e[n]=r)}else if(n===`remove`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&e.splice(n,1)}}function Wt(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}function Gt(e){if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t))return K(t.map(e=>String(e)))}catch{}return K(e.split(`,`))}let X=/* @__PURE__ */ new Map;function Z(e){if(typeof document>`u`)return null;let t=`shadow-claw-site-config`;if(e){let n=e.getAttribute(`config`)?.trim();n&&(t=n.replace(/^#/,``))}let n=document.getElementById(t);if(!n?.textContent)return X.delete(t),null;let r=X.get(t);if(r&&r.rawText===n.textContent)return r.config;try{let e=JSON.parse(n.textContent);if(!e||typeof e!=`object`)return X.delete(t),null;let r={...e};return X.set(t,{rawText:n.textContent,config:r}),r}catch(e){return console.warn(`[ShadowClaw] Failed to parse site configuration from #${t}:`,e),null}}var Kt=/* @__PURE__ */ e({OrchestratorStore:()=>Qt,accumulateTokenUsage:()=>Zt,orchestratorStore:()=>$t});function qt(e){if(e){if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:void 0}catch{return}}}function Jt(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return typeof e==`number`&&e===1}function Yt(e){return!!e}async function Q(e,t,n,r){if(!Yt(r))return!0;if(!e.schedule)return await $(e.id,t,n,r)!==`failed`;try{let r=t.replace(/\/$/,``);return(await fetch(`${r}/tasks`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,subscriberId:n})})).ok}catch{return!1}}async function $(e,t,n,r){if(!Yt(r))return`missing`;try{let r=t.replace(/\/$/,``),i=`subscriberId=${encodeURIComponent(n)}`,a=await fetch(`${r}/tasks/${encodeURIComponent(e)}?${i}`,{method:`DELETE`});return a.ok?`deleted`:a.status===404||a.status===405?`missing`:`failed`}catch{return`failed`}}async function Xt(e,t,n,r){if(!Yt(r))return null;try{let r=t.replace(/\/$/,``),i=await fetch(`${r}/tasks?groupId=${encodeURIComponent(e)}&subscriberId=${encodeURIComponent(n)}`,{method:`GET`});if(!i.ok||typeof i.json!=`function`)return null;let a=await i.json();return Array.isArray(a)?a.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.schedule==`string`&&typeof e.prompt==`string`).map(t=>({id:t.id,groupId:t.group_id||t.groupId||e,schedule:t.schedule,type:t.type,prompt:t.prompt,tools:qt(t.tools),channel:typeof t.channel==`string`?t.channel:void 0,enabled:t.enabled===!0||t.enabled===1,lastRun:typeof t.lastRun==`number`?t.lastRun:typeof t.last_run==`number`?t.last_run:null,createdAt:typeof t.createdAt==`number`?t.createdAt:typeof t.created_at==`number`?t.created_at:Date.now(),name:typeof t.name==`string`?t.name:void 0,order:typeof t.order==`number`?t.order:typeof t.task_order==`number`?t.task_order:void 0})):null}catch{return null}}function Zt(e,t){let n=(e?.inputTokens??0)+(t.inputTokens??0),r=(e?.outputTokens??0)+(t.outputTokens??0),i=(e?.cacheReadTokens??0)+(t.cacheReadTokens??0),a=(e?.cacheCreationTokens??0)+(t.cacheCreationTokens??0);return{groupId:t.groupId||e?.groupId||``,inputTokens:n,outputTokens:r,cacheReadTokens:i,cacheCreationTokens:a,totalTokens:n+r+i+a,contextLimit:t.contextLimit||e?.contextLimit||0}}var Qt=class e{static DEFAULT_PAGE_PATH=`MEMORY.md`;orchestrator;_activeGroupId;_activePage;_activePinnedPage;_defaultPinnedPage;_activityLog;_activityLogSessionStartedAtByGroup;_aguiAdapter;_aguiEvent;_contextUsage;_currentPath;_db;_error;_files;_gitProxyUrl;_groups;_hadPersistedActivePage;_initResolve;_isTyping;_lastOrchestratorDisplayState=`idle`;_messages;_modelDownloadProgress;_onlineReplayHandler;_pages;_pagesAllowList;_pagesDenyList;_peerStateByGroup;_proxyUrl;_ready;_remoteAgentStatusByGroup;_remoteAgentTypingByGroup;_replayingTaskSyncOutbox;_subscriberId;_sidebarDefaultPage;_state;_storageStatus;_streamingText;_tasks;_taskSyncOutbox;_tokenUsage;_tokenUsageAccumulator=null;_toolActivity;_unreadGroupIds;_useProxy;_vmBashFullInternetAccess;_whenInitialized;_whenReady;_readyResolve;constructor(){this._messages=new h.State([]),this._isTyping=new h.State(!1),this._storageStatus=new h.State(null),this._toolActivity=new h.State(null),this._modelDownloadProgress=new h.State(null),this._activityLog=new h.State([]),this._state=new h.State(`idle`),this._tokenUsage=new h.State(null),this._error=new h.State(null),this._activeGroupId=new h.State(c),this._ready=new h.State(!1),this._tasks=new h.State([]),this._files=new h.State([]),this._currentPath=new h.State(`.`),this._groups=new h.State([]),this._unreadGroupIds=new h.State(/* @__PURE__ */ new Set),this._streamingText=new h.State(null),this._aguiEvent=new h.State(null),this._contextUsage=new h.State(null),this._useProxy=new h.State(!1),this._proxyUrl=new h.State(`/proxy`),this._gitProxyUrl=new h.State(`/git-proxy`),this._vmBashFullInternetAccess=new h.State(!1),this._activePage=new h.State(`pages`);let e=Z()?.sidebar?.defaultPage,t=e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`;this._sidebarDefaultPage=new h.State(t),this._pages=new h.State([]),this._pagesAllowList=new h.State([]),this._pagesDenyList=new h.State([]),this._activePinnedPage=new h.State(null),this._defaultPinnedPage=new h.State(null),this._remoteAgentStatusByGroup=new h.State(/* @__PURE__ */ new Map),this._remoteAgentTypingByGroup=new h.State(/* @__PURE__ */ new Map),this._peerStateByGroup=new h.State(/* @__PURE__ */ new Map),this._hadPersistedActivePage=!1,this._initResolve=null,this._whenInitialized=new Promise(e=>{this._initResolve=e}),this._readyResolve=null,this._whenReady=new Promise(e=>{this._readyResolve=e}),this.orchestrator=null,this._db=null,this._activityLogSessionStartedAtByGroup=/* @__PURE__ */ new Map,this._taskSyncOutbox=[],this._replayingTaskSyncOutbox=!1,this._subscriberId=null,this._onlineReplayHandler=null,this._aguiAdapter=null}get activeGroupId(){return this._activeGroupId.get()}get activePage(){return this._activePage.get()}get activePinnedPage(){return this._activePinnedPage.get()}get defaultPinnedPage(){return this._defaultPinnedPage.get()}get pagesAllowList(){return this._pagesAllowList.get()}get pagesDenyList(){return this._pagesDenyList.get()}isPageAllowed(e,t){return xt(e,{allowList:this._pagesAllowList.get(),denyList:this._pagesDenyList.get(),groupId:t??this._activeGroupId.get()})}get effectiveDefaultPage(){let e=this._defaultPinnedPage.get();return e&&this.isPageAllowed(e.path,e.groupId)?e:this._pages.get()[0]||null}get activityLog(){return this._activityLog.get()}get taskServerEnabled(){return this.orchestrator?.taskServerEnabled??!1}get aguiEvent(){return this._aguiEvent.get()}clearError(){this._error.set(null),this._state.get()===`error`&&this._state.set(`idle`)}get contextUsage(){return this._contextUsage.get()}get tokenUsageAccumulator(){return this._tokenUsageAccumulator}get currentPath(){return this._currentPath.get()}get error(){return this._error.get()}get files(){return this._files.get()}getPeerState(e){return this._peerStateByGroup.get().get(e)||null}getRemoteAgentStatus(e){return this._remoteAgentStatusByGroup.get().get(e)||`idle`}getState(){return{messages:this.messages,isTyping:this.isTyping,toolActivity:this.toolActivity,activityLog:this.activityLog,state:this.state,tokenUsage:this.tokenUsage,modelDownloadProgress:this.modelDownloadProgress,error:this.error,activeGroupId:this.activeGroupId,pages:this.pages,ready:this.ready,files:this.files,currentPath:this.currentPath,streamingText:this.streamingText,contextUsage:this.contextUsage}}getTasksForBackup(){return this._tasks.get()}get gitProxyUrl(){return this._gitProxyUrl.get()}get groups(){return this._groups.get()}get hadPersistedActivePage(){return this._hadPersistedActivePage}isRemoteAgentTyping(e){return this._remoteAgentTypingByGroup.get().get(e)||!1}get isTyping(){return this._isTyping.get()}get messages(){return this._messages.get()}get modelDownloadProgress(){return this._modelDownloadProgress.get()}get pages(){return this._pages.get()}get proxyUrl(){return this._proxyUrl.get()}get ready(){return this._ready.get()}sendMessage(e,t=[],n){n===void 0?this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t):this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t,n)}async sendFileToPeer(e,t=this._activeGroupId.get(),n){let r=t.startsWith(`peer:`),i=t.startsWith(`room:`);if(!r&&!i){let e=`Can only send files to peers in a peer or room conversation.`;throw O(e,4500),Error(e)}let a=this.orchestrator?.router;if(!a){let e=`Network router is not initialized.`;throw O(e,4500),Error(e)}let o=n?.fileName||e.split(`/`).pop()||e,s=n?.mimeType||`application/octet-stream`,c=n?.size||0;a.setTyping(t,!0);try{let n={path:e,fileName:o,mimeType:s,size:c};if(await a.send(t,``,[n]),this._db){let e={id:_(),groupId:t,sender:`You`,content:``,timestamp:Date.now(),channel:i?`room`:`peerjs`,attachments:[n],isFromMe:!1,isTrigger:!1};await N(this._db,e),this.orchestrator?.events.emit(`message`,e)}ae(`Sent ${o} to ${i?`room peers`:`peer`}`,2500)}catch(e){let t=e instanceof Error?e.message:String(e);throw console.error(`sendFileToPeer error:`,e),O(`Failed to send file: ${t}`,6e3),e}finally{a.setTyping(t,!1)}}setActiveGroup(e,t,n=this._activePage.get()===`chat`){if(this._activeGroupId.set(t),this._messages.set([]),this._activityLog.set([]),this._error.set(null),this._isTyping.set(!1),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._currentPath.set(`.`),n){let e=new Set(this._unreadGroupIds.get());e.delete(t)&&this._unreadGroupIds.set(e)}this.loadHistory(),this.loadTasks(e),this.loadFiles(e)}setReady(e=!0){this._ready.set(e),e&&this._readyResolve&&this._readyResolve()}setRemoteAgentStatus(e,t){let n=this._remoteAgentStatusByGroup.get(),r=new Map(n);r.set(e,t),this._remoteAgentStatusByGroup.set(r)}setRemoteAgentTyping(e,t){let n=this._remoteAgentTypingByGroup.get(),r=new Map(n);t?r.set(e,!0):r.delete(e),this._remoteAgentTypingByGroup.set(r)}get sidebarDefaultPage(){return this._sidebarDefaultPage.get()}get state(){return this._state.get()}stopCurrentRequest(){this.orchestrator?.stopCurrentRequest?.(this._activeGroupId.get())}get storageStatus(){return this._storageStatus.get()}get streamingText(){return this._streamingText.get()}syncHostWorkspaceToVM(){fe(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){pe(this.orchestrator,this._activeGroupId.get())}get tasks(){return this._tasks.get()}get tokenUsage(){return this._tokenUsage.get()}get toolActivity(){return this._toolActivity.get()}get unreadGroupIds(){return this._unreadGroupIds.get()}get useProxy(){return this._useProxy.get()}get vmBashFullInternetAccess(){return this._vmBashFullInternetAccess.get()}get whenInitialized(){return this._whenInitialized}async resetSiteConfigSeed(e){await g(e,l.SITE_CONFIG_SEEDED,!1)}get whenReady(){return this._whenReady}async addPage(e,t,n=this._activeGroupId.get()){let r=n===`br:main`?this.normalizePagePath(t):t.trim();if(!r||!this.isPageAllowed(r,n))return;let i=this._pages.get();i.some(e=>e.path===r&&e.groupId===n)||(this.setPages([...i,{groupId:n,path:r}]),await pt(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await z(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await v(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r)await $(t.id,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)===`failed`?(console.warn(`Failed to delete task "${t.id}" from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t.id,queuedAt:Date.now()})):await Le(e,t.id);await this.loadTasks(e)}async cloneConversation(e,t){let n=await Ke(e,t);if(!n)return null;await Pe(e,t,n.groupId),await Fe(e,t,n.groupId);try{let r=await b(e,t,`MEMORY.md`);r&&await D(e,n.groupId,`MEMORY.md`,r)}catch{}try{await Qe(e,t,n.groupId,`attachments`)}catch{}return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async compactContext(e){if(!this.orchestrator)return;let{compactContext:t}=await import(`./compact-context-dHitmPsV.js`);return t(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await Ve(e,t);return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await We(e,t),await Ne(e,t),await this.loadGroups(e),this._activeGroupId.get()===t)){let t=this._groups.get()[0]?.groupId||`br:main`;this.setActiveGroup(e,t)}}async deleteMessage(e,t){await Ie(e,t),await this.loadHistory(),this.orchestrator?.refreshContextUsage&&await this.orchestrator.refreshContextUsage(e,this._activeGroupId.get())}async deleteTask(e,t){let n=await this.getSubscriberId(e);if(await $(t,this.getTaskServerBaseUrl(),n,this.orchestrator?.taskServerEnabled??!1)===`failed`)throw console.warn(`Failed to delete task from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t,queuedAt:Date.now()}),Error(`Failed to delete scheduled task on server; task kept locally.`);await Le(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await M(e);if(!r.find(e=>e.groupId===n)){let i=[...r],a=``;if(this.orchestrator?.peerjsPeerAliases){for(let[e,n]of Object.entries(this.orchestrator.peerjsPeerAliases))if(n===t){a=e;break}}i.push({groupId:n,name:`Peer: ${a||t.substring(0,8)}`,createdAt:Date.now()}),await j(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await st(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,i){this._db=e,this.orchestrator=i,this._taskSyncOutbox=this.parseTaskSyncOutbox(await m(e,l.TASK_SYNC_OUTBOX)),await this.replayTaskSyncOutbox(e),typeof window<`u`&&!this._onlineReplayHandler&&(this._onlineReplayHandler=()=>{this._db&&this.replayTaskSyncOutbox(this._db)},window.addEventListener(`online`,this._onlineReplayHandler)),i.events.on(`a2ui-surface`,async({groupId:t,envelope:n})=>{t&&this.ensureGroupExists(e,t);let r=this._messages.get(),i=r.findIndex(e=>e.a2uiEnvelopes?.some(e=>e.surfaceId===n.surfaceId));if(i!==-1){let t=r[i],a=[...t.a2uiEnvelopes||[],n],o={...t,a2uiEnvelopes:a},s=[...r];s[i]=o,this._messages.set(s),await N(e,o)}else{let i=!t.startsWith(`peer:`),a={id:_(),groupId:t,sender:i?`agent`:t.replace(/^peer:/,``),content:``,timestamp:Date.now(),channel:t.startsWith(`peer:`)?`peerjs`:`browser`,isFromMe:i,isTrigger:!1,a2uiEnvelopes:[n]};t===this._activeGroupId.get()&&this._messages.set([...r,a]),await N(e,a)}}),i.events.on(`message`,t=>{if(t.groupId&&this.ensureGroupExists(e,t.groupId,t.timestamp),t.groupId&&t.groupId!==this._activeGroupId.get()){let e=new Set(this._unreadGroupIds.get());e.add(t.groupId),this._unreadGroupIds.set(e)}else t.isFromMe&&this._streamingText.get()!==null&&this._streamingText.set(null),this._messages.set([...this._messages.get(),t])}),i.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),i.events.on(`tool-activity`,({groupId:e,tool:t,status:n})=>{e&&e!==this._activeGroupId.get()||this._toolActivity.set(n===`running`?{tool:t,status:n}:null)}),i.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),i.events.on(`thinking-log`,e=>{e.groupId&&e.groupId!==this._activeGroupId.get()||(e.level===`info`&&e.label===`Starting`?this._activityLog.set([e]):this._activityLog.set([...this._activityLog.get(),e]),this.forwardActivityLogEntryToServer(e))}),i.events.on(`state-change`,e=>{let t=typeof e==`string`?e:e.state,n=typeof e==`string`?void 0:e.groupId;if(n&&n!==this._activeGroupId.get())return;let r=this._lastOrchestratorDisplayState;this._lastOrchestratorDisplayState=t,this._state.set(t),t===`idle`&&(this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null)),t===`thinking`&&r!==`thinking`&&r!==`responding`&&(this._tokenUsageAccumulator=null)}),i.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),i.events.on(`session-reset`,()=>{this._messages.set([]),this._activityLog.set([]),this._tokenUsageAccumulator=null,this._tokenUsage.set(null),this._contextUsage.set(null),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._isTyping.set(!1),this._state.set(`idle`)}),i.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),i.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=Zt(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),i.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),i.events.on(`ready`,()=>{this._ready.set(!0)}),i.events.on(`task-change`,()=>{this.loadTasks(e)}),i.events.on(`file-change`,()=>{this.loadFiles(e)}),i.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),i.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),i.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),i.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),i.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new Bt(i.events),this._aguiAdapter.start(),typeof window<`u`&&window.addEventListener(`shadow-claw-agui-event`,(e=>{e.detail.groupId===this._activeGroupId.get()&&this._aguiEvent.set(e.detail);let t=e.detail.event;if(t){if(t.type===`STATE_SNAPSHOT`){let n=new Map(this._peerStateByGroup.get());n.set(e.detail.groupId,t.snapshot||{}),this._peerStateByGroup.set(n)}else if(t.type===`STATE_DELTA`){let n=new Map(this._peerStateByGroup.get()),r=Vt(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await r(e),t(),n(),await k();let s=await m(e,l.PAGES_ALLOW_LIST),u=await m(e,l.PAGES_DENY_LIST);s&&this._pagesAllowList.set(Gt(String(s))),u&&this._pagesDenyList.set(Gt(String(u))),await k();let d=typeof document<`u`&&document.getElementById(`shadow-claw-static-routing`)!==null,f=await m(e,l.PAGES_LIST),p=f==null?[]:this.parsePagesList(f),h=await zt(e,c,p);h.length>0?(this.setPages(h),await this.persistPages(e)):await this.ensureDefaultPage(e),await k(),await this.applySiteConfigDefaults(e),await k(),await this.loadGroups(e);let g=await m(e,l.LAST_ACTIVE_GROUP);g&&g!==this._activeGroupId.get()&&this._activeGroupId.set(g),await k();let v=await m(e,l.LAST_ACTIVE_PAGE);v&&(this._activePage.set(v),this._hadPersistedActivePage=!0);let y=await m(e,l.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(y));let b=Pt(),x=null;if(b&&(x=o(b)),!x){let t=await m(e,l.DEFAULT_PINNED_PAGE);t&&(x=o(t))}x&&this.isPageAllowed(x.path,x.groupId)&&this._defaultPinnedPage.set(x),await k();let S=typeof window<`u`&&window.history?window.history.state:null,C=!!(S?.inFeedScroll||S?.scrollSpy||S?.suppressRouter)||typeof window<`u`&&window.location&&(()=>{let e=window.location.pathname||`/`,t=a();t!==`/`&&e.startsWith(t)&&(e=`/`+e.slice(t.length));let n=e.split(`/`).filter(Boolean);return n.length===0||n.length===1&&n[0]===`index.html`})(),w=!1;if(C&&x&&this.isPageAllowed(x.path,x.groupId)&&(this._activePinnedPage.set(x),w=!0),!w){let t=await m(e,l.LAST_SELECTED_PINNED_PAGE);if(t)try{let e=JSON.parse(t);e&&typeof e.path==`string`&&typeof e.groupId==`string`&&this.isPageAllowed(e.path,e.groupId)&&(this._activePinnedPage.set(e),w=!0)}catch{}}!w&&C&&this.effectiveDefaultPage&&this.isPageAllowed(this.effectiveDefaultPage.path,this.effectiveDefaultPage.groupId)&&(this._activePinnedPage.set(this.effectiveDefaultPage),w=!0),this.orchestrator&&(this._useProxy.set(this.orchestrator.useProxy),this._proxyUrl.set(this.orchestrator.proxyUrl),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess));let[ee,te,T]=await Promise.all([m(e,l.SIDEBAR_CHAT_HIDDEN),m(e,l.SIDEBAR_TASKS_HIDDEN),m(e,l.SIDEBAR_FILES_HIDDEN)]),E=Z(),ne=E?.sidebar?.chatHidden,re=E?.sidebar?.tasksHidden,D=E?.sidebar?.filesHidden,ie=ee==null?!!ne:oe(ee),ae=te==null?!!re:oe(te),O=T==null?!!D:oe(T),se=()=>{let t=[];(!ie||this.activePage===`chat`)&&t.push(this.loadHistory()),(!ae||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),Promise.all(t).catch(e=>{console.warn(`Secondary background store loads failed:`,e)})};if(d)typeof window.requestIdleCallback==`function`?window.requestIdleCallback(se,{timeout:2e3}):setTimeout(se,100);else{let t=[];(!ie||this.activePage===`chat`)&&t.push(this.loadHistory()),(!ae||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),await Promise.all(t)}await k(),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await C(e));let r=await at(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await M(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await Re(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await v(e),r=n.filter(e=>e.groupId===t);r.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(r);let i=await this.getSubscriberId(e),a=await Xt(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1);if(!a)return;let o=new Set(n.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));if(s.length===0)return;for(let t of s)await P(e,t);let c=[...r,...s];c.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(c)}async navigateBackFolder(e){let t=this._currentPath.get();if(t===`.`)return;let n=t.split(`/`).filter(Boolean);n.pop();let r=n.length===0?`.`:n.join(`/`);await this.setCurrentPath(e,r)}async navigateIntoFolder(e,t){let n=this._currentPath.get(),r=n===`.`?t.replace(/\/$/,``):`${n}/${t.replace(/\/$/,``)}`;try{await this.setCurrentPath(e,r)}catch(t){console.error(`Failed to navigate into folder in store:`,t),O(`Folder not found: ${r}`,4500),await this.loadFiles(e)}}async newSession(e){await this.orchestrator?.newSession?.(e,this._activeGroupId.get()),await this.loadHistory()}async removePage(t,n,r=this._activeGroupId.get()){let i=this.normalizePagePath(n);if(!i)return;let a=this._pages.get();if(!a.some(e=>e.path===i&&e.groupId===r))return;let o=a.filter(e=>e.path!==i||e.groupId!==r);await ft(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await z(t,!0);let l=s||await R(t);if(o.length===0&&!l){if(await B(t,`br:main`))o.push({groupId:c,path:e.DEFAULT_PAGE_PATH});else return}this.setPages(o);let u=this._defaultPinnedPage.get();u&&u.path===i&&u.groupId===r&&await this.setDefaultPinnedPage(t,null),await this.persistPages(t)}async removeAllPages(e){let t=[...this._pages.get()];for(let n of t)await ft(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await z(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await He(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await Ge(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await Ze(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await Q(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync reordered task "${t.id}" to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}async replayTaskSyncOutbox(e){if(!(this._replayingTaskSyncOutbox||this._taskSyncOutbox.length===0)){this._replayingTaskSyncOutbox=!0;try{let t=await this.getSubscriberId(e),n=[];for(let e of this._taskSyncOutbox){let r=this.getTaskServerBaseUrl();(e.type===`upsert`?await Q(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await $(e.id,r,t,this.orchestrator?.taskServerEnabled??!1))||n.push(e)}this._taskSyncOutbox=this.compactTaskSyncOutbox(n),await this.persistTaskSyncOutbox(e)}finally{this._replayingTaskSyncOutbox=!1}}}async resetToRootFolder(e){await this.setCurrentPath(e,`.`)}async restartCurrentRequest(){return this.orchestrator?.restartCurrentRequest?this.orchestrator.restartCurrentRequest(this._activeGroupId.get()):!1}async restoreTasksFromBackup(e,t){await this.clearAllTasks(e);let n=this._activeGroupId.get();for(let r of t){let t={...r,groupId:n,id:crypto.randomUUID?crypto.randomUUID():`task-${Date.now()}-${Math.random()}`};await this.upsertTask(e,t,{reloadTasks:!1})}await this.loadTasks(e)}async runTask(e,t=!1){let n=this._db;if(t&&n&&(await Xe(e.id,Date.now()),await this.loadTasks(n)),e.type===`tools`&&Array.isArray(e.tools)&&e.tools.length>0){if(this.orchestrator?.agentWorker){let n=e.subagent?`subagent:${_()}`:e.groupId;this.orchestrator.agentWorker.postMessage({type:`execute-task-tools`,payload:{groupId:n,tools:e.tools,isManual:t}})}else console.error(`Agent worker not available to execute tool task.`)}else{if(!e.groupId){console.error(`Task ${e.id} has no groupId - refusing to execute in active conversation to prevent context pollution.`);return}this.orchestrator?.browserChat?.submit(e.prompt,e.groupId,[],void 0,e.freshContext,e.subagent)}}async setActivePage(e,t){this._activePage.set(t),await g(e,l.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await g(e,l.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){t&&!this.isPageAllowed(t.path,t.groupId)&&(t=this.effectiveDefaultPage),this._activePinnedPage.set(t),t?await g(e,l.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await g(e,l.LAST_SELECTED_PINNED_PAGE,null)}async setDefaultPinnedPage(e,t){if(t&&!this.isPageAllowed(t.path,t.groupId))return;let n=this._defaultPinnedPage.get(),r=n&&t&&n.path===t.path&&n.groupId===t.groupId?null:t;this._defaultPinnedPage.set(r),r?await g(e,l.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await g(e,l.DEFAULT_PINNED_PAGE,null)}async reorderPages(e,t){this.setPages(t),await this.persistPages(e)}async setCurrentPath(e,t){let n=t.replace(/^\/+|\/+$/g,``)||`.`,r=this._activeGroupId.get();this._storageStatus.set(await C(e));let i=await at(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await be(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await Ce(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await Ae(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await je(this.orchestrator,e,t),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess))}async switchConversation(e,t,n){this.setActiveGroup(e,t,n??this._activePage.get()===`chat`),await g(e,l.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await P(e,r),await this.loadTasks(e),await Q(r,this.getTaskServerBaseUrl(),await this.getSubscriberId(e),this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to update task on server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:r.id,task:r,queuedAt:Date.now()}))}async updateConversationPinnedProvider(e,t,n,r,i){await qe(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await Ye(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await Je(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await Ue(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await P(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await Q(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync task to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}compactTaskSyncOutbox(e){let t=/* @__PURE__ */ new Map;return e.forEach((e,n)=>{t.set(e.id,n)}),e.filter((e,n)=>t.get(e.id)===n)}deriveGroupName(e){return e.startsWith(`tg:`)?`Telegram ${e.slice(3)}`:e.startsWith(`im:`)?`iMessage ${e.slice(3)}`:e.startsWith(`br:`)?e===`br:main`?`Main`:`Browser Conversation`:`Conversation`}getActivityLogSessionStartedAt(e){let t=this._activityLogSessionStartedAtByGroup.get(e);if(t)return t;let n=(/* @__PURE__ */ new Date()).toISOString();return this._activityLogSessionStartedAtByGroup.set(e,n),n}getTaskServerBaseUrl(){return this.orchestrator?.taskServerUrl??`/schedule`}async getSubscriberId(e){if(this._subscriberId)return this._subscriberId;let t=await S(e);return this._subscriberId=t,t}normalizePagePath(t){let n=t.trim().replace(/^\/+/,``).replace(/\/+/g,`/`);return n===`main/memory.md`?e.DEFAULT_PAGE_PATH:n}normalizeSidebarDefaultPage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`}parsePagesList(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{groupId:c,path:this.normalizePagePath(e)};if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.path!=`string`)return null;let n=typeof t.groupId==`string`&&t.groupId.trim().length>0?t.groupId:c,r=n===`br:main`?this.normalizePagePath(t.path):t.path.trim();return r?{groupId:n,path:r}:null}).filter(e=>!!e).filter((e,t,n)=>{let r=`${e.groupId}\u0000${e.path}`;return t===n.findIndex(e=>`${e.groupId}\u0000${e.path}`===r)}):[]}catch{return[]}}parseTaskSyncOutbox(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>!!e&&typeof e==`object`).filter(e=>e.type===`upsert`||e.type===`delete`).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({...e,queuedAt:typeof e.queuedAt==`number`?e.queuedAt:Date.now()}));return this.compactTaskSyncOutbox(n)}catch{return[]}}resolveSidebarDefaultPageForActivePage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:this._sidebarDefaultPage.get()}setPages(e){let t=e.filter(e=>this.isPageAllowed(e.path,e.groupId)),n=t.filter(e=>e.path.toLowerCase()===`memory.md`),r=t.filter(e=>e.path.toLowerCase()!==`memory.md`);this._pages.set([...r,...n])}async ensureDefaultPage(t){if(await R(t))return;let n=await B(t,c);await I(t,c),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:c,path:e.DEFAULT_PAGE_PATH}]),await this.persistPages(t))}async ensureGroupExists(e,t,n){let r=this._groups.get();if(r.some(e=>e.groupId===t))return;let i=[...r,{groupId:t,name:this.deriveGroupName(t),createdAt:n||Date.now()}];this._groups.set(i);try{await j(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!Jt(await m(this._db,l.ACTIVITY_LOG_DISK_LOGGING_ENABLED)))return;let t=typeof e.groupId==`string`&&e.groupId?e.groupId:this._activeGroupId.get();if(!t)return;let n=typeof e.message==`string`?e.message.trim():``;if(!n)return;e.level===`info`&&e.label===`Starting`&&this._activityLogSessionStartedAtByGroup.set(t,(/* @__PURE__ */ new Date()).toISOString());let r=this.getActivityLogSessionStartedAt(t);try{await fetch(`/activity-log`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({groupId:t,level:e.level,label:e.label,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString(),sessionStartedAt:r})})}catch(e){console.warn(`Failed to persist activity log entry to server:`,e)}}scheduleBackgroundStaticMainSiteSeeding(e){if(typeof window>`u`)return;let t=async()=>{try{if(await Ct(e,`br:main`))return;let t=await m(e,l.PAGES_LIST),n=t==null?[]:this.parsePagesList(t),r=await zt(e,c,n,{preferEmbedded:!1});r&&r.length>0&&(this.setPages(r),await this.persistPages(e))}catch(e){console.warn(`Background static main site seeding failed:`,e)}};typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:3e3}):setTimeout(()=>void t(),100)}async persistPages(e){await g(e,l.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await g(e,l.TASK_SYNC_OUTBOX,JSON.stringify(this._taskSyncOutbox))}async queueTaskSyncOutboxOperation(e,t){this._taskSyncOutbox=this.compactTaskSyncOutbox([...this._taskSyncOutbox,t]),await this.persistTaskSyncOutbox(e)}async applySiteConfigDefaults(e){if(typeof document<`u`)try{let r=Z();if(!r||typeof r!=`object`)return;i(r),t(),n();let a=r.customElements;if((await M(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await Ue(e,c,void 0),(r.settings?.internetAccess??r.settings?.vm_bash_full_internet_access??r.settings?.fullInternetAccess??r.internetAccess)===!0&&await m(e,l.VM_BASH_FULL_INTERNET_ACCESS)!==`true`&&(await g(e,l.VM_BASH_FULL_INTERNET_ACCESS,`true`),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=!0),this._vmBashFullInternetAccess.set(!0)),r.pages&&typeof r.pages==`object`){let{defaultPinnedPage:t}=r.pages;if(t&&typeof t==`string`){let n=o(t);n&&this.isPageAllowed(n.path,n.groupId)&&(this._defaultPinnedPage.set(n),await g(e,l.DEFAULT_PINNED_PAGE,JSON.stringify(n)))}}let s=r.allowedCustomElements||(typeof a==`object`&&!Array.isArray(a)?a.allowedElements:void 0);s!==void 0&&(await m(e,l.ALLOWED_CUSTOM_ELEMENTS)??await g(e,l.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(s)));let u=r.allowedCustomElementDomains||(typeof a==`object`&&!Array.isArray(a)?a.allowedDomains:void 0);if(u!==void 0&&(await m(e,l.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS)??await g(e,l.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(u))),r.sidebar&&typeof r.sidebar==`object`){let{pagesHidden:t,chatHidden:n,tasksHidden:i,filesHidden:a,defaultPage:o}=r.sidebar;if(t!==void 0&&(await m(e,l.SIDEBAR_PAGES_HIDDEN)??await g(e,l.SIDEBAR_PAGES_HIDDEN,String(!!t))),n!==void 0&&(await m(e,l.SIDEBAR_CHAT_HIDDEN)??await g(e,l.SIDEBAR_CHAT_HIDDEN,String(!!n))),i!==void 0&&(await m(e,l.SIDEBAR_TASKS_HIDDEN)??await g(e,l.SIDEBAR_TASKS_HIDDEN,String(!!i))),a!==void 0&&(await m(e,l.SIDEBAR_FILES_HIDDEN)??await g(e,l.SIDEBAR_FILES_HIDDEN,String(!!a))),o&&typeof o==`string`){let t=this.normalizeSidebarDefaultPage(o);this._sidebarDefaultPage.set(t),await m(e,l.SIDEBAR_DEFAULT_PAGE)||await g(e,l.SIDEBAR_DEFAULT_PAGE,o)}}if(r.settings&&typeof r.settings==`object`){let{assistantName:t,defaultProvider:n,provider:i,defaultModel:a,model:o}=r.settings;t&&typeof t==`string`&&(await m(e,l.ASSISTANT_NAME)||await g(e,l.ASSISTANT_NAME,t));let s=n??i;if(typeof s==`string`&&s.trim().length>0&&!await m(e,l.PROVIDER)){let t=s.trim();await g(e,l.PROVIDER,t),this.orchestrator&&(this.orchestrator.provider=t)}let c=a??o;if(typeof c==`string`&&c.trim().length>0&&!await m(e,l.MODEL)){let t=c.trim();await g(e,l.MODEL,t),this.orchestrator&&(this.orchestrator.model=t)}let u=r.settings.internetAccess??r.settings.vm_bash_full_internet_access??r.settings.fullInternetAccess??r.internetAccess;typeof u==`boolean`&&(await m(e,l.VM_BASH_FULL_INTERNET_ACCESS)??(await g(e,l.VM_BASH_FULL_INTERNET_ACCESS,String(u)),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=u),this._vmBashFullInternetAccess.set(u)))}let d=(r.settings&&typeof r.settings==`object`?r.settings.defaultToolsProfile:void 0)??r.defaultToolsProfile;if(typeof d==`string`&&d.trim().length>0&&!await m(e,l.ACTIVE_TOOL_PROFILE)){let t=d.trim();if(t.toLowerCase()===`none`)await x.deactivateProfile(e);else{let n=x.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await x.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(r.pages&&typeof r.pages==`object`){let{defaultPinnedPage:t}=r.pages;t&&typeof t==`string`&&(await m(e,l.DEFAULT_PINNED_PAGE)||await g(e,l.DEFAULT_PINNED_PAGE,t))}let f=r.pages?.allowList??r.pages?.allowlist??r.allowList??r.allowlist,p=r.pages?.denyList??r.pages?.denylist??r.denyList??r.denylist;if(Array.isArray(f)&&await m(e,l.PAGES_ALLOW_LIST)==null){let t=K(f.map(String));this._pagesAllowList.set(t),await g(e,l.PAGES_ALLOW_LIST,JSON.stringify(t))}if(Array.isArray(p)&&await m(e,l.PAGES_DENY_LIST)==null){let t=K(p.map(String));this._pagesDenyList.set(t),await g(e,l.PAGES_DENY_LIST,JSON.stringify(t))}await g(e,l.SITE_CONFIG_SEEDED,`true`);let h=this._pages.get(),_=h.filter(e=>this.isPageAllowed(e.path,e.groupId));_.length!==h.length&&(this.setPages(_),await this.persistPages(e));let v=this._activePinnedPage.get();v&&!this.isPageAllowed(v.path,v.groupId)&&await this.setActivePinnedPage(e,this.effectiveDefaultPage);let y=this._defaultPinnedPage.get();if(y&&!this.isPageAllowed(y.path,y.groupId)&&await this.setDefaultPinnedPage(e,null),Array.isArray(r.enabledTools)){let t=r.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await x.setAllEnabled(e,t),await x.setAllDeclarativeEnabled(e,t)}await g(e,l.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const $t=new Qt;export{ye as A,Ae as B,N as C,Re as D,M as E,Te as F,le as G,ve as H,Ee as I,he as J,de as K,De as L,Se as M,Ce as N,Le as O,we as P,k as Q,Oe as R,P as S,A as T,me as U,Me as V,ue as W,se as X,_e as Y,ce as Z,B as _,Pt as a,nt as b,K as c,U as d,ct as f,at as g,H as h,Gt as i,xe as j,Ne as k,ft as l,lt as m,Kt as n,Ft as o,V as p,ge as q,Z as r,jt as s,$t as t,W as u,z as v,Ve as w,Xe as x,I as y,ke as z};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./config-C-YdSFZB.js";import{n as e}from"./db-BUuJo1Gf.js";import{t}from"./dist-CeFyqf9k.js";import{t as n}from"./ulid-BSJxYh6W.js";import{o as r}from"./tools-DHA1dK2I.js";import{a as i}from"./transformers-C-DuTM2K.js";import{i as a}from"./mime-ClqNyXPc.js";import{t as o}from"./upload-group-file-Cejr3zo1.js";import{n as s}from"./filename-kBumOBho.js";import{t as c}from"./write-group-file-bytes-Cejr3zo1.js";function l(e){return s(e,{replacement:`-`,fallback:`attachment`,stripLeadingDots:!0,collapseReplacement:!0,stripControlChars:!0})}function u(e){return e.previewDisposition===`inline`||a(e.fileName,e.mimeType||``)===`image/png`}function d(e,t=``,n=Date.now()){let r=l(e),i=t.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``);return`attachments/${n}-${i?`${i}-`:``}${r}`}async function f(e,t,n=[]){let r=[];for(let i of n){let n=l(i.fileName||``),s=i.path||d(n,i.id),c=i.source,u=a(n,i.mimeType||``),f=i.size;if(c){let r=await p(c);u=a(n,i.mimeType||r.type),f=typeof f==`number`?f:r.size,await o(e,t,s,r)}r.push(m({...i,fileName:n,mimeType:u,size:f,path:s,previewDisposition:i.previewDisposition||(u===`image/png`?`inline`:`file`)}))}return r}async function p(e){if(e.kind===`local-file`)return e.file;if(e.kind===`inline-text`)return new Blob([e.text],{type:e.mimeType||`text/plain`});let t=await fetch(e.url,{headers:e.headers});if(!t.ok)throw Error(`Attachment download failed: HTTP ${t.status} ${t.statusText}`);return await t.blob()}function m(e){let{source:t,...n}=e;return n}const h=/* @__PURE__ */ new Set([`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_REJECTED`]),g=/* @__PURE__ */ new Set([`TASK_STATE_INPUT_REQUIRED`,`TASK_STATE_AUTH_REQUIRED`]),_={SEND_MESSAGE:`SendMessage`,SEND_STREAMING_MESSAGE:`SendStreamingMessage`,GET_TASK:`GetTask`,CANCEL_TASK:`CancelTask`,GET_AGENT_CARD:`GetAgentCard`},v={EVENT:`agui/event`},y={STATUS_UPDATE:`tasks/statusUpdate`,ARTIFACT_UPDATE:`tasks/artifactUpdate`},b={JOIN:`room/join`,ROSTER:`room/roster`,LEAVE:`room/leave`,MESSAGE:`room/message`,INVITE:`room/invite`,RELAY:`room/relay`,A2UI:`room/a2ui`,A2UI_ACTION:`room/a2ui-action`},x={TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603};function S(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`&&(e.id===null||typeof e.id==`string`||typeof e.id==`number`)&&typeof e.method==`string`}function C(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`&&(e.id===null||typeof e.id==`string`||typeof e.id==`number`)&&!(`method`in e)}function w(e){let t={url:`webrtc://${e.peerId}`,protocolBinding:`https://xt-ml.github.io/shadow-claw/bindings/webrtc-datachannel/v1`,protocolVersion:`1.0`},n={streaming:e.streaming??!0,pushNotifications:!1};return{name:e.name,description:e.description??`AI assistant agent (${e.name})`,version:e.version??`1.0.0`,supportedInterfaces:[t],capabilities:n,defaultInputModes:[`text/plain`,`application/json`],defaultOutputModes:[`text/plain`,`application/json`],skills:e.skills??[],iconUrl:e.iconUrl}}function T(){return{jsonrpc:`2.0`,id:n(),method:_.GET_AGENT_CARD}}function E(e,t){return{jsonrpc:`2.0`,id:e,result:t}}function D(e){if(e.error)return console.warn(`GetAgentCard returned error:`,e.error),null;let t=e.result;return!t||typeof t!=`object`||typeof t.name!=`string`||typeof t.version!=`string`?null:t}var O=class{_cards=/* @__PURE__ */ new Map;clear(){this._cards.clear()}delete(e){this._cards.delete(e)}entries(){return this._cards.entries()}get(e){return this._cards.get(e)}getDisplayName(e){return this._cards.get(e)?.name??e}has(e){return this._cards.has(e)}set(e,t){this._cards.set(e,t)}supportsStreaming(e){return this._cards.get(e)?.capabilities?.streaming??!1}};const k={maxTasks:100,maxHistoryPerTask:50},A=/* @__PURE__ */ new Map([[`TASK_STATE_SUBMITTED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_REJECTED`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])],[`TASK_STATE_WORKING`,/* @__PURE__ */ new Set([`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_INPUT_REQUIRED`,`TASK_STATE_AUTH_REQUIRED`])],[`TASK_STATE_INPUT_REQUIRED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])],[`TASK_STATE_AUTH_REQUIRED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])]]);var j=class{_config;_contextActiveTask=/* @__PURE__ */ new Map;_listeners=/* @__PURE__ */ new Set;_taskOrder=[];_tasks=/* @__PURE__ */ new Map;constructor(e){this._config={...k,...e}}addArtifact(e,t,n=!1){let r=this._tasks.get(e);if(!r)return;if(r.artifacts||=[],n){let e=r.artifacts.find(e=>e.artifactId===t.artifactId);e?e.parts.push(...t.parts):r.artifacts.push(t)}else r.artifacts.push(t);let i={taskId:r.id,contextId:r.contextId??``,artifact:t,append:n,lastChunk:!1};this._emit({type:`artifactUpdate`,taskId:r.id,contextId:r.contextId??``,payload:i})}cancelTask(e){let t=this._tasks.get(e);return!t||h.has(t.status.state)?!1:(this._transitionState(t,`TASK_STATE_CANCELED`,{messageId:n(),role:`ROLE_AGENT`,parts:[{text:`Task canceled by peer request.`}]}),!0)}clear(){this._tasks.clear(),this._taskOrder=[],this._contextActiveTask.clear()}emitRunError(e,t,n){let r=this._tasks.get(e);if(!r)return;let i={type:`RUN_ERROR`,message:t,code:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitRunFinished(e){let t=this._tasks.get(e);if(!t)return;let n={type:`RUN_FINISHED`,threadId:t.contextId??t.id,runId:t.id,timestamp:Date.now()};this._emitAGUI(t,n)}emitRunStarted(e){let t=this._tasks.get(e);if(!t)return;let n={type:`RUN_STARTED`,threadId:t.contextId??t.id,runId:t.id,timestamp:Date.now()};this._emitAGUI(t,n)}emitStateSnapshot(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`STATE_SNAPSHOT`,snapshot:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitTextMessageContent(e,t,n){let r=this._tasks.get(e);if(!r)return;let i={type:`TEXT_MESSAGE_CONTENT`,messageId:t,delta:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitTextMessageEnd(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`TEXT_MESSAGE_END`,messageId:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitTextMessageStart(e,t,n=`assistant`){let r=this._tasks.get(e);if(!r)return;let i={type:`TEXT_MESSAGE_START`,messageId:t,role:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitToolCallEnd(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitToolCallStart(e,t,n,r){let i=this._tasks.get(e);if(!i)return;let a={type:`TOOL_CALL_START`,toolCallId:t,toolCallName:n,parentMessageId:r,timestamp:Date.now()};this._emitAGUI(i,a)}getActiveTaskForContext(e){let t=this._contextActiveTask.get(e);if(t)return this._tasks.get(t)}getActiveTasks(){return Array.from(this._tasks.values()).filter(e=>!h.has(e.status.state))}getAllTasks(){return Array.from(this._tasks.values())}getTask(e){return this._tasks.get(e)}handleSendMessage(e){let t=e.message,r=t.contextId??n(),i=t.taskId??this._contextActiveTask.get(r);return i&&this._tasks.has(i)?this._continueTask(i,t):this._createTask(r,t)}markCompleted(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_COMPLETED`,t)}markFailed(e,t){let r=this._tasks.get(e);r&&this._transitionState(r,`TASK_STATE_FAILED`,{messageId:n(),role:`ROLE_AGENT`,parts:[{text:t}]})}markInputRequired(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_INPUT_REQUIRED`,t)}markWorking(e){let t=this._tasks.get(e);t&&this._transitionState(t,`TASK_STATE_WORKING`)}off(e){this._listeners.delete(e)}on(e){this._listeners.add(e)}_addTask(e){for(this._tasks.set(e.id,e),this._taskOrder.push(e.id);this._taskOrder.length>this._config.maxTasks;){let e=this._taskOrder.shift(),t=this._tasks.get(e);if(t&&h.has(t.status.state))this._tasks.delete(e),t.contextId&&this._contextActiveTask.delete(t.contextId);else{this._taskOrder.unshift(e);break}}}_continueTask(e,t){let n=this._tasks.get(e);return g.has(n.status.state)&&this._transitionState(n,`TASK_STATE_WORKING`),n.history||=[],n.history.push(t),n.history.length>this._config.maxHistoryPerTask&&(n.history=n.history.slice(-this._config.maxHistoryPerTask)),this._touchTask(e),{task:n}}_createTask(e,t){let r=n(),i={id:r,contextId:e,status:{state:`TASK_STATE_SUBMITTED`,timestamp:(/* @__PURE__ */ new Date()).toISOString()},history:[t]};return this._addTask(i),this._contextActiveTask.set(e,r),this._emitStatusUpdate(i),{task:i}}_emit(e){for(let t of this._listeners)try{t(e)}catch(e){console.error(`PeerTaskManager: listener error`,e)}}_emitAGUI(e,t){this._emit({type:`aguiEvent`,taskId:e.id,contextId:e.contextId??``,payload:t})}_emitStatusUpdate(e){let t={taskId:e.id,contextId:e.contextId??``,status:e.status};this._emit({type:`statusUpdate`,taskId:e.id,contextId:e.contextId??``,payload:t})}_touchTask(e){let t=this._taskOrder.indexOf(e);t!==-1&&(this._taskOrder.splice(t,1),this._taskOrder.push(e))}_transitionState(e,t,n){let r=e.status.state,i=A.get(r);i&&!i.has(t)?console.warn(`PeerTaskManager: invalid transition ${r} → ${t} for task ${e.id}`):h.has(r)?console.warn(`PeerTaskManager: task ${e.id} is in terminal state ${r}, cannot transition`):(e.status={state:t,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString()},h.has(t)&&e.contextId&&this._contextActiveTask.get(e.contextId)===e.id&&this._contextActiveTask.delete(e.contextId),this._emitStatusUpdate(e))}};const M=new t.State(null);let N=null;function P(e){N!==null&&(clearTimeout(N),N=null),M.set(e)}function F(e=1500){N!==null&&clearTimeout(N),N=setTimeout(()=>{M.set(null),N=null},e)}const I=15360;var L=class a{static _RECONNECT_BASE_MS=1e3;static _RECONNECT_MAX_MS=6e4;connectedPeersSignal=new t.State([]);connections=/* @__PURE__ */ new Map;messageCallback=null;myPeerId=``;peerCards=new O;running=!1;serverConfig={};transferProgressSignal=M;trustedPeerIds=/* @__PURE__ */ new Set;type=`peerjs`;typingCallback=null;_inboundRemap=/* @__PURE__ */ new Map;_localCard=null;_onTaskCompleteCallback=null;peer=null;_inboundSavePromises=/* @__PURE__ */ new Map;_pendingInboundFile=null;_pendingRequests=/* @__PURE__ */ new Map;_reconnectAttempts=0;_reconnectTimer=null;_roomNotificationHandler=null;_taskManagers=/* @__PURE__ */ new Map;_inboundTransfers=/* @__PURE__ */ new Map;constructor(){typeof globalThis.addEventListener==`function`&&globalThis.addEventListener(`peerjs-dc-handle-chunk`,e=>{if(e?.detail?.chunkInfo){if(this._inboundTransfers.size>0)return;let{count:t,total:n}=e.detail.chunkInfo,r=t+1;P({count:r,total:n,direction:`receive`}),r>=n&&F(1500)}})}completeActiveTask(e){let t=e.replace(/^peer:/,``),n=this._taskManagers.get(t);if(!n)return!1;let r=n.getActiveTasks();if(r.length===0)return!1;let i=r[r.length-1];return n.markWorking(i.id),n.markCompleted(i.id),!0}configure(e,t,n={}){this.myPeerId=e.trim(),this.trustedPeerIds=new Set(t.map(e=>e.trim()).filter(Boolean)),this.serverConfig=n}connectPeer(e){this._getOrOpenConnection(e)}getTaskManager(e){let t=this._taskManagers.get(e);return t||(t=new j,this._taskManagers.set(e,t),t.on(t=>{this._forwardTaskEvent(e,t)})),t}isConfigured(){return this.myPeerId.length>0}isPeerConnected(e){let t=this.connections.get(e);return!!t&&!!t.open}onMessage(e){this.messageCallback=e}onTaskComplete(e){this._onTaskCompleteCallback=e}onTyping(e){this.typingCallback=e}sendRoomNotification(e,t){let n=this._getOrOpenConnection(e);if(!n)return!1;if(n.open)try{return n.send(t),!0}catch(t){return console.error(`PeerJsChannel: failed to send room notification to ${e}:`,t),!1}return this._waitForOpen(n).then(()=>{try{n.send(t)}catch(t){console.error(`PeerJsChannel: failed to flush room notification to ${e}:`,t)}}).catch(()=>{}),!0}setRoomNotificationHandler(e){this._roomNotificationHandler=e}async sendAttachmentsToRoom(t,r,a){let o=this.myPeerId,s=(a||[]).filter(e=>!!e.path);if(s.length!==0)try{let a=await e();for(let e of s){let s;try{s=await i(a,r,e.path)}catch(t){console.warn(`PeerJsChannel: failed to read file ${e.path} for room:`,t);continue}let c=e.path,l=e.mimeType||`application/octet-stream`,u=Math.max(1,Math.ceil(s.length/I));for(let i of t.members){if(i.peerId===o)continue;let t=this._getOrOpenConnection(i.peerId);if(t)try{await this._waitForOpen(t);let e=n();t.send({type:`__file_header`,id:e,name:c,mimeType:l,size:s.length,totalChunks:u,chunkSize:I,groupId:r});for(let n=0;n<u;n++){let r=n*I,i=Math.min(r+I,s.length),a=s.subarray(r,i),o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);t.send({type:`__file_chunk`,id:e,name:c,index:n,totalChunks:u,data:o}),P({count:n+1,total:u,direction:`send`}),await this._waitForBufferDrain(t)}F(1500)}catch(t){console.warn(`PeerJsChannel: failed to stream file ${e.path} to room member ${i.peerId}:`,t)}}}}catch(e){console.error(`PeerJsChannel: failed to access DB for room file transfer`,e)}}setTyping(e,t){let n=e.replace(/^peer:/,``),r=this.connections.get(n);if(r)try{r.send({type:`typing`,typing:t})}catch{}}start(){this.isConfigured()&&!this.running&&(this.running=!0,this._localCard=w({peerId:this.myPeerId,name:this.myPeerId,description:`ShadowClaw AI assistant`,streaming:!0}),this._initPeer())}ensureConnected(e=!1){if(!this.running||!this.isConfigured())return;this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0;let t=this.peer;if(!t||t.destroyed||e&&!t.open){if(t&&!t.destroyed)try{t.destroy()}catch{}this.peer=null,this._initPeer()}else if(t.disconnected)try{t.reconnect?.()}catch{this._initPeer()}}stop(){if(this.running=!1,this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this.connections.forEach(e=>{try{e.close()}catch{}}),this.connections.clear(),this.peerCards.clear(),this._taskManagers.clear(),this._pendingRequests.forEach(({timer:e})=>clearTimeout(e)),this._pendingRequests.clear(),this._updateConnectedPeersSignal(),this.peer){try{this.peer.destroy()}catch{}this.peer=null}}async send(t,r,a){let o=t.replace(/^peer:/,``),s=this._getOrOpenConnection(o);if(!s)console.warn(`PeerJsChannel: no connection available for ${o}`);else try{await this._waitForOpen(s);let{attachments:o}=R(r),c=[...(a||[]).filter(e=>!!e.path),...o.map(e=>({path:e.path,mimeType:`application/octet-stream`}))],l=/* @__PURE__ */ new Map,u=[];try{let r=await e();for(let e of c)if(e.path)try{let a=await i(r,t,e.path),o=e.path;l.has(e.path)||l.set(e.path,o);let c=e.mimeType||`application/octet-stream`,d=n(),f=Math.max(1,Math.ceil(a.length/I));s.send({type:`__file_header`,id:d,name:o,mimeType:c,size:a.length,totalChunks:f,chunkSize:I,groupId:t});for(let e=0;e<f;e++){let t=e*I,n=Math.min(t+I,a.length),r=a.subarray(t,n),i=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);s.send({type:`__file_chunk`,id:d,name:o,index:e,totalChunks:f,data:i}),P({count:e+1,total:f,direction:`send`}),await this._waitForBufferDrain(s)}F(1500),u.push({kind:`file`,name:o,mimeType:c,size:a.length})}catch(t){console.warn(`PeerJsChannel: failed to process file ${e.path}:`,t)}}catch(e){console.error(`PeerJsChannel: failed to access DB`,e)}let d=r;for(let[e,t]of l){let n=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);d=d.replace(RegExp(`(!?\\[.*?\\])\\(${n}\\)`,`g`),`$1(${t})`)}let f=[...u,{kind:`text`,text:d}],p=n(),m={jsonrpc:`2.0`,id:p,method:_.SEND_MESSAGE,params:{message:{messageId:n(),role:`ROLE_AGENT`,parts:f}}};s.send(m),this._registerPendingRequest(p,e=>{})}catch(e){console.error(`PeerJsChannel: send failed for ${o}:`,e),window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{remotePeerId:o,error:e instanceof Error?e.message:String(e)}}))}}async sendA2UI(e,t){let r=e.replace(/^peer:/,``),i=this._getOrOpenConnection(r);if(!i)console.warn(`PeerJsChannel.sendA2UI: no connection available for ${r}`);else try{await this._waitForOpen(i);let e={jsonrpc:`2.0`,method:`message/send`,id:n(),params:{message:{role:`agent`,parts:[{kind:`a2ui`,envelope:t}]}}};i.send(e)}catch(e){console.error(`PeerJsChannel.sendA2UI: failed for ${r}:`,e)}}async sendA2UIAction(e,t){let r=e.replace(/^peer:/,``),i=this._getOrOpenConnection(r);if(!i)console.warn(`PeerJsChannel.sendA2UIAction: no connection available for ${r}`);else try{await this._waitForOpen(i);let e={jsonrpc:`2.0`,method:`message/send`,id:n(),params:{message:{role:`user`,parts:[{kind:`a2ui-action`,action:t}]}}};i.send(e)}catch(e){console.error(`PeerJsChannel.sendA2UIAction: failed for ${r}:`,e)}}_exchangeAgentCards(e,t){if(!this._localCard)return;let n=T();t.send(n),this._registerPendingRequest(n.id,t=>{let n=D(t);n&&(this.peerCards.set(e,n),console.log(`PeerJsChannel: received AgentCard from ${e}: "${n.name}"`))})}_forwardTaskEvent(e,t){let n=this.connections.get(e);if(!n)return;let r;switch(t.type){case`statusUpdate`:r=y.STATUS_UPDATE;break;case`artifactUpdate`:r=y.ARTIFACT_UPDATE;break;case`aguiEvent`:r=v.EVENT;break;default:return}let i={jsonrpc:`2.0`,method:r,params:t.payload};try{n.send(i)}catch(n){console.error(`PeerJsChannel: failed to forward ${t.type} to ${e}:`,n)}}_getOrOpenConnection(e){let t=this.connections.get(e);if(t)return t;if(!this.peer)return null;try{let t=this.peer.connect(e,{reliable:!0,serialization:`binary`});return t?(this._handleIncomingConnection(t),t):null}catch(t){return console.error(`PeerJsChannel: failed to connect to ${e}:`,t),null}}_handleA2ACancelTask(e,t){let n=t.params;if(!n?.taskId){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing taskId in CancelTask params`});return}let r=this._taskManagers.get(e);if(!r){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_FOUND,message:`Task not found: ${n.taskId}`});return}if(!r.cancelTask(n.taskId)){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_CANCELABLE,message:`Task not cancelable: ${n.taskId}`});return}let i=this.connections.get(e);if(i){let e=r.getTask(n.taskId),a={jsonrpc:`2.0`,id:t.id,result:{task:e}};i.send(a)}}_handleA2AGetTask(e,t){let n=t.params;if(!n?.taskId){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing taskId in GetTask params`});return}let r=this._taskManagers.get(e)?.getTask(n.taskId);if(!r){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_FOUND,message:`Task not found: ${n.taskId}`});return}let i=this.connections.get(e);if(i){let e={jsonrpc:`2.0`,id:t.id,result:{task:r}};i.send(e)}}_handleA2AJsonRpc(e,t){if(C(t)){let e=String(t.id??``),n=this._pendingRequests.get(e);n&&(clearTimeout(n.timer),this._pendingRequests.delete(e),n.resolve(t));return}let n=t.method;if(n){if(n.startsWith(`room/`))this._roomNotificationHandler?.(e,n,t.params);else if(S(t)){let r={[_.GET_AGENT_CARD]:(e,t)=>this._handleGetAgentCard(e,t),[_.SEND_MESSAGE]:(e,t)=>this._handleA2ASendMessage(e,t),[_.CANCEL_TASK]:(e,t)=>this._handleA2ACancelTask(e,t),[_.GET_TASK]:(e,t)=>this._handleA2AGetTask(e,t)}[n];if(r){r(e,t);return}if(n===`message/send`){let n=t.params;n?.message?.parts&&Array.isArray(n.message.parts)&&this._processInboundA2AEnvelope(e,n.message.parts).catch(e=>console.error(`PeerJsChannel: failed to process inbound A2A envelope`,e))}else this._sendJsonRpcError(e,t.id,{code:x.METHOD_NOT_FOUND,message:`Method not found: ${n}`})}else({[v.EVENT]:(e,t)=>this._handleAGUIEventNotification(e,t),[y.STATUS_UPDATE]:(e,t)=>this._handleTaskStatusNotification(e,t),[y.ARTIFACT_UPDATE]:()=>{},"message/send":(e,t)=>{t?.message?.parts&&Array.isArray(t.message.parts)&&this._processInboundA2AEnvelope(e,t.message.parts).catch(e=>console.error(`PeerJsChannel: failed to process inbound A2A envelope`,e))}})[n]?.(e,t.params)}}_handleA2ASendMessage(e,t){let n=t.params;if(!n?.message){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing message in SendMessage params`});return}let r=this._taskManagers.get(e);r||(r=new j,this._taskManagers.set(e,r),r.on(t=>{this._forwardTaskEvent(e,t)}));let i=r.handleSendMessage(n),a=this.connections.get(e);if(a){let e={jsonrpc:`2.0`,id:t.id,result:i};a.send(e)}n.message.parts&&Array.isArray(n.message.parts)&&this._processInboundA2AEnvelope(e,n.message.parts,i.task?.id,i.task?.contextId).catch(e=>console.error(`PeerJsChannel: failed to process A2A SendMessage`,e))}_handleAGUIEventNotification(e,t){if(!t||typeof t!=`object`)return;let n=t;window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{remotePeerId:e,event:n}}))}_handleGetAgentCard(e,t){if(!this._localCard){this._sendJsonRpcError(e,t.id,{code:x.INTERNAL_ERROR,message:`Agent card not available`});return}let n=E(t.id,this._localCard),r=this.connections.get(e);r&&r.send(n)}_handleInboundData(e,t){if(t instanceof ArrayBuffer||t instanceof Uint8Array){if(this._pendingInboundFile){let n=this._pendingInboundFile.name,r=new Uint8Array(t),i=this._pendingInboundFile.targetGroupId||`peer:${e}`,a=this._saveInboundFile(i,n,r);this._inboundSavePromises.set(n,a),this._pendingInboundFile=null}return}if(!t||typeof t!=`object`)return;let r=t;if(r.type===`__file_header`){let t=r.id||r.name,n=r.totalChunks||1,i=this._inboundTransfers.get(t),a=typeof r.groupId==`string`&&r.groupId.startsWith(`room:`)?r.groupId:`peer:${e}`;this._inboundTransfers.set(t,{transferId:t,name:r.name,mimeType:r.mimeType||`application/octet-stream`,size:r.size||0,totalChunks:n,receivedChunks:i?.receivedChunks||/* @__PURE__ */ new Map,receivedBytes:i?.receivedBytes||0,targetGroupId:a}),this._pendingInboundFile={name:r.name,mimeType:r.mimeType,size:r.size,targetGroupId:a},P({count:0,total:n,direction:`receive`})}else if(r.type===`__file_chunk`){let t=r.id||r.name,n=this._inboundTransfers.get(t);if(!n){let e=r.totalChunks||1;n={transferId:t,name:r.name,mimeType:`application/octet-stream`,size:0,totalChunks:e,receivedChunks:/* @__PURE__ */ new Map,receivedBytes:0},this._inboundTransfers.set(t,n)}let i=typeof r.index==`number`?r.index:0,a=r.data instanceof ArrayBuffer?new Uint8Array(r.data):r.data instanceof Uint8Array?r.data:new Uint8Array(r.data||[]);if(n.receivedChunks.has(i)||(n.receivedChunks.set(i,a),n.receivedBytes+=a.byteLength),P({count:n.receivedChunks.size,total:n.totalChunks,direction:`receive`}),n.receivedChunks.size>=n.totalChunks){let r=new Uint8Array(n.size||n.receivedBytes),i=0;for(let e=0;e<n.totalChunks;e++){let t=n.receivedChunks.get(e);t&&(r.set(t,i),i+=t.byteLength)}let a=n.targetGroupId||`peer:${e}`,o=this._saveInboundFile(a,n.name,r);this._inboundSavePromises.set(n.name,o),this._inboundTransfers.delete(t),this._pendingInboundFile=null,F(1500)}}else if(r.type===`typing`)this.typingCallback?.(`peer:${e}`,!!r.typing);else if(r.type===`chat`){let t=typeof r.text==`string`?r.text.trim():``;t&&this.messageCallback?.({id:n(),groupId:`peer:${e}`,sender:e,content:t,timestamp:Date.now(),channel:`peerjs`})}else if(r.jsonrpc===`2.0`)this._handleA2AJsonRpc(e,r);else if(r.type===`command:execute`){let t=r.payload||{},i=t.action||``,a=t.args||{},o=t.commandId||``;import(`./init-control-plane-BoJijVtf.js`).then(({executeClientControlCommand:e})=>e(i,a)).then(t=>{let r=this.connections.get(e);if(r){let e=!!t?.error;r.send({id:n(),type:`command:result`,payload:{commandId:o,action:i,success:!e,data:t,...e?{error:t.error}:{}}})}}).catch(t=>{let r=this.connections.get(e);r&&r.send({id:n(),type:`command:result`,payload:{commandId:o,action:i,success:!1,error:t?.message||String(t)}})})}}_isTrustedPeer(e){if(this.trustedPeerIds.size===0||this.trustedPeerIds.has(e))return!0;for(let t of this.trustedPeerIds){let n=t.trim();if(n.endsWith(`*`)&&e.startsWith(n.slice(0,-1))||n===`cli`&&e.startsWith(`cli-`))return!0}return!1}_handleIncomingConnection(e){let t=e.peer;if(this._isTrustedPeer(t))this._attachChunkProgressTracker(e),this.connections.set(t,e),this._updateConnectedPeersSignal(),e.on(`open`,()=>{console.log(`PeerJsChannel: connection opened with ${t}`),this._exchangeAgentCards(t,e)}),e.on(`data`,e=>{this._handleInboundData(t,e)}),e.on(`close`,()=>{console.log(`PeerJsChannel: connection closed with ${t}`),this.connections.delete(t),this.peerCards.delete(t),this._taskManagers.delete(t),this._updateConnectedPeersSignal()}),e.on(`error`,e=>{console.error(`PeerJsChannel: connection error with ${t}:`,e),this.connections.delete(t),this._updateConnectedPeersSignal(),window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{remotePeerId:t,error:e.message}}))}),e.on(`iceStateChanged`,e=>{(e===`failed`||e===`disconnected`||e===`closed`)&&(console.warn(`PeerJsChannel: ICE state changed to ${e} for ${t}`),this.connections.delete(t),this._updateConnectedPeersSignal())});else{console.warn(`PeerJsChannel: rejecting connection from untrusted peer: ${t}`);try{e.close()}catch{}}}_attachChunkProgressTracker(e){let t=e;if(t._chunkProgressPatched)return;t._chunkProgressPatched=!0;let n=this,r=t._handleChunk;typeof r==`function`&&(t._handleChunk=function(e){if(e&&typeof e==`object`&&`__peerData`in e&&n._inboundTransfers.size===0){let t=e.__peerData,n=this._chunkedData?.[t]?.count??0,r=e.total;if(typeof globalThis.dispatchEvent==`function`&&typeof CustomEvent==`function`)globalThis.dispatchEvent(new CustomEvent(`peerjs-dc-handle-chunk`,{detail:{chunkInfo:{count:n,total:r}}}));else{let e=n+1;P({count:e,total:r,direction:`receive`}),e>=r&&F(1500)}}return r.call(this,e)})}_handleTaskStatusNotification(e,t){if(!t||typeof t!=`object`)return;let n=t;if(n.status?.state&&h.has(n.status.state)){let t=`peer:${e}`;this._onTaskCompleteCallback?.(t)}window.dispatchEvent(new CustomEvent(`shadow-claw-task-status`,{detail:{remotePeerId:e,...n}}))}async _initPeer(){let{Peer:e}=await import(`./bundler-UnYfEehP.js`),t={},n=this.serverConfig.host??`0.peerjs.com`,r=this.serverConfig.port??443,i=this.serverConfig.path??`/`,a=this.serverConfig.secure??!0;t.host=n,t.port=r,t.path=i,t.secure=a,t.debug=3,t.config={iceServers:this.serverConfig.iceServers??[{urls:`stun:stun.l.google.com:19302`},{urls:`stun:stun1.l.google.com:19302`}]},this.peer=new e(this.myPeerId,t),this.peer.on(`open`,e=>{console.log(`PeerJsChannel: connected to signaling server, peer ID: ${e}`),this._reconnectAttempts=0}),this.peer.on(`connection`,e=>{this._handleIncomingConnection(e)}),this.peer.on(`error`,e=>{console.error(`PeerJsChannel: peer error [${e.type}]:`,e.message),(e.type===`peer-unavailable`||e.type===`unavailable-id`)&&window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{error:e.message}})),e.type!==`peer-unavailable`&&e.type!==`network`&&e.type!==`disconnected`&&e.type===`unavailable-id`&&console.warn(`PeerJsChannel: peer ID is already in use. Stop the channel and reconfigure.`)}),this.peer.on(`disconnected`,()=>{this.running&&this._scheduleReconnect()}),this.peer.on(`close`,()=>{console.log(`PeerJsChannel: peer closed`)})}_registerPendingRequest(e,t){let n=String(e??``),r=setTimeout(()=>{this._pendingRequests.delete(n),console.warn(`PeerJsChannel: JSON-RPC request ${n} timed out (10s)`)},1e4);this._pendingRequests.set(n,{resolve:t,timer:r})}_scheduleReconnect(){if(this._reconnectTimer!==null)return;let e=Math.min(a._RECONNECT_BASE_MS*2**this._reconnectAttempts,a._RECONNECT_MAX_MS);this._reconnectAttempts++,console.log(`PeerJsChannel: disconnected from signaling server, reconnecting in ${(e/1e3).toFixed(1)}s (attempt ${this._reconnectAttempts})`),this._reconnectTimer=setTimeout(()=>{if(this._reconnectTimer=null,this.running)try{this.peer?.reconnect?.()}catch{this._scheduleReconnect()}},e)}_sendJsonRpcError(e,t,n){let r=this.connections.get(e);if(!r)return;let i={jsonrpc:`2.0`,id:t,error:n};try{r.send(i)}catch{}}async _waitForBufferDrain(e,t=65536){let n=e.dataChannel||e._dc;n&&typeof n.bufferedAmount==`number`&&(n.bufferedAmount<=t||await new Promise(e=>{let r=setInterval(()=>{(!n||n.bufferedAmount<=t)&&(clearInterval(r),e())},20);if(typeof n.addEventListener==`function`){let i=()=>{clearInterval(r),n.removeEventListener(`bufferedamountlow`,i),e()};try{n.bufferedAmountLowThreshold=t,n.addEventListener(`bufferedamountlow`,i,{once:!0})}catch{}}}))}async _saveInboundFile(t,n,i){try{let a=await e(),o=n,s=1;for(;await r(a,t,o);){let e=n.lastIndexOf(`.`);if(e>0&&e<n.length-1){let t=n.substring(0,e),r=n.substring(e);o=`${t} (${s})${r}`}else o=`${n} (${s})`;s++}o!==n&&this._inboundRemap.set(n,o),await c(a,t,o,i);try{let{orchestratorStore:e}=await import(`./orchestrator-CaUpEVkQ.js`).then(e=>e.n);e.activeGroupId===t&&await e.loadFiles(a)}catch{}}catch(e){console.error(`PeerJsChannel: failed to write inbound file bytes`,e)}}_updateConnectedPeersSignal(){this.connectedPeersSignal.set(Array.from(this.connections.keys()))}_waitForOpen(e){return e.open?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>{n(/* @__PURE__ */ Error(`Connection open timeout (5s)`))},5e3);e.on(`open`,()=>{clearTimeout(r),t()}),e.on(`error`,e=>{clearTimeout(r),n(e)})})}async _processInboundA2AEnvelope(e,t,r,i){let a=`peer:${e}`,o=``,s=[],c=[],l;for(let e of t)if(e.kind===`text`&&typeof e.text==`string`)o+=e.text;else if(e.kind===`file`){let t=e.name||`attachment`,n=this._inboundSavePromises.get(t);if(n)try{await n}catch{}finally{this._inboundSavePromises.delete(t)}if(this._inboundRemap.has(t)){let e=this._inboundRemap.get(t),n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);o=o.replace(RegExp(`(!?\\[.*?\\])\\(${n}\\)`,`g`),`$1(${e})`),this._inboundRemap.delete(t),t=e}let r=t.split(`/`).pop()||`attachment`;s.push({fileName:r,mimeType:e.mimeType,path:t,size:e.size||0})}else e.kind===`a2ui`&&e.envelope?c.push(e.envelope):e.kind===`a2ui-action`&&e.action&&(l=e.action);o=o.trim(),(o||s.length!==0||c.length!==0||l)&&this.messageCallback?.({id:n(),groupId:a,sender:e,content:o,timestamp:Date.now(),channel:`peerjs`,attachments:s.length>0?s:void 0,a2uiEnvelopes:c.length>0?c:void 0,a2uiAction:l,taskId:r,contextId:i})}};function R(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r,i=e;for(;(r=n.exec(e))!==null;){let e=r[1],n=z((r[2]||``).trim());n&&t.push({alt:e,path:n})}return{remainingText:i,attachments:t}}function z(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}export{u as a,f as i,M as n,b as r,L as t};
|
|
1
|
+
import"./config-C16fFWtP.js";import{n as e}from"./db-BUuJo1Gf.js";import{t}from"./dist-CeFyqf9k.js";import{t as n}from"./ulid-BSJxYh6W.js";import{o as r}from"./tools-D-52Zmfc.js";import{a as i}from"./transformers-CQ9ss9rD.js";import{i as a}from"./mime-ClqNyXPc.js";import{t as o}from"./upload-group-file-A8kB7lvO.js";import{n as s}from"./filename-kBumOBho.js";import{t as c}from"./write-group-file-bytes-A8kB7lvO.js";function l(e){return s(e,{replacement:`-`,fallback:`attachment`,stripLeadingDots:!0,collapseReplacement:!0,stripControlChars:!0})}function u(e){return e.previewDisposition===`inline`||a(e.fileName,e.mimeType||``)===`image/png`}function d(e,t=``,n=Date.now()){let r=l(e),i=t.trim().replace(/[^a-zA-Z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``);return`attachments/${n}-${i?`${i}-`:``}${r}`}async function f(e,t,n=[]){let r=[];for(let i of n){let n=l(i.fileName||``),s=i.path||d(n,i.id),c=i.source,u=a(n,i.mimeType||``),f=i.size;if(c){let r=await p(c);u=a(n,i.mimeType||r.type),f=typeof f==`number`?f:r.size,await o(e,t,s,r)}r.push(m({...i,fileName:n,mimeType:u,size:f,path:s,previewDisposition:i.previewDisposition||(u===`image/png`?`inline`:`file`)}))}return r}async function p(e){if(e.kind===`local-file`)return e.file;if(e.kind===`inline-text`)return new Blob([e.text],{type:e.mimeType||`text/plain`});let t=await fetch(e.url,{headers:e.headers});if(!t.ok)throw Error(`Attachment download failed: HTTP ${t.status} ${t.statusText}`);return await t.blob()}function m(e){let{source:t,...n}=e;return n}const h=/* @__PURE__ */ new Set([`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_REJECTED`]),g=/* @__PURE__ */ new Set([`TASK_STATE_INPUT_REQUIRED`,`TASK_STATE_AUTH_REQUIRED`]),_={SEND_MESSAGE:`SendMessage`,SEND_STREAMING_MESSAGE:`SendStreamingMessage`,GET_TASK:`GetTask`,CANCEL_TASK:`CancelTask`,GET_AGENT_CARD:`GetAgentCard`},v={EVENT:`agui/event`},y={STATUS_UPDATE:`tasks/statusUpdate`,ARTIFACT_UPDATE:`tasks/artifactUpdate`},b={JOIN:`room/join`,ROSTER:`room/roster`,LEAVE:`room/leave`,MESSAGE:`room/message`,INVITE:`room/invite`,RELAY:`room/relay`,A2UI:`room/a2ui`,A2UI_ACTION:`room/a2ui-action`},x={TASK_NOT_FOUND:-32001,TASK_NOT_CANCELABLE:-32002,PUSH_NOTIFICATION_NOT_SUPPORTED:-32003,UNSUPPORTED_OPERATION:-32004,CONTENT_TYPE_NOT_SUPPORTED:-32005,INVALID_AGENT_RESPONSE:-32006,PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603};function S(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`&&(e.id===null||typeof e.id==`string`||typeof e.id==`number`)&&typeof e.method==`string`}function C(e){return typeof e==`object`&&!!e&&e.jsonrpc===`2.0`&&(e.id===null||typeof e.id==`string`||typeof e.id==`number`)&&!(`method`in e)}function w(e){let t={url:`webrtc://${e.peerId}`,protocolBinding:`https://xt-ml.github.io/shadow-claw/bindings/webrtc-datachannel/v1`,protocolVersion:`1.0`},n={streaming:e.streaming??!0,pushNotifications:!1};return{name:e.name,description:e.description??`AI assistant agent (${e.name})`,version:e.version??`1.0.0`,supportedInterfaces:[t],capabilities:n,defaultInputModes:[`text/plain`,`application/json`],defaultOutputModes:[`text/plain`,`application/json`],skills:e.skills??[],iconUrl:e.iconUrl}}function T(){return{jsonrpc:`2.0`,id:n(),method:_.GET_AGENT_CARD}}function E(e,t){return{jsonrpc:`2.0`,id:e,result:t}}function D(e){if(e.error)return console.warn(`GetAgentCard returned error:`,e.error),null;let t=e.result;return!t||typeof t!=`object`||typeof t.name!=`string`||typeof t.version!=`string`?null:t}var O=class{_cards=/* @__PURE__ */ new Map;clear(){this._cards.clear()}delete(e){this._cards.delete(e)}entries(){return this._cards.entries()}get(e){return this._cards.get(e)}getDisplayName(e){return this._cards.get(e)?.name??e}has(e){return this._cards.has(e)}set(e,t){this._cards.set(e,t)}supportsStreaming(e){return this._cards.get(e)?.capabilities?.streaming??!1}};const k={maxTasks:100,maxHistoryPerTask:50},A=/* @__PURE__ */ new Map([[`TASK_STATE_SUBMITTED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_REJECTED`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])],[`TASK_STATE_WORKING`,/* @__PURE__ */ new Set([`TASK_STATE_COMPLETED`,`TASK_STATE_FAILED`,`TASK_STATE_CANCELED`,`TASK_STATE_INPUT_REQUIRED`,`TASK_STATE_AUTH_REQUIRED`])],[`TASK_STATE_INPUT_REQUIRED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])],[`TASK_STATE_AUTH_REQUIRED`,/* @__PURE__ */ new Set([`TASK_STATE_WORKING`,`TASK_STATE_CANCELED`,`TASK_STATE_FAILED`])]]);var j=class{_config;_contextActiveTask=/* @__PURE__ */ new Map;_listeners=/* @__PURE__ */ new Set;_taskOrder=[];_tasks=/* @__PURE__ */ new Map;constructor(e){this._config={...k,...e}}addArtifact(e,t,n=!1){let r=this._tasks.get(e);if(!r)return;if(r.artifacts||=[],n){let e=r.artifacts.find(e=>e.artifactId===t.artifactId);e?e.parts.push(...t.parts):r.artifacts.push(t)}else r.artifacts.push(t);let i={taskId:r.id,contextId:r.contextId??``,artifact:t,append:n,lastChunk:!1};this._emit({type:`artifactUpdate`,taskId:r.id,contextId:r.contextId??``,payload:i})}cancelTask(e){let t=this._tasks.get(e);return!t||h.has(t.status.state)?!1:(this._transitionState(t,`TASK_STATE_CANCELED`,{messageId:n(),role:`ROLE_AGENT`,parts:[{text:`Task canceled by peer request.`}]}),!0)}clear(){this._tasks.clear(),this._taskOrder=[],this._contextActiveTask.clear()}emitRunError(e,t,n){let r=this._tasks.get(e);if(!r)return;let i={type:`RUN_ERROR`,message:t,code:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitRunFinished(e){let t=this._tasks.get(e);if(!t)return;let n={type:`RUN_FINISHED`,threadId:t.contextId??t.id,runId:t.id,timestamp:Date.now()};this._emitAGUI(t,n)}emitRunStarted(e){let t=this._tasks.get(e);if(!t)return;let n={type:`RUN_STARTED`,threadId:t.contextId??t.id,runId:t.id,timestamp:Date.now()};this._emitAGUI(t,n)}emitStateSnapshot(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`STATE_SNAPSHOT`,snapshot:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitTextMessageContent(e,t,n){let r=this._tasks.get(e);if(!r)return;let i={type:`TEXT_MESSAGE_CONTENT`,messageId:t,delta:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitTextMessageEnd(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`TEXT_MESSAGE_END`,messageId:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitTextMessageStart(e,t,n=`assistant`){let r=this._tasks.get(e);if(!r)return;let i={type:`TEXT_MESSAGE_START`,messageId:t,role:n,timestamp:Date.now()};this._emitAGUI(r,i)}emitToolCallEnd(e,t){let n=this._tasks.get(e);if(!n)return;let r={type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()};this._emitAGUI(n,r)}emitToolCallStart(e,t,n,r){let i=this._tasks.get(e);if(!i)return;let a={type:`TOOL_CALL_START`,toolCallId:t,toolCallName:n,parentMessageId:r,timestamp:Date.now()};this._emitAGUI(i,a)}getActiveTaskForContext(e){let t=this._contextActiveTask.get(e);if(t)return this._tasks.get(t)}getActiveTasks(){return Array.from(this._tasks.values()).filter(e=>!h.has(e.status.state))}getAllTasks(){return Array.from(this._tasks.values())}getTask(e){return this._tasks.get(e)}handleSendMessage(e){let t=e.message,r=t.contextId??n(),i=t.taskId??this._contextActiveTask.get(r);return i&&this._tasks.has(i)?this._continueTask(i,t):this._createTask(r,t)}markCompleted(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_COMPLETED`,t)}markFailed(e,t){let r=this._tasks.get(e);r&&this._transitionState(r,`TASK_STATE_FAILED`,{messageId:n(),role:`ROLE_AGENT`,parts:[{text:t}]})}markInputRequired(e,t){let n=this._tasks.get(e);n&&this._transitionState(n,`TASK_STATE_INPUT_REQUIRED`,t)}markWorking(e){let t=this._tasks.get(e);t&&this._transitionState(t,`TASK_STATE_WORKING`)}off(e){this._listeners.delete(e)}on(e){this._listeners.add(e)}_addTask(e){for(this._tasks.set(e.id,e),this._taskOrder.push(e.id);this._taskOrder.length>this._config.maxTasks;){let e=this._taskOrder.shift(),t=this._tasks.get(e);if(t&&h.has(t.status.state))this._tasks.delete(e),t.contextId&&this._contextActiveTask.delete(t.contextId);else{this._taskOrder.unshift(e);break}}}_continueTask(e,t){let n=this._tasks.get(e);return g.has(n.status.state)&&this._transitionState(n,`TASK_STATE_WORKING`),n.history||=[],n.history.push(t),n.history.length>this._config.maxHistoryPerTask&&(n.history=n.history.slice(-this._config.maxHistoryPerTask)),this._touchTask(e),{task:n}}_createTask(e,t){let r=n(),i={id:r,contextId:e,status:{state:`TASK_STATE_SUBMITTED`,timestamp:(/* @__PURE__ */ new Date()).toISOString()},history:[t]};return this._addTask(i),this._contextActiveTask.set(e,r),this._emitStatusUpdate(i),{task:i}}_emit(e){for(let t of this._listeners)try{t(e)}catch(e){console.error(`PeerTaskManager: listener error`,e)}}_emitAGUI(e,t){this._emit({type:`aguiEvent`,taskId:e.id,contextId:e.contextId??``,payload:t})}_emitStatusUpdate(e){let t={taskId:e.id,contextId:e.contextId??``,status:e.status};this._emit({type:`statusUpdate`,taskId:e.id,contextId:e.contextId??``,payload:t})}_touchTask(e){let t=this._taskOrder.indexOf(e);t!==-1&&(this._taskOrder.splice(t,1),this._taskOrder.push(e))}_transitionState(e,t,n){let r=e.status.state,i=A.get(r);i&&!i.has(t)?console.warn(`PeerTaskManager: invalid transition ${r} → ${t} for task ${e.id}`):h.has(r)?console.warn(`PeerTaskManager: task ${e.id} is in terminal state ${r}, cannot transition`):(e.status={state:t,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString()},h.has(t)&&e.contextId&&this._contextActiveTask.get(e.contextId)===e.id&&this._contextActiveTask.delete(e.contextId),this._emitStatusUpdate(e))}};const M=new t.State(null);let N=null;function P(e){N!==null&&(clearTimeout(N),N=null),M.set(e)}function F(e=1500){N!==null&&clearTimeout(N),N=setTimeout(()=>{M.set(null),N=null},e)}const I=15360;var L=class a{static _RECONNECT_BASE_MS=1e3;static _RECONNECT_MAX_MS=6e4;connectedPeersSignal=new t.State([]);connections=/* @__PURE__ */ new Map;messageCallback=null;myPeerId=``;peerCards=new O;running=!1;serverConfig={};transferProgressSignal=M;trustedPeerIds=/* @__PURE__ */ new Set;type=`peerjs`;typingCallback=null;_inboundRemap=/* @__PURE__ */ new Map;_localCard=null;_onTaskCompleteCallback=null;peer=null;_inboundSavePromises=/* @__PURE__ */ new Map;_pendingInboundFile=null;_pendingRequests=/* @__PURE__ */ new Map;_reconnectAttempts=0;_reconnectTimer=null;_roomNotificationHandler=null;_taskManagers=/* @__PURE__ */ new Map;_inboundTransfers=/* @__PURE__ */ new Map;constructor(){typeof globalThis.addEventListener==`function`&&globalThis.addEventListener(`peerjs-dc-handle-chunk`,e=>{if(e?.detail?.chunkInfo){if(this._inboundTransfers.size>0)return;let{count:t,total:n}=e.detail.chunkInfo,r=t+1;P({count:r,total:n,direction:`receive`}),r>=n&&F(1500)}})}completeActiveTask(e){let t=e.replace(/^peer:/,``),n=this._taskManagers.get(t);if(!n)return!1;let r=n.getActiveTasks();if(r.length===0)return!1;let i=r[r.length-1];return n.markWorking(i.id),n.markCompleted(i.id),!0}configure(e,t,n={}){this.myPeerId=e.trim(),this.trustedPeerIds=new Set(t.map(e=>e.trim()).filter(Boolean)),this.serverConfig=n}connectPeer(e){this._getOrOpenConnection(e)}getTaskManager(e){let t=this._taskManagers.get(e);return t||(t=new j,this._taskManagers.set(e,t),t.on(t=>{this._forwardTaskEvent(e,t)})),t}isConfigured(){return this.myPeerId.length>0}isPeerConnected(e){let t=this.connections.get(e);return!!t&&!!t.open}onMessage(e){this.messageCallback=e}onTaskComplete(e){this._onTaskCompleteCallback=e}onTyping(e){this.typingCallback=e}sendRoomNotification(e,t){let n=this._getOrOpenConnection(e);if(!n)return!1;if(n.open)try{return n.send(t),!0}catch(t){return console.error(`PeerJsChannel: failed to send room notification to ${e}:`,t),!1}return this._waitForOpen(n).then(()=>{try{n.send(t)}catch(t){console.error(`PeerJsChannel: failed to flush room notification to ${e}:`,t)}}).catch(()=>{}),!0}setRoomNotificationHandler(e){this._roomNotificationHandler=e}async sendAttachmentsToRoom(t,r,a){let o=this.myPeerId,s=(a||[]).filter(e=>!!e.path);if(s.length!==0)try{let a=await e();for(let e of s){let s;try{s=await i(a,r,e.path)}catch(t){console.warn(`PeerJsChannel: failed to read file ${e.path} for room:`,t);continue}let c=e.path,l=e.mimeType||`application/octet-stream`,u=Math.max(1,Math.ceil(s.length/I));for(let i of t.members){if(i.peerId===o)continue;let t=this._getOrOpenConnection(i.peerId);if(t)try{await this._waitForOpen(t);let e=n();t.send({type:`__file_header`,id:e,name:c,mimeType:l,size:s.length,totalChunks:u,chunkSize:I,groupId:r});for(let n=0;n<u;n++){let r=n*I,i=Math.min(r+I,s.length),a=s.subarray(r,i),o=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength);t.send({type:`__file_chunk`,id:e,name:c,index:n,totalChunks:u,data:o}),P({count:n+1,total:u,direction:`send`}),await this._waitForBufferDrain(t)}F(1500)}catch(t){console.warn(`PeerJsChannel: failed to stream file ${e.path} to room member ${i.peerId}:`,t)}}}}catch(e){console.error(`PeerJsChannel: failed to access DB for room file transfer`,e)}}setTyping(e,t){let n=e.replace(/^peer:/,``),r=this.connections.get(n);if(r)try{r.send({type:`typing`,typing:t})}catch{}}start(){this.isConfigured()&&!this.running&&(this.running=!0,this._localCard=w({peerId:this.myPeerId,name:this.myPeerId,description:`ShadowClaw AI assistant`,streaming:!0}),this._initPeer())}ensureConnected(e=!1){if(!this.running||!this.isConfigured())return;this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0;let t=this.peer;if(!t||t.destroyed||e&&!t.open){if(t&&!t.destroyed)try{t.destroy()}catch{}this.peer=null,this._initPeer()}else if(t.disconnected)try{t.reconnect?.()}catch{this._initPeer()}}stop(){if(this.running=!1,this._reconnectTimer!==null&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this.connections.forEach(e=>{try{e.close()}catch{}}),this.connections.clear(),this.peerCards.clear(),this._taskManagers.clear(),this._pendingRequests.forEach(({timer:e})=>clearTimeout(e)),this._pendingRequests.clear(),this._updateConnectedPeersSignal(),this.peer){try{this.peer.destroy()}catch{}this.peer=null}}async send(t,r,a){let o=t.replace(/^peer:/,``),s=this._getOrOpenConnection(o);if(!s)console.warn(`PeerJsChannel: no connection available for ${o}`);else try{await this._waitForOpen(s);let{attachments:o}=R(r),c=[...(a||[]).filter(e=>!!e.path),...o.map(e=>({path:e.path,mimeType:`application/octet-stream`}))],l=/* @__PURE__ */ new Map,u=[];try{let r=await e();for(let e of c)if(e.path)try{let a=await i(r,t,e.path),o=e.path;l.has(e.path)||l.set(e.path,o);let c=e.mimeType||`application/octet-stream`,d=n(),f=Math.max(1,Math.ceil(a.length/I));s.send({type:`__file_header`,id:d,name:o,mimeType:c,size:a.length,totalChunks:f,chunkSize:I,groupId:t});for(let e=0;e<f;e++){let t=e*I,n=Math.min(t+I,a.length),r=a.subarray(t,n),i=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);s.send({type:`__file_chunk`,id:d,name:o,index:e,totalChunks:f,data:i}),P({count:e+1,total:f,direction:`send`}),await this._waitForBufferDrain(s)}F(1500),u.push({kind:`file`,name:o,mimeType:c,size:a.length})}catch(t){console.warn(`PeerJsChannel: failed to process file ${e.path}:`,t)}}catch(e){console.error(`PeerJsChannel: failed to access DB`,e)}let d=r;for(let[e,t]of l){let n=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);d=d.replace(RegExp(`(!?\\[.*?\\])\\(${n}\\)`,`g`),`$1(${t})`)}let f=[...u,{kind:`text`,text:d}],p=n(),m={jsonrpc:`2.0`,id:p,method:_.SEND_MESSAGE,params:{message:{messageId:n(),role:`ROLE_AGENT`,parts:f}}};s.send(m),this._registerPendingRequest(p,e=>{})}catch(e){console.error(`PeerJsChannel: send failed for ${o}:`,e),window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{remotePeerId:o,error:e instanceof Error?e.message:String(e)}}))}}async sendA2UI(e,t){let r=e.replace(/^peer:/,``),i=this._getOrOpenConnection(r);if(!i)console.warn(`PeerJsChannel.sendA2UI: no connection available for ${r}`);else try{await this._waitForOpen(i);let e={jsonrpc:`2.0`,method:`message/send`,id:n(),params:{message:{role:`agent`,parts:[{kind:`a2ui`,envelope:t}]}}};i.send(e)}catch(e){console.error(`PeerJsChannel.sendA2UI: failed for ${r}:`,e)}}async sendA2UIAction(e,t){let r=e.replace(/^peer:/,``),i=this._getOrOpenConnection(r);if(!i)console.warn(`PeerJsChannel.sendA2UIAction: no connection available for ${r}`);else try{await this._waitForOpen(i);let e={jsonrpc:`2.0`,method:`message/send`,id:n(),params:{message:{role:`user`,parts:[{kind:`a2ui-action`,action:t}]}}};i.send(e)}catch(e){console.error(`PeerJsChannel.sendA2UIAction: failed for ${r}:`,e)}}_exchangeAgentCards(e,t){if(!this._localCard)return;let n=T();t.send(n),this._registerPendingRequest(n.id,t=>{let n=D(t);n&&(this.peerCards.set(e,n),console.log(`PeerJsChannel: received AgentCard from ${e}: "${n.name}"`))})}_forwardTaskEvent(e,t){let n=this.connections.get(e);if(!n)return;let r;switch(t.type){case`statusUpdate`:r=y.STATUS_UPDATE;break;case`artifactUpdate`:r=y.ARTIFACT_UPDATE;break;case`aguiEvent`:r=v.EVENT;break;default:return}let i={jsonrpc:`2.0`,method:r,params:t.payload};try{n.send(i)}catch(n){console.error(`PeerJsChannel: failed to forward ${t.type} to ${e}:`,n)}}_getOrOpenConnection(e){let t=this.connections.get(e);if(t)return t;if(!this.peer)return null;try{let t=this.peer.connect(e,{reliable:!0,serialization:`binary`});return t?(this._handleIncomingConnection(t),t):null}catch(t){return console.error(`PeerJsChannel: failed to connect to ${e}:`,t),null}}_handleA2ACancelTask(e,t){let n=t.params;if(!n?.taskId){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing taskId in CancelTask params`});return}let r=this._taskManagers.get(e);if(!r){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_FOUND,message:`Task not found: ${n.taskId}`});return}if(!r.cancelTask(n.taskId)){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_CANCELABLE,message:`Task not cancelable: ${n.taskId}`});return}let i=this.connections.get(e);if(i){let e=r.getTask(n.taskId),a={jsonrpc:`2.0`,id:t.id,result:{task:e}};i.send(a)}}_handleA2AGetTask(e,t){let n=t.params;if(!n?.taskId){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing taskId in GetTask params`});return}let r=this._taskManagers.get(e)?.getTask(n.taskId);if(!r){this._sendJsonRpcError(e,t.id,{code:x.TASK_NOT_FOUND,message:`Task not found: ${n.taskId}`});return}let i=this.connections.get(e);if(i){let e={jsonrpc:`2.0`,id:t.id,result:{task:r}};i.send(e)}}_handleA2AJsonRpc(e,t){if(C(t)){let e=String(t.id??``),n=this._pendingRequests.get(e);n&&(clearTimeout(n.timer),this._pendingRequests.delete(e),n.resolve(t));return}let n=t.method;if(n){if(n.startsWith(`room/`))this._roomNotificationHandler?.(e,n,t.params);else if(S(t)){let r={[_.GET_AGENT_CARD]:(e,t)=>this._handleGetAgentCard(e,t),[_.SEND_MESSAGE]:(e,t)=>this._handleA2ASendMessage(e,t),[_.CANCEL_TASK]:(e,t)=>this._handleA2ACancelTask(e,t),[_.GET_TASK]:(e,t)=>this._handleA2AGetTask(e,t)}[n];if(r){r(e,t);return}if(n===`message/send`){let n=t.params;n?.message?.parts&&Array.isArray(n.message.parts)&&this._processInboundA2AEnvelope(e,n.message.parts).catch(e=>console.error(`PeerJsChannel: failed to process inbound A2A envelope`,e))}else this._sendJsonRpcError(e,t.id,{code:x.METHOD_NOT_FOUND,message:`Method not found: ${n}`})}else({[v.EVENT]:(e,t)=>this._handleAGUIEventNotification(e,t),[y.STATUS_UPDATE]:(e,t)=>this._handleTaskStatusNotification(e,t),[y.ARTIFACT_UPDATE]:()=>{},"message/send":(e,t)=>{t?.message?.parts&&Array.isArray(t.message.parts)&&this._processInboundA2AEnvelope(e,t.message.parts).catch(e=>console.error(`PeerJsChannel: failed to process inbound A2A envelope`,e))}})[n]?.(e,t.params)}}_handleA2ASendMessage(e,t){let n=t.params;if(!n?.message){this._sendJsonRpcError(e,t.id,{code:x.INVALID_PARAMS,message:`Missing message in SendMessage params`});return}let r=this._taskManagers.get(e);r||(r=new j,this._taskManagers.set(e,r),r.on(t=>{this._forwardTaskEvent(e,t)}));let i=r.handleSendMessage(n),a=this.connections.get(e);if(a){let e={jsonrpc:`2.0`,id:t.id,result:i};a.send(e)}n.message.parts&&Array.isArray(n.message.parts)&&this._processInboundA2AEnvelope(e,n.message.parts,i.task?.id,i.task?.contextId).catch(e=>console.error(`PeerJsChannel: failed to process A2A SendMessage`,e))}_handleAGUIEventNotification(e,t){if(!t||typeof t!=`object`)return;let n=t;window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{remotePeerId:e,event:n}}))}_handleGetAgentCard(e,t){if(!this._localCard){this._sendJsonRpcError(e,t.id,{code:x.INTERNAL_ERROR,message:`Agent card not available`});return}let n=E(t.id,this._localCard),r=this.connections.get(e);r&&r.send(n)}_handleInboundData(e,t){if(t instanceof ArrayBuffer||t instanceof Uint8Array){if(this._pendingInboundFile){let n=this._pendingInboundFile.name,r=new Uint8Array(t),i=this._pendingInboundFile.targetGroupId||`peer:${e}`,a=this._saveInboundFile(i,n,r);this._inboundSavePromises.set(n,a),this._pendingInboundFile=null}return}if(!t||typeof t!=`object`)return;let r=t;if(r.type===`__file_header`){let t=r.id||r.name,n=r.totalChunks||1,i=this._inboundTransfers.get(t),a=typeof r.groupId==`string`&&r.groupId.startsWith(`room:`)?r.groupId:`peer:${e}`;this._inboundTransfers.set(t,{transferId:t,name:r.name,mimeType:r.mimeType||`application/octet-stream`,size:r.size||0,totalChunks:n,receivedChunks:i?.receivedChunks||/* @__PURE__ */ new Map,receivedBytes:i?.receivedBytes||0,targetGroupId:a}),this._pendingInboundFile={name:r.name,mimeType:r.mimeType,size:r.size,targetGroupId:a},P({count:0,total:n,direction:`receive`})}else if(r.type===`__file_chunk`){let t=r.id||r.name,n=this._inboundTransfers.get(t);if(!n){let e=r.totalChunks||1;n={transferId:t,name:r.name,mimeType:`application/octet-stream`,size:0,totalChunks:e,receivedChunks:/* @__PURE__ */ new Map,receivedBytes:0},this._inboundTransfers.set(t,n)}let i=typeof r.index==`number`?r.index:0,a=r.data instanceof ArrayBuffer?new Uint8Array(r.data):r.data instanceof Uint8Array?r.data:new Uint8Array(r.data||[]);if(n.receivedChunks.has(i)||(n.receivedChunks.set(i,a),n.receivedBytes+=a.byteLength),P({count:n.receivedChunks.size,total:n.totalChunks,direction:`receive`}),n.receivedChunks.size>=n.totalChunks){let r=new Uint8Array(n.size||n.receivedBytes),i=0;for(let e=0;e<n.totalChunks;e++){let t=n.receivedChunks.get(e);t&&(r.set(t,i),i+=t.byteLength)}let a=n.targetGroupId||`peer:${e}`,o=this._saveInboundFile(a,n.name,r);this._inboundSavePromises.set(n.name,o),this._inboundTransfers.delete(t),this._pendingInboundFile=null,F(1500)}}else if(r.type===`typing`)this.typingCallback?.(`peer:${e}`,!!r.typing);else if(r.type===`chat`){let t=typeof r.text==`string`?r.text.trim():``;t&&this.messageCallback?.({id:n(),groupId:`peer:${e}`,sender:e,content:t,timestamp:Date.now(),channel:`peerjs`})}else if(r.jsonrpc===`2.0`)this._handleA2AJsonRpc(e,r);else if(r.type===`command:execute`){let t=r.payload||{},i=t.action||``,a=t.args||{},o=t.commandId||``;import(`./init-control-plane-Ctz7FI8M.js`).then(({executeClientControlCommand:e})=>e(i,a)).then(t=>{let r=this.connections.get(e);if(r){let e=!!t?.error;r.send({id:n(),type:`command:result`,payload:{commandId:o,action:i,success:!e,data:t,...e?{error:t.error}:{}}})}}).catch(t=>{let r=this.connections.get(e);r&&r.send({id:n(),type:`command:result`,payload:{commandId:o,action:i,success:!1,error:t?.message||String(t)}})})}}_isTrustedPeer(e){if(this.trustedPeerIds.size===0||this.trustedPeerIds.has(e))return!0;for(let t of this.trustedPeerIds){let n=t.trim();if(n.endsWith(`*`)&&e.startsWith(n.slice(0,-1))||n===`cli`&&e.startsWith(`cli-`))return!0}return!1}_handleIncomingConnection(e){let t=e.peer;if(this._isTrustedPeer(t))this._attachChunkProgressTracker(e),this.connections.set(t,e),this._updateConnectedPeersSignal(),e.on(`open`,()=>{console.log(`PeerJsChannel: connection opened with ${t}`),this._exchangeAgentCards(t,e)}),e.on(`data`,e=>{this._handleInboundData(t,e)}),e.on(`close`,()=>{console.log(`PeerJsChannel: connection closed with ${t}`),this.connections.delete(t),this.peerCards.delete(t),this._taskManagers.delete(t),this._updateConnectedPeersSignal()}),e.on(`error`,e=>{console.error(`PeerJsChannel: connection error with ${t}:`,e),this.connections.delete(t),this._updateConnectedPeersSignal(),window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{remotePeerId:t,error:e.message}}))}),e.on(`iceStateChanged`,e=>{(e===`failed`||e===`disconnected`||e===`closed`)&&(console.warn(`PeerJsChannel: ICE state changed to ${e} for ${t}`),this.connections.delete(t),this._updateConnectedPeersSignal())});else{console.warn(`PeerJsChannel: rejecting connection from untrusted peer: ${t}`);try{e.close()}catch{}}}_attachChunkProgressTracker(e){let t=e;if(t._chunkProgressPatched)return;t._chunkProgressPatched=!0;let n=this,r=t._handleChunk;typeof r==`function`&&(t._handleChunk=function(e){if(e&&typeof e==`object`&&`__peerData`in e&&n._inboundTransfers.size===0){let t=e.__peerData,n=this._chunkedData?.[t]?.count??0,r=e.total;if(typeof globalThis.dispatchEvent==`function`&&typeof CustomEvent==`function`)globalThis.dispatchEvent(new CustomEvent(`peerjs-dc-handle-chunk`,{detail:{chunkInfo:{count:n,total:r}}}));else{let e=n+1;P({count:e,total:r,direction:`receive`}),e>=r&&F(1500)}}return r.call(this,e)})}_handleTaskStatusNotification(e,t){if(!t||typeof t!=`object`)return;let n=t;if(n.status?.state&&h.has(n.status.state)){let t=`peer:${e}`;this._onTaskCompleteCallback?.(t)}window.dispatchEvent(new CustomEvent(`shadow-claw-task-status`,{detail:{remotePeerId:e,...n}}))}async _initPeer(){let{Peer:e}=await import(`./bundler-UnYfEehP.js`),t={},n=this.serverConfig.host??`0.peerjs.com`,r=this.serverConfig.port??443,i=this.serverConfig.path??`/`,a=this.serverConfig.secure??!0;t.host=n,t.port=r,t.path=i,t.secure=a,t.debug=3,t.config={iceServers:this.serverConfig.iceServers??[{urls:`stun:stun.l.google.com:19302`},{urls:`stun:stun1.l.google.com:19302`}]},this.peer=new e(this.myPeerId,t),this.peer.on(`open`,e=>{console.log(`PeerJsChannel: connected to signaling server, peer ID: ${e}`),this._reconnectAttempts=0}),this.peer.on(`connection`,e=>{this._handleIncomingConnection(e)}),this.peer.on(`error`,e=>{console.error(`PeerJsChannel: peer error [${e.type}]:`,e.message),(e.type===`peer-unavailable`||e.type===`unavailable-id`)&&window.dispatchEvent(new CustomEvent(`shadow-claw-peer-error`,{detail:{error:e.message}})),e.type!==`peer-unavailable`&&e.type!==`network`&&e.type!==`disconnected`&&e.type===`unavailable-id`&&console.warn(`PeerJsChannel: peer ID is already in use. Stop the channel and reconfigure.`)}),this.peer.on(`disconnected`,()=>{this.running&&this._scheduleReconnect()}),this.peer.on(`close`,()=>{console.log(`PeerJsChannel: peer closed`)})}_registerPendingRequest(e,t){let n=String(e??``),r=setTimeout(()=>{this._pendingRequests.delete(n),console.warn(`PeerJsChannel: JSON-RPC request ${n} timed out (10s)`)},1e4);this._pendingRequests.set(n,{resolve:t,timer:r})}_scheduleReconnect(){if(this._reconnectTimer!==null)return;let e=Math.min(a._RECONNECT_BASE_MS*2**this._reconnectAttempts,a._RECONNECT_MAX_MS);this._reconnectAttempts++,console.log(`PeerJsChannel: disconnected from signaling server, reconnecting in ${(e/1e3).toFixed(1)}s (attempt ${this._reconnectAttempts})`),this._reconnectTimer=setTimeout(()=>{if(this._reconnectTimer=null,this.running)try{this.peer?.reconnect?.()}catch{this._scheduleReconnect()}},e)}_sendJsonRpcError(e,t,n){let r=this.connections.get(e);if(!r)return;let i={jsonrpc:`2.0`,id:t,error:n};try{r.send(i)}catch{}}async _waitForBufferDrain(e,t=65536){let n=e.dataChannel||e._dc;n&&typeof n.bufferedAmount==`number`&&(n.bufferedAmount<=t||await new Promise(e=>{let r=setInterval(()=>{(!n||n.bufferedAmount<=t)&&(clearInterval(r),e())},20);if(typeof n.addEventListener==`function`){let i=()=>{clearInterval(r),n.removeEventListener(`bufferedamountlow`,i),e()};try{n.bufferedAmountLowThreshold=t,n.addEventListener(`bufferedamountlow`,i,{once:!0})}catch{}}}))}async _saveInboundFile(t,n,i){try{let a=await e(),o=n,s=1;for(;await r(a,t,o);){let e=n.lastIndexOf(`.`);if(e>0&&e<n.length-1){let t=n.substring(0,e),r=n.substring(e);o=`${t} (${s})${r}`}else o=`${n} (${s})`;s++}o!==n&&this._inboundRemap.set(n,o),await c(a,t,o,i);try{let{orchestratorStore:e}=await import(`./orchestrator-Li1UAsv7.js`).then(e=>e.n);e.activeGroupId===t&&await e.loadFiles(a)}catch{}}catch(e){console.error(`PeerJsChannel: failed to write inbound file bytes`,e)}}_updateConnectedPeersSignal(){this.connectedPeersSignal.set(Array.from(this.connections.keys()))}_waitForOpen(e){return e.open?Promise.resolve():new Promise((t,n)=>{let r=setTimeout(()=>{n(/* @__PURE__ */ Error(`Connection open timeout (5s)`))},5e3);e.on(`open`,()=>{clearTimeout(r),t()}),e.on(`error`,e=>{clearTimeout(r),n(e)})})}async _processInboundA2AEnvelope(e,t,r,i){let a=`peer:${e}`,o=``,s=[],c=[],l;for(let e of t)if(e.kind===`text`&&typeof e.text==`string`)o+=e.text;else if(e.kind===`file`){let t=e.name||`attachment`,n=this._inboundSavePromises.get(t);if(n)try{await n}catch{}finally{this._inboundSavePromises.delete(t)}if(this._inboundRemap.has(t)){let e=this._inboundRemap.get(t),n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);o=o.replace(RegExp(`(!?\\[.*?\\])\\(${n}\\)`,`g`),`$1(${e})`),this._inboundRemap.delete(t),t=e}let r=t.split(`/`).pop()||`attachment`;s.push({fileName:r,mimeType:e.mimeType,path:t,size:e.size||0})}else e.kind===`a2ui`&&e.envelope?c.push(e.envelope):e.kind===`a2ui-action`&&e.action&&(l=e.action);o=o.trim(),(o||s.length!==0||c.length!==0||l)&&this.messageCallback?.({id:n(),groupId:a,sender:e,content:o,timestamp:Date.now(),channel:`peerjs`,attachments:s.length>0?s:void 0,a2uiEnvelopes:c.length>0?c:void 0,a2uiAction:l,taskId:r,contextId:i})}};function R(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r,i=e;for(;(r=n.exec(e))!==null;){let e=r[1],n=z((r[2]||``).trim());n&&t.push({alt:e,path:n})}return{remainingText:i,attachments:t}}function z(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}export{u as a,f as i,M as n,b as r,L as t};
|
package/dist/public/{process-peer-query-param-BL2k0Hu-.js → process-peer-query-param-DQIgr3KL.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./orchestrator-
|
|
1
|
+
import{t as e}from"./orchestrator-Li1UAsv7.js";import{t}from"./ulid-BSJxYh6W.js";import{a as n,r}from"./toast-CtIuHprH.js";import{c as i,d as a}from"./channel-DIpDQekL.js";import{t as o}from"./configure-peer-js-DV1rqvFX.js";import{t as s}from"./shadow-claw-Bg9AQ5x_.js";async function c(c,l,u,d){if(!u)return;let f=new URL(window.location?.href||`http://localhost/`),p=f.searchParams.get(`peer`);if(!p)return;let m=p.trim();if(m)try{let r=i(d),p=r.myPeerId;p||=t().toLowerCase();let h=new Set(r.trustedPeerIds);h.add(m),await o(d,u,p,Array.from(h),r.serverHost,r.serverPort,r.serverPath,r.serverSecure),r.enabled||await a(d,u,`peerjs`,!0);let g=await e.ensurePeerConversation(u,m);await e.switchConversation(u,g),s(c,l,u,e,`chat`),f.searchParams.delete(`peer`);let _=`${f.pathname}${f.search}${f.hash}`;window.history.replaceState({},``,_||`/`),n(`Connected to Peer: ${m.substring(0,8)}`)}catch(e){let t=e instanceof Error?e.message:String(e);r(`Failed to process peer parameter: ${t}`,6e3)}}export{c as processPeerQueryParam};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{t as e}from"./write-group-file-
|
|
1
|
+
import{t as e}from"./write-group-file-R67DjJ-q.js";import{a as t,r as n}from"./toast-CtIuHprH.js";import{t as r}from"./write-group-file-bytes-A8kB7lvO.js";import{t as i}from"./shadow-claw-Bg9AQ5x_.js";const a=`pendingShares`;function o(e){return{id:typeof e?.id==`string`?e.id:``,createdAt:typeof e?.createdAt==`number`?e.createdAt:0,title:typeof e?.title==`string`?e.title:``,text:typeof e?.text==`string`?e.text:``,url:typeof e?.url==`string`?e.url:``,fileName:typeof e?.fileName==`string`?e.fileName:``,fileType:typeof e?.fileType==`string`?e.fileType:``,fileBytes:e?.fileBytes instanceof ArrayBuffer?e.fileBytes:null}}async function s(e){return!e||typeof e.transaction!=`function`?[]:new Promise((t,n)=>{let r;try{r=e.transaction(a,`readwrite`)}catch(e){if(e instanceof DOMException&&e.name===`NotFoundError`){t([]);return}n(e);return}let i=r.objectStore(a),s=i.getAll();s.onerror=()=>{n(s.error||/* @__PURE__ */ Error(`Failed to read pending shares`))},s.onsuccess=()=>{let e=Array.isArray(s.result)?s.result.map(o).filter(e=>typeof e.id==`string`&&e.id.length>0).sort((e,t)=>e.createdAt-t.createdAt):[],r=i.clear();r.onerror=()=>{n(r.error||/* @__PURE__ */ Error(`Failed to clear pending shares`))},r.onsuccess=()=>{t(e)}},r.onabort=()=>{n(r.error||/* @__PURE__ */ Error(`Pending share transaction aborted`))}})}function c(e){let t=[`# Shared Content`,``];return e.title&&t.push(`Title: ${e.title}`),e.url&&t.push(`URL: ${e.url}`),e.text&&t.push(``,e.text),t.join(`
|
|
2
2
|
`).trim()+`
|
|
3
3
|
`}async function l(e,t){let n=/* @__PURE__ */ new Date,r=`Shared Files ${`${String(n.getFullYear())}-${String(n.getMonth()+1).padStart(2,`0`)}-${String(n.getDate()).padStart(2,`0`)}`}`,i=t.groups.find(e=>e.name===r);return i?(await t.switchConversation(e,i.groupId),i.groupId):(await t.createConversation(e,r)).groupId}function u(e,t){return(e.replace(/\\/g,`/`).split(`/`).filter(Boolean).pop()||``).replace(/\s+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`-`).replace(/-+/g,`-`).replace(/^-+|-+$/g,``)||`${t}.txt`}async function d(a,o,d,f,p,m,h){if(!m)return;let g=await s(m);if(g.length!==0)try{let n=await l(m,f),s=[];for(let t=0;t<g.length;t++){let i=g[t],a=`shared-${Date.now()}-${t+1}`;if(i.fileBytes instanceof ArrayBuffer){let e=u(i.fileName||(i.fileType===`application/pdf`?`${a}.pdf`:`${a}.bin`),a);await r(m,n,e,new Uint8Array(i.fileBytes)),s.push(e);continue}let o=u(i.fileName||`${a}.md`,a),l=c(i);await e(m,n,o,l),s.push(o)}await f.loadFiles(m),i(o,d,m,f,`files`),s.length>0&&await p.openFile(m,s[0],n),t(`Imported ${s.length} shared item${s.length===1?``:`s`}.`);let _=h;if(_.searchParams.has(`share-target`)){_.searchParams.delete(`share-target`);let e=`${_.pathname}${_.search}${_.hash}`;a.history.replaceState({},``,e||`/`)}}catch(e){let t=e instanceof Error?e.message:String(e);n(`Failed to import shared content: ${t}`,6e3)}}export{d as processPendingSharedPayloads};
|
package/dist/public/{process-room-query-param-DM0QCq3_.js → process-room-query-param-F-XnIVoZ.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./ulid-BSJxYh6W.js";import{a as t,r as n}from"./toast-CtIuHprH.js";import{l as r}from"./transformers-
|
|
1
|
+
import{t as e}from"./ulid-BSJxYh6W.js";import{a as t,r as n}from"./toast-CtIuHprH.js";import{l as r}from"./transformers-CQ9ss9rD.js";import{c as i,d as a}from"./channel-DIpDQekL.js";import{t as o}from"./configure-peer-js-DV1rqvFX.js";import{t as s}from"./shadow-claw-Bg9AQ5x_.js";async function c(c,l,u,d,f,p){if(!d)return;let m=new URL(window.location?.href||`http://localhost/`),h=(m.searchParams.get(`room`)||``).trim(),g=(m.searchParams.get(`host`)||``).trim(),_=(m.searchParams.get(`name`)||``).trim()||`Room`;if(h&&g)try{let n=i(f),v=n.myPeerId;v||=e().toLowerCase();let y=new Set(n.trustedPeerIds);y.add(g),await o(f,d,v,Array.from(y),n.serverHost,n.serverPort,n.serverPath,n.serverSecure),n.enabled||await a(f,d,`peerjs`,!0),r(f,h,g,_),await p.switchConversation(d,`room:${h}`),s(l,u,d,p,`chat`),m.searchParams.delete(`room`),m.searchParams.delete(`host`),m.searchParams.delete(`name`);let b=`${m.pathname}${m.search}${m.hash}`;c.history.replaceState({},``,b||`/`),t(`Joined room "${_}"`)}catch(e){let t=e instanceof Error?e.message:String(e);n(`Failed to join room: ${t}`,6e3)}}export{c as processRoomQueryParam};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{C as e,I as t,O as n,P as r,et as i,r as a,y as o}from"./config-C16fFWtP.js";import{t as s}from"./get-config-Bkvl__ZS.js";import{t as c}from"./set-config-DSiuMe0k.js";import{t as l}from"./tools-D-52Zmfc.js";function u(){let e=globalThis.LanguageModel;return!e||typeof e!=`function`||typeof e.availability!=`function`||typeof e.create!=`function`?null:e}function d(){return!!u()}async function f(e){return await e.getApiKey()||void 0}async function p(e){return await e.getApiKey()||``}function m(e){return{mode:e.llamafileMode,host:e.llamafileHost,port:e.llamafilePort,offline:e.llamafileOffline}}function h(e){return{authMode:e.bedrockAuthMode,profile:e.bedrockProfileFallback,region:e.bedrockRegionFallback}}function g(){return Object.entries(e).map(([e,t])=>({id:e,name:t.name,...!t.modelsUrl&&{models:Array.isArray(t.models)&&t.models.length>0?t.models:[t.defaultModel]},...t.modelsUrl&&{modelsUrl:t.modelsUrl},...t.headers&&{headers:t.headers},...t.apiKeyHeader&&{apiKeyHeader:t.apiKeyHeader},...t.apiKeyHeaderFormat&&{apiKeyHeaderFormat:t.apiKeyHeaderFormat},...typeof t.requiresApiKey==`boolean`&&{requiresApiKey:t.requiresApiKey}}))}function _(e){let t=typeof e.reasoningEffort==`string`?e.reasoningEffort.trim().toLowerCase():`none`;if(t&&t!==`none`)return{effort:t}}function v(e,t,n=``,r){if(t===`llamafile`){let t=r?.llamafile,i={"x-llamafile-mode":t?.mode===`server`||t?.mode===`cli`?t.mode:e.llamafileMode,"x-llamafile-host":t?.host||e.llamafileHost,"x-llamafile-port":String(t?.port||e.llamafilePort),"x-llamafile-offline":t?.offline??e.llamafileOffline?`true`:`false`};return n&&(i[`x-shadowclaw-request-id`]=n),i}if(t===`bedrock_proxy`){let t=r?.bedrock_proxy,n={};return(t?.region||e.bedrockRegionFallback)&&(n[`x-bedrock-region`]=t?.region||e.bedrockRegionFallback),(t?.profile||e.bedrockProfileFallback)&&(n[`x-bedrock-profile`]=t?.profile||e.bedrockProfileFallback),n[`x-bedrock-auth-mode`]=t?.authMode||e.bedrockAuthMode,n}return{}}function y(e){e.providerConfig?.id===`llamafile`&&(e.providerConfig={...e.providerConfig,headers:{...e.providerConfig.headers||{},"x-llamafile-mode":e.llamafileMode,"x-llamafile-host":e.llamafileHost,"x-llamafile-port":String(e.llamafilePort),"x-llamafile-offline":e.llamafileOffline?`true`:`false`}})}function b(e){e.providerConfig?.id===`mesh-llm`&&(e.providerConfig={...e.providerConfig,headers:{...e.providerConfig.headers||{},"x-mesh-llm-host":e.meshLlmHost}})}function x(e,n){if(n&&e.inFlightEffectiveProviderByGroup){let t=e.inFlightEffectiveProviderByGroup.get(n);if(t?.providerId===`transformers_js_local`){let e=t.providerConfig.baseUrl||``;if(e.includes(`/chat/completions`))return e.replace(`/chat/completions`,`/status`)}}let r=e.providerConfig;if(r&&(!r.id||r.id===`transformers_js_local`)){let e=r.baseUrl||``;if(e.includes(`/chat/completions`))return e.replace(`/chat/completions`,`/status`)}let i=t(`transformers_js_local`)?.baseUrl||``;return i.includes(`/chat/completions`)?i.replace(`/chat/completions`,`/status`):`http://localhost:8888/transformers-js-proxy/status`}async function S(e,t,r,i=c){e.assistantName=r,e.triggerPattern=n(r),await i(t,a.ASSISTANT_NAME,r)}async function C(e,t,n,r=c){let i=typeof n.region==`string`?n.region.trim():``,o=typeof n.profile==`string`?n.profile.trim():``,s=n.authMode===`sso`?`sso`:`provider_chain`;e.bedrockRegionFallback=i,e.bedrockProfileFallback=o,e.bedrockAuthMode=s,await r(t,a.BEDROCK_REGION_FALLBACK,i),await r(t,a.BEDROCK_PROFILE_FALLBACK,o),await r(t,a.BEDROCK_AUTH_MODE,s)}async function w(e,t,n,r=c){e.llamafileMode=n.mode,e.llamafileHost=n.host,e.llamafilePort=n.port,e.llamafileOffline=n.offline,await r(t,a.LLAMAFILE_MODE,n.mode),await r(t,a.LLAMAFILE_HOST,n.host),await r(t,a.LLAMAFILE_PORT,String(n.port)),await r(t,a.LLAMAFILE_OFFLINE,n.offline?`true`:`false`),y(e)}async function T(e,t,n,r=c){e.meshLlmHost=n.host,await r(t,a.MESH_LLM_HOST,n.host),b(e)}async function E(e,t,n,i=c){e.model=n;let o=n;e.provider===`prompt_api`&&!d()&&(n===`browser-built-in`||!n)&&(o=await s(t,a.PROMPT_API_FALLBACK_MODEL)||`onnx-community/Qwen3-0.6B-ONNX`),e.maxTokens=r(o),await i(t,a.MODEL,n),await k(e,t)}async function D(e,t,n,r=c){e.peerjsMyAlias=n.trim(),await r(t,a.PEERJS_MY_ALIAS,e.peerjsMyAlias)}async function O(e,t,n,r=c){e.peerjsPeerAliases={...n},await r(t,a.PEERJS_PEER_ALIASES,JSON.stringify(e.peerjsPeerAliases))}async function k(e,t){if(!l.activeProfileId&&l.enabledToolNames.size===0)return;let n=l.findProfilesForProvider(e.provider,e.model);if(n.length===0)return;let r=n.find(t=>t.providerId===e.provider&&t.model===e.model);if(r){await l.activateProfile(t,r.id);return}let i=n.find(t=>t.providerId===e.provider&&!t.model);i&&await l.activateProfile(t,i.id)}async function A(e,n,o,l,u=c){let f=t(o);if(!f)throw Error(`Unknown provider: ${o}`);e.provider=o,e.providerConfig=f,e.model=f.defaultModel,y(e),b(e),await l.loadApiKeyForProvider(n,o),await i.fetchModelInfo(f,await l.getApiKeyForHeaders()||void 0,v(e,o));let p=e.model;o===`prompt_api`&&!d()&&(e.model===`browser-built-in`||!e.model)&&(p=await s(n,a.PROMPT_API_FALLBACK_MODEL)||`onnx-community/Qwen3-0.6B-ONNX`),e.maxTokens=r(p),await u(n,a.PROVIDER,o),await u(n,a.MODEL,e.model),await k(e,n)}async function j(e,t,n,r){try{let i=x(e,n),a=await fetch(i,{headers:{Accept:`application/json`},method:`GET`});if(!a.ok)return;let o=await a.json(),s=Number(o?.progress),c=Number.isFinite(s)&&s>1?Math.max(0,Math.min(1,s/100)):Number.isFinite(s)?Math.max(0,Math.min(1,s)):null,l={groupId:n,message:typeof o?.message==`string`&&o.message?o.message:void 0,progress:c,status:o?.status===`done`||o?.status===`error`?o.status:`running`};t.emit(`model-download-progress`,l),(l.status===`done`||l.status===`error`)&&r(n)}catch{}}function M(e,t,n){N(e,n),t.emit(`model-download-progress`,{groupId:n,message:`Preparing local model download...`,progress:null,status:`running`}),j(e,t,n,t=>N(e,t));let r=setInterval(()=>{j(e,t,n,t=>N(e,t))},1e3);e.transformersProgressPollers.set(n,r)}function N(e,t){let n=e.transformersProgressPollers.get(t);typeof n==`number`&&(clearInterval(n),e.transformersProgressPollers.delete(t))}async function P(e){try{await fetch(o.replace(`/chat/completions`,`/cancel`),{body:JSON.stringify({requestId:e}),headers:{"Content-Type":`application/json`,"x-shadowclaw-request-id":e},keepalive:!0,method:`POST`})}catch{}}export{d as S,O as _,p as a,N as b,m as c,S as d,C as f,D as g,E as h,f as i,v as l,T as m,b as n,g as o,w as p,P as r,h as s,y as t,_ as u,A as v,u as x,M as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./config-
|
|
1
|
+
import{r as e}from"./config-C16fFWtP.js";import{n as t}from"./db-BUuJo1Gf.js";import{t as n}from"./get-config-Bkvl__ZS.js";import{t as r}from"./get-or-create-subscriber-id-jVHnQfbr.js";async function i(r){let i=await t(),a=await n(i,e.PUSH_PROXY_URL);if(!a&&typeof localStorage<`u`)try{a=localStorage.getItem(e.PUSH_PROXY_URL)||void 0}catch{}if(!a)return r;let o=r.startsWith(`/`)?r:`/${r}`;return`${a.endsWith(`/`)?a.slice(0,-1):a}${o}`}function a(e,t={}){let n={...t};try{let t=typeof location<`u`?location.origin:`http://127.0.0.1:8888`,r=new URL(e,t).hostname.toLowerCase();r===`localhost`||r===`127.0.0.1`||r===`::1`||r===`[::1]`?n.targetAddressSpace=`loopback`:(/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(r)||!r.includes(`.`)||r.endsWith(`.local`)||r.endsWith(`.lan`)||r.endsWith(`.home`)||r.endsWith(`.internal`))&&(n.targetAddressSpace=`private`)}catch{}return n}function o(e){let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t);return Uint8Array.from([...n].map(e=>e.charCodeAt(0)))}async function s(){let e=await i(`/push/vapid-public-key`);return(await(await fetch(e,a(e))).json()).publicKey}async function c(n,c,l){let u=await navigator.serviceWorker.ready,d=await s(),f=await u.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:o(d)}),p=n||typeof localStorage<`u`&&localStorage.getItem(e.CONTROL_PLANE_CLIENT_ID)||void 0,m=c,h=l;if(!p||!m)try{let e=await import(`./init-control-plane-Ctz7FI8M.js`);!p&&typeof e.getOrCreateControlPlaneClientId==`function`&&(p=e.getOrCreateControlPlaneClientId()),!m&&typeof e.detectDeviceLabel==`function`&&(m=e.detectDeviceLabel())}catch{}if(!h)try{let e=await Promise.race([t(),new Promise(e=>setTimeout(()=>e(null),500))]);e&&(h=await r(e))}catch{}let g=typeof f.toJSON==`function`?f.toJSON():JSON.parse(JSON.stringify(f)),_=await i(`/push/subscribe`);return await fetch(_,a(_,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...g,...p?{clientId:p}:{},...m?{deviceLabel:m}:{},...h?{subscriberId:h}:{}})})),f}async function l(n){if(typeof navigator<`u`&&navigator.serviceWorker)try{let o=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!o)return;let s,c,l=n;typeof localStorage<`u`&&(s=localStorage.getItem(e.CONTROL_PLANE_CLIENT_ID)||void 0);try{let e=await import(`./init-control-plane-Ctz7FI8M.js`);!s&&typeof e.getOrCreateControlPlaneClientId==`function`&&(s=e.getOrCreateControlPlaneClientId()),typeof e.detectDeviceLabel==`function`&&(c=e.detectDeviceLabel())}catch{}if(!l)try{let e=await Promise.race([t(),new Promise(e=>setTimeout(()=>e(null),500))]);e&&(l=await r(e))}catch{}let u=typeof o.toJSON==`function`?o.toJSON():JSON.parse(JSON.stringify(o)),d=await i(`/push/subscribe`);await fetch(d,a(d,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...u,...s?{clientId:s}:{},...c?{deviceLabel:c}:{},...l?{subscriberId:l}:{}})}))}catch{}}async function u(){let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;let{endpoint:t}=e;await e.unsubscribe();let n=await i(`/push/subscribe`);await fetch(n,a(n,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({endpoint:t})}))}async function d(){return(await navigator.serviceWorker.ready).pushManager.getSubscription()}export{l as a,c as i,a as n,u as o,i as r,d as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./get-config-Bkvl__ZS.js";import{T as t,w as n}from"./orchestrator-
|
|
1
|
+
import{t as e}from"./get-config-Bkvl__ZS.js";import{T as t,w as n}from"./orchestrator-Li1UAsv7.js";import{t as r}from"./set-config-DSiuMe0k.js";const i=`room_metadata`,a=`room:`;function o(e){return`${a}${e}`}function s(e){return e.startsWith(`room:`)?e.slice(5):e}async function c(t){let n=await e(t,i);if(!n)return[];try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}async function l(e,t){await r(e,i,JSON.stringify(t))}async function u(e,t){let n=await c(e),r=n.findIndex(e=>e.roomId===t.roomId);r>=0?n[r]=t:n.push(t),await l(e,n),await d(e,t)}async function d(e,r){let i=await t(e),s=o(r.roomId);i.some(e=>e.groupId===s)||await n(e,r.name,a,r.roomId)}async function f(e,t){await l(e,(await c(e)).filter(e=>e.roomId!==t))}export{s as a,o as i,f as n,u as o,c as r,a as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
try{self[`workbox:window:7.4.0`]&&_()}catch{}function e(e,t){return new Promise((function(n){var r=new MessageChannel;r.port1.onmessage=function(e){n(e.data)},e.postMessage(t,[r.port2])}))}function t(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function n(e,t,n){return t&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,a(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function r(e,n){var r=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,n){if(e){if(typeof e==`string`)return t(e,n);var r={}.toString.call(e).slice(8,-1);return r===`Object`&&e.constructor&&(r=e.constructor.name),r===`Map`||r===`Set`?Array.from(e):r===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}}(e))||n){r&&(e=r);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
2
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function i(e,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},i(e,t)}function a(e){var t=function(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return String(e)}(e,`string`);return typeof t==`symbol`?t:t+``}try{self[`workbox:core:7.4.0`]&&_()}catch{}var o=function(){var e=this;this.promise=new Promise((function(t,n){e.resolve=t,e.reject=n}))};function s(e,t){var n=location.href;return new URL(e,n).href===new URL(t,n).href}var c=function(e,t){this.type=e,Object.assign(this,t)};function l(e,t,n){return e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e}function u(){}var d={type:`SKIP_WAITING`};function f(e,t){return e&&e.then?e.then(u):Promise.resolve()}var p=function(t){function r(e,n){var r,i;return n===void 0&&(n={}),(r=t.call(this)||this).nn={},r.tn=0,r.rn=new o,r.en=new o,r.on=new o,r.un=0,r.an=/* @__PURE__ */ new Set,r.cn=function(){var e=r.fn,t=e.installing;r.tn>0||!s(t.scriptURL,r.sn.toString())||performance.now()>r.un+6e4?(r.vn=t,e.removeEventListener(`updatefound`,r.cn)):(r.hn=t,r.an.add(t),r.rn.resolve(t)),++r.tn,t.addEventListener(`statechange`,r.ln)},r.ln=function(e){var t=r.fn,n=e.target,i=n.state,a=n===r.vn,o={sw:n,isExternal:a,originalEvent:e};!a&&r.mn&&(o.isUpdate=!0),r.dispatchEvent(new c(i,o)),i===`installed`?r.wn=self.setTimeout((function(){i===`installed`&&t.waiting===n&&r.dispatchEvent(new c(`waiting`,o))}),200):i===`activating`&&(clearTimeout(r.wn),a||r.en.resolve(n))},r.yn=function(e){var t=r.hn,n=t!==navigator.serviceWorker.controller;r.dispatchEvent(new c(`controlling`,{isExternal:n,originalEvent:e,sw:t,isUpdate:r.mn})),n||r.on.resolve(t)},r.gn=(i=function(e){var t=e.data,n=e.ports,i=e.source;return l(r.getSW(),(function(){r.an.has(i)&&r.dispatchEvent(new c(`message`,{data:t,originalEvent:e,ports:n,sw:i}))}))},function(){var e=[...arguments];try{return Promise.resolve(i.apply(this,e))}catch(e){return Promise.reject(e)}}),r.sn=e,r.nn=n,navigator.serviceWorker.addEventListener(`message`,r.gn),r}var a,u=t;(a=r).prototype=Object.create(u.prototype),a.prototype.constructor=a,i(a,u);var p=r.prototype;return p.register=function(e){var t=(e===void 0?{}:e).immediate,n=t!==void 0&&t;try{var r=this;return l(function(e,t){var n=e();return n&&n.then?n.then(t):t(n)}((function(){if(!n&&document.readyState!==`complete`)return f(new Promise((function(e){return window.addEventListener(`load`,e)})))}),(function(){return r.mn=!!navigator.serviceWorker.controller,r.dn=r.pn(),l(r.bn(),(function(e){r.fn=e,r.dn&&(r.hn=r.dn,r.en.resolve(r.dn),r.on.resolve(r.dn),r.dn.addEventListener(`statechange`,r.ln,{once:!0}));var t=r.fn.waiting;return t&&s(t.scriptURL,r.sn.toString())&&(r.hn=t,Promise.resolve().then((function(){r.dispatchEvent(new c(`waiting`,{sw:t,wasWaitingBeforeRegister:!0}))})).then((function(){}))),r.hn&&(r.rn.resolve(r.hn),r.an.add(r.hn)),r.fn.addEventListener(`updatefound`,r.cn),navigator.serviceWorker.addEventListener(`controllerchange`,r.yn),r.fn}))})))}catch(e){return Promise.reject(e)}},p.update=function(){try{return this.fn?l(f(this.fn.update())):l()}catch(e){return Promise.reject(e)}},p.getSW=function(){return this.hn===void 0?this.rn.promise:Promise.resolve(this.hn)},p.messageSW=function(t){try{return l(this.getSW(),(function(n){return e(n,t)}))}catch(e){return Promise.reject(e)}},p.messageSkipWaiting=function(){this.fn&&this.fn.waiting&&e(this.fn.waiting,d)},p.pn=function(){var e=navigator.serviceWorker.controller;return e&&s(e.scriptURL,this.sn.toString())?e:void 0},p.bn=function(){try{var e=this;return l(function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}((function(){return l(navigator.serviceWorker.register(e.sn,e.nn),(function(t){return e.un=performance.now(),t}))}),(function(e){throw e})))}catch(e){return Promise.reject(e)}},n(r,[{key:`active`,get:function(){return this.en.promise}},{key:`controlling`,get:function(){return this.on.promise}}])}(function(){function e(){this.Pn=/* @__PURE__ */ new Map}var t=e.prototype;return t.addEventListener=function(e,t){this.jn(e).add(t)},t.removeEventListener=function(e,t){this.jn(e).delete(t)},t.dispatchEvent=function(e){e.target=this;for(var t,n=r(this.jn(e.type));!(t=n()).done;)(0,t.value)(e)},t.jn=function(e){return this.Pn.has(e)||this.Pn.set(e,/* @__PURE__ */ new Set),this.Pn.get(e)},e}());const m=`__shadowClawDefaultTrustedTypesPolicyState`,h=`default`,g=`shadowclaw-sandbox`;function v(){let e=globalThis;return e[m]||(e[m]={initialized:!1,policy:null}),e[m]}function y(){let e=v();if(e.initialized)return;let t=Reflect.get(globalThis,`trustedTypes`);if(t&&typeof t.createPolicy==`function`){e.initialized=!0;try{if(typeof t.getPolicy==`function`){let n=t.getPolicy(h);if(n){e.policy=n;return}}let n=!1;if(typeof t.getPolicyNames==`function`){let e=t.getPolicyNames();Array.isArray(e)&&e.includes(h)&&(n=!0)}if(n){if(typeof t.getPolicy==`function`){let n=t.getPolicy(g);if(n){e.policy=n;return}}e.policy=t.createPolicy(g,{createHTML:e=>e,createScriptURL:e=>e});return}e.policy=t.createPolicy(h,{createHTML:e=>e,createScriptURL:e=>e})}catch{typeof t.getPolicy==`function`&&(e.policy=t.getPolicy(h)??t.getPolicy(g)??null)}}}function b(e){y();let t=v().policy;return!t||typeof t.createScriptURL!=`function`?e:t.createScriptURL(e)}const x=`shadowclaw-oac-reload-attempted`,S=`shadowclaw-sw-update-intent`,C=3e4,w=`shadowclaw-sw-update-failure`;let T=!1,E=null;async function
|
|
2
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function i(e,t){return i=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},i(e,t)}function a(e){var t=function(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return String(e)}(e,`string`);return typeof t==`symbol`?t:t+``}try{self[`workbox:core:7.4.0`]&&_()}catch{}var o=function(){var e=this;this.promise=new Promise((function(t,n){e.resolve=t,e.reject=n}))};function s(e,t){var n=location.href;return new URL(e,n).href===new URL(t,n).href}var c=function(e,t){this.type=e,Object.assign(this,t)};function l(e,t,n){return e&&e.then||(e=Promise.resolve(e)),t?e.then(t):e}function u(){}var d={type:`SKIP_WAITING`};function f(e,t){return e&&e.then?e.then(u):Promise.resolve()}var p=function(t){function r(e,n){var r,i;return n===void 0&&(n={}),(r=t.call(this)||this).nn={},r.tn=0,r.rn=new o,r.en=new o,r.on=new o,r.un=0,r.an=/* @__PURE__ */ new Set,r.cn=function(){var e=r.fn,t=e.installing;r.tn>0||!s(t.scriptURL,r.sn.toString())||performance.now()>r.un+6e4?(r.vn=t,e.removeEventListener(`updatefound`,r.cn)):(r.hn=t,r.an.add(t),r.rn.resolve(t)),++r.tn,t.addEventListener(`statechange`,r.ln)},r.ln=function(e){var t=r.fn,n=e.target,i=n.state,a=n===r.vn,o={sw:n,isExternal:a,originalEvent:e};!a&&r.mn&&(o.isUpdate=!0),r.dispatchEvent(new c(i,o)),i===`installed`?r.wn=self.setTimeout((function(){i===`installed`&&t.waiting===n&&r.dispatchEvent(new c(`waiting`,o))}),200):i===`activating`&&(clearTimeout(r.wn),a||r.en.resolve(n))},r.yn=function(e){var t=r.hn,n=t!==navigator.serviceWorker.controller;r.dispatchEvent(new c(`controlling`,{isExternal:n,originalEvent:e,sw:t,isUpdate:r.mn})),n||r.on.resolve(t)},r.gn=(i=function(e){var t=e.data,n=e.ports,i=e.source;return l(r.getSW(),(function(){r.an.has(i)&&r.dispatchEvent(new c(`message`,{data:t,originalEvent:e,ports:n,sw:i}))}))},function(){var e=[...arguments];try{return Promise.resolve(i.apply(this,e))}catch(e){return Promise.reject(e)}}),r.sn=e,r.nn=n,navigator.serviceWorker.addEventListener(`message`,r.gn),r}var a,u=t;(a=r).prototype=Object.create(u.prototype),a.prototype.constructor=a,i(a,u);var p=r.prototype;return p.register=function(e){var t=(e===void 0?{}:e).immediate,n=t!==void 0&&t;try{var r=this;return l(function(e,t){var n=e();return n&&n.then?n.then(t):t(n)}((function(){if(!n&&document.readyState!==`complete`)return f(new Promise((function(e){return window.addEventListener(`load`,e)})))}),(function(){return r.mn=!!navigator.serviceWorker.controller,r.dn=r.pn(),l(r.bn(),(function(e){r.fn=e,r.dn&&(r.hn=r.dn,r.en.resolve(r.dn),r.on.resolve(r.dn),r.dn.addEventListener(`statechange`,r.ln,{once:!0}));var t=r.fn.waiting;return t&&s(t.scriptURL,r.sn.toString())&&(r.hn=t,Promise.resolve().then((function(){r.dispatchEvent(new c(`waiting`,{sw:t,wasWaitingBeforeRegister:!0}))})).then((function(){}))),r.hn&&(r.rn.resolve(r.hn),r.an.add(r.hn)),r.fn.addEventListener(`updatefound`,r.cn),navigator.serviceWorker.addEventListener(`controllerchange`,r.yn),r.fn}))})))}catch(e){return Promise.reject(e)}},p.update=function(){try{return this.fn?l(f(this.fn.update())):l()}catch(e){return Promise.reject(e)}},p.getSW=function(){return this.hn===void 0?this.rn.promise:Promise.resolve(this.hn)},p.messageSW=function(t){try{return l(this.getSW(),(function(n){return e(n,t)}))}catch(e){return Promise.reject(e)}},p.messageSkipWaiting=function(){this.fn&&this.fn.waiting&&e(this.fn.waiting,d)},p.pn=function(){var e=navigator.serviceWorker.controller;return e&&s(e.scriptURL,this.sn.toString())?e:void 0},p.bn=function(){try{var e=this;return l(function(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}((function(){return l(navigator.serviceWorker.register(e.sn,e.nn),(function(t){return e.un=performance.now(),t}))}),(function(e){throw e})))}catch(e){return Promise.reject(e)}},n(r,[{key:`active`,get:function(){return this.en.promise}},{key:`controlling`,get:function(){return this.on.promise}}])}(function(){function e(){this.Pn=/* @__PURE__ */ new Map}var t=e.prototype;return t.addEventListener=function(e,t){this.jn(e).add(t)},t.removeEventListener=function(e,t){this.jn(e).delete(t)},t.dispatchEvent=function(e){e.target=this;for(var t,n=r(this.jn(e.type));!(t=n()).done;)(0,t.value)(e)},t.jn=function(e){return this.Pn.has(e)||this.Pn.set(e,/* @__PURE__ */ new Set),this.Pn.get(e)},e}());const m=`__shadowClawDefaultTrustedTypesPolicyState`,h=`default`,g=`shadowclaw-sandbox`;function v(){let e=globalThis;return e[m]||(e[m]={initialized:!1,policy:null}),e[m]}function y(){let e=v();if(e.initialized)return;let t=Reflect.get(globalThis,`trustedTypes`);if(t&&typeof t.createPolicy==`function`){e.initialized=!0;try{if(typeof t.getPolicy==`function`){let n=t.getPolicy(h);if(n){e.policy=n;return}}let n=!1;if(typeof t.getPolicyNames==`function`){let e=t.getPolicyNames();Array.isArray(e)&&e.includes(h)&&(n=!0)}if(n){if(typeof t.getPolicy==`function`){let n=t.getPolicy(g);if(n){e.policy=n;return}}e.policy=t.createPolicy(g,{createHTML:e=>e,createScriptURL:e=>e});return}e.policy=t.createPolicy(h,{createHTML:e=>e,createScriptURL:e=>e})}catch{typeof t.getPolicy==`function`&&(e.policy=t.getPolicy(h)??t.getPolicy(g)??null)}}}function b(e){y();let t=v().policy;return!t||typeof t.createScriptURL!=`function`?e:t.createScriptURL(e)}const x=`shadowclaw-oac-reload-attempted`,S=`shadowclaw-sw-update-intent`,C=3e4,w=`shadowclaw-sw-update-failure`;let T=!1,E=!1,D=!1,O=0,k=0,A=!1,j=!1,M=null;async function N(e=5e3){let t=Date.now();for(;Date.now()-t<e;){let e=document.querySelector(`shadow-claw`);if(e&&typeof e.requestDialog==`function`)return e;await new Promise(e=>{globalThis.setTimeout(e,50)})}return null}async function P(){let e=await N();return e?.requestDialog?await e.requestDialog({title:`Update Available`,message:`A new version of ShadowClaw is ready. Reload now to apply the update?`,confirmLabel:`Reload now`,cancelLabel:`Later`}):null}async function F(){let e=await N();e?.requestDialog&&await e.requestDialog({title:`Update Failed`,message:`The app update failed to install automatically. Please try restarting your browser to complete the update.`,confirmLabel:`OK`}),console.warn(`[ShadowClaw] Service worker update failed. Please restart your browser to complete the update.`)}function I(){try{let e=globalThis.sessionStorage?.getItem(S);if(!e)return null;let t=JSON.parse(e);return typeof t.startedAt!=`number`||typeof t.fallbackReloadAttempts!=`number`?null:{startedAt:t.startedAt,fallbackReloadAttempts:t.fallbackReloadAttempts}}catch{return null}}function L(e){try{globalThis.sessionStorage?.setItem(S,JSON.stringify(e))}catch{}}function R(){try{globalThis.sessionStorage?.removeItem(S)}catch{}}function z(){let e=I();return e?Date.now()-e.startedAt<=C||(R(),!1):!1}function B(){U(),L({startedAt:Date.now(),fallbackReloadAttempts:0})}function V(){try{let e=globalThis.sessionStorage?.getItem(w);if(!e)return null;let t=JSON.parse(e);return typeof t.failedAt==`number`?{failedAt:t.failedAt}:null}catch{return null}}function H(e){try{globalThis.sessionStorage?.setItem(w,JSON.stringify(e))}catch{}}function U(){try{globalThis.sessionStorage?.removeItem(w)}catch{}}function W(){let e=V();return e?Date.now()-e.failedAt<=3e5||(U(),!1):!1}function G(){R(),H({failedAt:Date.now()})}function K(){if(T)return;T=!0,M!==null&&(globalThis.clearTimeout(M),M=null);let e=globalThis.location;typeof e?.reload==`function`&&e.reload()}async function q(){if(T||M!==null)return;let e=I();e&&(Date.now()-e.startedAt>C?R():e.fallbackReloadAttempts>=2?(G(),await F()):(L({...e,fallbackReloadAttempts:e.fallbackReloadAttempts+1}),M=globalThis.setTimeout(()=>{K()},3e3)))}async function J(e){e.messageSkipWaiting(),await q()}function Y(){return z()}function X(){if(globalThis.originAgentCluster!==!1)return!1;let e=globalThis.location?.protocol;if(e!==`http:`&&e!==`https:`)return!1;try{return!globalThis.sessionStorage?.getItem(x)}catch{return!1}}function ee(){try{globalThis.sessionStorage?.setItem(x,`1`)}catch{return}K()}function Z(){let e=Y();R(),U(),e?K():j?te():X()&&ee()}async function te(){if(!(A||T)){A=!0;try{await(await N())?.requestDialog?.({title:`Update Installed`,message:`A new version of ShadowClaw was installed. Reload now to use it?`,confirmLabel:`Reload now`,cancelLabel:`Later`})&&K()}finally{A=!1}}}async function Q(e){if(!(!E||D||Date.now()<O)&&!W()){if(z())await J(e);else{D=!0;try{let t=await P();if(t===null)return;t?(B(),await J(e)):O=Date.now()+9e5}finally{D=!1}}}}async function $(e,t){if(!(t&&Date.now()-k<3e4)){k=Date.now();try{await e.update()}catch{}await Q(e)}}function ne(e){globalThis.setInterval(()=>$(e,!1),36e5),globalThis.addEventListener(`focus`,()=>$(e,!0)),document.addEventListener(`visibilitychange`,async()=>{document.visibilityState===`visible`&&await $(e,!0)})}try{if(typeof navigator<`u`&&`serviceWorker`in navigator&&navigator.serviceWorker){y();let e=new p(b(`service-worker.js`),{updateViaCache:`none`});j=!!navigator.serviceWorker.controller,e.addEventListener(`waiting`,async()=>{E=!0,await Q(e)}),e.addEventListener(`controlling`,()=>{Z()}),navigator.serviceWorker.addEventListener(`controllerchange`,()=>{Z()});let t=()=>{globalThis.setTimeout(()=>{e.register(),ne(e)},1e4)};document.readyState===`complete`?t():globalThis.addEventListener(`load`,t)}}catch{}export{K as reloadCurrentPage,Y as shouldReloadAfterControllerChange,X as shouldReloadForOriginAgentCluster};
|
|
@@ -36,4 +36,4 @@ const shadowClawImportScripts = (...urls) => {
|
|
|
36
36
|
|
|
37
37
|
shadowClawNativeImportScripts(...urls.map((url) => shadowClawServiceWorkerTrustedTypesPolicy.createScriptURL(url)));
|
|
38
38
|
};
|
|
39
|
-
if(!self.define){let e,s={};const r=(r,i)=>(r=new URL(r+".js",i).href,s[r]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=r,e.onload=s,document.head.appendChild(e)}else e=r,shadowClawImportScripts(r),s()}).then(()=>{let e=s[r];if(!e)throw new Error(`Module ${r} didn’t register its module`);return e}));self.define=(i,c)=>{const n=e||("document"in self?document.currentScript.src:"")||location.href;if(s[n])return;let o={};const a=e=>r(e,n),t={module:{uri:n},exports:o,require:a};s[n]=Promise.all(i.map(e=>t[e]||a(e))).then(e=>(c(...e),o))}}define(["./workbox-
|
|
39
|
+
if(!self.define){let e,s={};const r=(r,i)=>(r=new URL(r+".js",i).href,s[r]||new Promise(s=>{if("document"in self){const e=document.createElement("script");e.src=r,e.onload=s,document.head.appendChild(e)}else e=r,shadowClawImportScripts(r),s()}).then(()=>{let e=s[r];if(!e)throw new Error(`Module ${r} didn’t register its module`);return e}));self.define=(i,c)=>{const n=e||("document"in self?document.currentScript.src:"")||location.href;if(s[n])return;let o={};const a=e=>r(e,n),t={module:{uri:n},exports:o,require:a};s[n]=Promise.all(i.map(e=>t[e]||a(e))).then(e=>(c(...e),o))}}define(["./workbox-e4022e15"],function(e){"use strict";shadowClawImportScripts("service-worker/fetch-proxy.js","service-worker/push-handler.js","service-worker/share-target.js"),self.addEventListener("message",e=>{e.data&&"SKIP_WAITING"===e.data.type&&self.skipWaiting()}),e.clientsClaim(),e.precacheAndRoute([{url:"index.html",revision:"a27799162a2ba34a92e69cf63e66bcb0"},{url:"404.html",revision:"74bc1afc55391d3ff43b99e39de1c72f"},{url:"index.css",revision:"7fd4b888962af18e251009bc1fe8a6ac"},{url:"index.js",revision:"09cebc15d50bad3223a040a119f1a305"},{url:"theme-init.js",revision:"7b5ff0abc56d80fc359785d019c5f9cb"},{url:"manifest.json",revision:"62f8d50f4e8fd710cb66c883f94b1c48"},{url:"favicon.ico",revision:"58fff7908409f246a6228529f384802e"},{url:"assets/icons/96.png",revision:"f91548690416c59ceb56cdb99809b955"},{url:"assets/icons/72.png",revision:"cba8470097972bdbc5d9a06fe67bfcf2"},{url:"assets/icons/512.png",revision:"ec2a8f28b812a0c2665a04cb3c535aab"},{url:"assets/icons/48.png",revision:"29eb2f38df4d5a6385399a04d7bdef00"},{url:"assets/icons/192.png",revision:"bf98264d7a62a47542e577245a292b77"},{url:"assets/icons/180.png",revision:"69128cf857af09292bb06fac0df9938b"},{url:"assets/icons/152.png",revision:"645ae818149dc508cc6146d620120db2"},{url:"assets/icons/128.png",revision:"84678d51d243c104d0c85a4e909fd0a6"},{url:"assets/icons/1024.png",revision:"ae17c81b3b93137df1702de6a9fcdab6"}],{}),e.cleanupOutdatedCaches(),e.registerRoute(new e.NavigationRoute(e.createHandlerBoundToURL("index.html"),{allowlist:[/^\/$/,/^(?:\/[^/]+)*\/$/,/^(?:\/[^/]+)*\/(chat|files|pages|tasks|settings)(?:\/.*)?$/],denylist:[/\/assets\//,/\.(png|jpe?g|gif|webp|svg|ico|bmp|avif|mp4|webm|mp3|wav|ogg|pdf|zip|gz|tar|css|js|json|wasm)$/i]})),e.registerRoute(({url:e,sameOrigin:s})=>{if(e.pathname.startsWith("/assets/v86.9pfs/"))return!1;const r=e.hostname.toLowerCase();if("huggingface.co"===r||r.endsWith(".huggingface.co")||r.endsWith(".hf.co")||"hf.co"===r||"hf-mirror.com"===r||r.endsWith(".hf-mirror.com")||"cdnjs.cloudflare.com"===r||"esm.sh"===r||r.endsWith(".esm.sh")||"unpkg.com"===r||"cdn.jsdelivr.net"===r||r.endsWith(".jsdelivr.net")||"esm.run"===r||"openrouter.ai"===r||r.endsWith(".openrouter.ai")||"api.telegram.org"===r)return!1;if(e.pathname.startsWith("/api/control/"))return!1;const i=e.pathname.endsWith("/share/share-target.html"),c="/proxy"===e.pathname||e.pathname.startsWith("/git-proxy/")||i||e.pathname.startsWith("/push/")||e.pathname.startsWith("/schedule/")||e.pathname.startsWith("/telegram/");return(!("localhost"===r||"127.0.0.1"===r||"::1"===r||"[::1]"===r)||!c)&&("boolean"!=typeof s||s)},new e.NetworkFirst({cacheName:"shadow-claw-cache",plugins:[new e.ExpirationPlugin({maxAgeSeconds:31536e3})]}),"GET")});
|