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
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as isStaleHandleError, i as getOpfsRootDirName, n as getGroupDir, o as getStorageStatus, s as invalidateStorageRoot, t as parsePath } from "./parse-path-
|
|
2
|
-
import { c as writeFileHandle, l as writeOpfsPathViaWorker } from "./tools-
|
|
1
|
+
import { c as isStaleHandleError, i as getOpfsRootDirName, n as getGroupDir, o as getStorageStatus, s as invalidateStorageRoot, t as parsePath } from "./parse-path-BOHQP_IQ.js";
|
|
2
|
+
import { c as writeFileHandle, l as writeOpfsPathViaWorker } from "./tools-B8OJ4sMF.js";
|
|
3
3
|
|
|
4
4
|
//#region src/storage/write-group-file-bytes.ts
|
|
5
5
|
/**
|
|
@@ -38,4 +38,4 @@ async function writeGroupFileBytes(db, groupId, filePath, content) {
|
|
|
38
38
|
|
|
39
39
|
//#endregion
|
|
40
40
|
export { writeGroupFileBytes as t };
|
|
41
|
-
//# sourceMappingURL=write-group-file-bytes-
|
|
41
|
+
//# sourceMappingURL=write-group-file-bytes-CNT7DqOZ.js.map
|
package/dist/lib/{write-group-file-bytes-Ccn-VFUU.js.map → write-group-file-bytes-CNT7DqOZ.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write-group-file-bytes-
|
|
1
|
+
{"version":3,"file":"write-group-file-bytes-CNT7DqOZ.js","names":[],"sources":["../../src/storage/write-group-file-bytes.ts"],"sourcesContent":["import { getGroupDir } from \"./get-group-dir.js\";\nimport { parsePath } from \"./parse-path.js\";\nimport {\n getOpfsRootDirName,\n getStorageStatus,\n invalidateStorageRoot,\n isStaleHandleError,\n} from \"./storage.js\";\nimport {\n writeFileHandle,\n writeOpfsPathViaWorker,\n} from \"./write-file-handle.js\";\nimport type { ShadowClawDatabase } from \"../db/types.js\";\n\n/**\n * Write binary content to a file in a group's workspace.\n * Creates intermediate directories as needed.\n */\nexport async function writeGroupFileBytes(\n db: ShadowClawDatabase,\n groupId: string,\n filePath: string,\n content: Uint8Array,\n): Promise<void> {\n const { dirs, filename } = parsePath(filePath);\n\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n const groupDir = await getGroupDir(db, groupId);\n let dir = groupDir;\n for (const seg of dirs) {\n dir = await dir.getDirectoryHandle(seg, { create: true });\n }\n\n const fileHandle = await dir.getFileHandle(filename, { create: true });\n\n try {\n await writeFileHandle(fileHandle, content);\n\n return;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const needsOpfsWorkerFallback =\n message.includes(\"Writable file streams are not supported\") &&\n (await getStorageStatus(db)).type === \"opfs\";\n\n if (!needsOpfsWorkerFallback) {\n throw err;\n }\n }\n\n const safeId = groupId.replace(/:/g, \"-\");\n await writeOpfsPathViaWorker(\n [getOpfsRootDirName(), \"groups\", safeId, ...dirs, filename],\n content,\n );\n\n return;\n } catch (err) {\n if (attempt === 0 && isStaleHandleError(err)) {\n invalidateStorageRoot();\n\n continue;\n }\n\n throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;AAkBA,eAAsB,oBACpB,IACA,SACA,UACA,SACe;CACf,MAAM,EAAE,MAAM,aAAa,UAAU,QAAQ;CAE7C,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WACjC,IAAI;EAEF,IAAI,MAAM,MADa,YAAY,IAAI,OAAO;EAE9C,KAAK,MAAM,OAAO,MAChB,MAAM,MAAM,IAAI,mBAAmB,KAAK,EAAE,QAAQ,KAAK,CAAC;EAG1D,MAAM,aAAa,MAAM,IAAI,cAAc,UAAU,EAAE,QAAQ,KAAK,CAAC;EAErE,IAAI;GACF,MAAM,gBAAgB,YAAY,OAAO;GAEzC;EACF,SAAS,KAAK;GAMZ,IAAI,GALY,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAEtD,CAAC,SAAS,yCAAyC,MACzD,MAAM,iBAAiB,EAAE,EAAC,CAAE,SAAS,SAGtC,MAAM;EAEV;EAEA,MAAM,SAAS,QAAQ,QAAQ,MAAM,GAAG;EACxC,MAAM,uBACJ;GAAC,mBAAmB;GAAG;GAAU;GAAQ,GAAG;GAAM;EAAQ,GAC1D,OACF;EAEA;CACF,SAAS,KAAK;EACZ,IAAI,YAAY,KAAK,mBAAmB,GAAG,GAAG;GAC5C,sBAAsB;GAEtB;EACF;EAEA,MAAM;CACR;AAEJ"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://modelcontextprotocol.io/schemas/server-card/v1.json",
|
|
3
3
|
"name": "shadow-claw",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.60.0",
|
|
5
5
|
"description": "Multi-runtime AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.",
|
|
6
6
|
"title": "ShadowClaw MCP Server",
|
|
7
7
|
"websiteUrl": "https://xt-ml.github.io/shadow-claw/",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://modelcontextprotocol.io/schemas/server-card/v1.json",
|
|
3
3
|
"name": "shadow-claw",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.60.0",
|
|
5
5
|
"description": "Multi-runtime AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.",
|
|
6
6
|
"title": "ShadowClaw MCP Server",
|
|
7
7
|
"websiteUrl": "https://xt-ml.github.io/shadow-claw/",
|
package/dist/public/AGENTS.md
CHANGED
|
@@ -127,6 +127,7 @@ To prevent infinite execution loops, the system enforces a strict recursion guar
|
|
|
127
127
|
|
|
128
128
|
- **Service Worker Loopback Bypass:** The Service Worker fetch proxy (`src/service-worker/fetch-proxy-rules.ts`) unconditionally bypasses all loopback (`localhost`, `127.0.0.1`, `::1`, `[::1]`) and private IP ranges (`10.x`, `172.16-31.x`, `192.168.x`) so browser tabs hosted on static platforms (such as GitHub Pages or Cloudflare Pages) can connect directly to local servers without Service Worker interception.
|
|
129
129
|
- **Service Worker Multi-Cache Matching & Offline Navigation:** The Service Worker fetch proxy (`src/service-worker/fetch-proxy.ts`) implements `matchCacheEntry` across all CacheStorage caches with `ignoreSearch: true` so route requests match regardless of query parameters. `findCachedAppShell` inspects candidate root URLs, dynamically caches successful navigation responses in `"shadow-claw-cache"`, and falls back to `fetchAppShellWithOriginAgentCluster` on network errors, ensuring robust offline SPA navigation.
|
|
130
|
+
- **Service Worker Lifecycle & Update Dialog Flow:** In `src/service-worker/init.ts`, the Workbox service worker registers with `{ updateViaCache: "none" }` and is deferred by 10 seconds to prioritize main-thread startup. Periodic update checks run every hour (`SW_UPDATE_CHECK_INTERVAL_MS`), on window focus and visibility (`SW_UPDATE_CHECK_ON_FOCUS`, min 30-second gap `SW_UPDATE_CHECK_MIN_GAP_MS`), and whenever a worker enters the waiting state. The update confirmation dialog (`confirmServiceWorkerUpdate`) returns `null` when the UI bridge is not yet ready, enabling retry on subsequent checks instead of permanently dropping updates. When an update is deferred with "Later", reprompting backs off by 15 minutes (`SW_UPDATE_REPROMPT_INTERVAL_MS`). Workbox enables `cleanupOutdatedCaches: true`. New worker activations in other tabs prompt open tabs to reload via `controllerchange` ("Update Installed").
|
|
130
131
|
- **Client `targetAddressSpace` Signaling:** Outgoing client fetch requests targeting local or private network endpoints (`control-plane-client.ts`, `backup-controller.ts`, `push-client.ts`, `task.ts`, and `fetch-proxy.ts`) must supply `targetAddressSpace: 'loopback'` (or `'private'`) for Chromium Private Network Access (PNA) compliance.
|
|
131
132
|
- **Server PNA & Cross-Origin Headers:** Server endpoints set `Access-Control-Allow-Private-Network: true` on both preflight (`OPTIONS`) and cross-origin responses, and trust `.github.io` / `.pages.dev` / `allowedOrigins` origins for browser integration.
|
|
132
133
|
|
|
@@ -205,6 +206,7 @@ Markdown and HTML preview work should preserve the Settings-backed iframe host a
|
|
|
205
206
|
### CLI, Headless Agent Participant & Dual-Root Build Pipeline
|
|
206
207
|
|
|
207
208
|
- **Dual-Root Path Resolution:** The build toolchain (`src/cli/build/build.ts`, invoked via `bin/build.mjs`) cleanly decouples `toolchainRoot` (the ShadowClaw package/repo root resolved dynamically via `getProjectRoot` in `src/cli/utils/resolve-project-root.ts`) from `contentRoot` (the consumer template project). In-repo builds (`resolve(contentRoot) === resolve(toolchainRoot)`) preserve the standalone in-tree compilation path. CLI/template consumer builds read pre-bundled web assets from `toolchainRoot/dist/public` (excluding local model cache directories) and inject `pages/`, `shadow-claw.config.json` (or `site-config.json`), `assets/`, `.agents/`, and pretty routes from `contentRoot`, outputting to `<contentRoot>/dist/public`. Library entry points across components and utilities are dynamically discovered in `configs/rolldown/rolldown.config.mjs` via `getLibraryEntries()`.
|
|
209
|
+
- **Standalone Single-File Builds & Companion Service Worker (`--single-file`, `--service-worker`):** `shadow-claw build --single-file` compiles markdown pages, theme stylesheets, and configuration into a standalone `dist/public/index.html`. Passing `--service-worker` emits a companion `service-worker.js` with content-hashed revision stamping (`// build: <sha256>`), network-first caching for navigation (`index.html`), and stale-while-revalidate caching for CDN runtime assets (`generateSingleFileServiceWorker`), alongside an inline registration script (`generateSingleFileSwRegistration`, `data-shadow-claw-sw="true"`) that mirrors the full update check, Trusted Types script URL wrapping, and UI dialog prompt flow. Single-file builds strip stale local modulepreload and script tags and warn on unpinned CDN URLs (`@latest`, `@next`).
|
|
208
210
|
- **CLI Commands (`src/cli/cli.ts`):** The `shadow-claw` / `shadowclaw` CLI is authored in TypeScript under `src/cli/` and bundled via Rolldown into `dist/cli/` (`npm run build:cli`), with thin entrypoint scripts in `bin/` (`bin/cli.mjs`). It provides `agent` (subcommands: `init`, `model`, `skills`, `tools`, `tool`, `skill`, `import`, `run`, `listen`), `skills` (top-level alias for `agent skills`: `list`, `add`, `remove`, `find`, `init`, `sync`, `update`, `check`, `restore`), `build`, `dev`, `run`, `serve`, `server` (aliases: `services`, `api`), `init`, `clients`, `send`, `send-file`, `backup`, `tasks`, `mcp`, `skills:index`, `webrtc`, and `peer-id` commands. It supports running dev and headless service servers programmatically via `startServer` (`src/server/server.ts`) with custom `--root-path`, `--cache-dir <dir>`, and `--database-dir` arguments.
|
|
209
211
|
- **Headless CLI Agent Participant (`shadow-claw agent`):**
|
|
210
212
|
- **Runtime Mode Flag:** Module-level `isHeadlessMode()` and `setHeadlessMode()` (`src/config/headless.ts`) signal headless server-side execution to tools and storage.
|
|
@@ -219,7 +221,7 @@ Markdown and HTML preview work should preserve the Settings-backed iframe host a
|
|
|
219
221
|
- **Direct Tool Inspection & Execution:** `shadow-claw agent tools` lists tools with capability tags; `shadow-claw agent tool <name> [jsonArgs]` inspects schemas or directly executes a tool against the workspace with stdin piping and plain-text parameter auto-mapping.
|
|
220
222
|
- **Local Model Management (`shadow-claw agent model`):** Dedicated subcommands (`list`, `remote` / `-r` / `--hf`, `download`, `set`) inspect local cached models with recursive directory verification (excluding `.part` and `.tmp` files), query Hugging Face `onnx-community`, download weights with terminal progress bars (`src/cli/utils/progress-bar.ts`), and set workspace defaults.
|
|
221
223
|
- **Interactive Model Selection & Prewarming:** `shadow-claw agent init` provides an interactive terminal model picker for headless workspaces with optional instant downloading (`--download`), supporting paginated (25 items/page) and searchable Hugging Face ONNX model browsing with in-memory session caching.
|
|
222
|
-
- **Execution Flags & Streaming (`shadow-claw agent run`):** Supports `--stream` / `--no-stream`, `--progress` / `--no-progress`, download confirmation guards (`--download`, `-y` / `--yes`), custom system prompts (`--system-prompt`, `--system-prompt-file`, `--no-system-prompt` / `--system-prompt none`), `--no-history`, and tool filtering (`--tools`, `--tools-profile`).
|
|
224
|
+
- **Execution Flags, File Attachments & Streaming (`shadow-claw agent run`):** Supports `--stream` / `--no-stream`, `--progress` / `--no-progress`, download confirmation guards (`--download`, `-y` / `--yes`), custom system prompts (`--system-prompt`, `--system-prompt-file`, `--no-system-prompt` / `--system-prompt none`), `--no-history`, and tool filtering (`--tools`, `--tools-profile`). Repeatable `-f, --file <path>` flags attach local files to prompts with modality size limits (`MAX_NATIVE_IMAGE_BYTES` = 3 MB default, configurable via `--max-image-size <MB>` or `maxImageBytes`; audio = 5 MB; document = 20 MB; text inlining = 100 KB) that fall back to text references with `stderr` warnings when exceeded. Provider `streaming-error` events surface as process failures (`success: false`, exit code 1).
|
|
223
225
|
- **Node-Native Offline Model Executors:** In headless mode, `handleInvoke` passes formatted messages with system prompts directly to `node-transformers-executor.ts` (running ONNX models in-process via `@huggingface/transformers` without requiring a browser or proxy server) and `node-llamafile-executor.ts` (managing host Llamafile and Agentfile binaries directly via `LocalBinaryDriver`).
|
|
224
226
|
- **Termination Cleanup & Signal Handling:** Process signals (`SIGINT` code 130, `SIGTERM` code 143, and `exit`) are intercepted via `registerTerminationCleanup` in `src/cli/cli.ts` and `agent run` signal handlers with force-exit timeouts to ensure background child processes (such as spawned llamafiles or server listeners) terminate cleanly.
|
|
225
227
|
- **Warning Suppression:** Node's experimental SQLite warnings are automatically intercepted via `src/cli/utils/suppress-warnings.ts`.
|
package/dist/public/README.md
CHANGED
|
@@ -65,8 +65,12 @@ npx shadow-claw agent --tools none --no-system-prompt --no-history run "Explain
|
|
|
65
65
|
# Pipe plain text into an agent tool (auto-mapped to tool schema)
|
|
66
66
|
echo "how are you doing today" | npx shadow-claw agent tool rewrite_text
|
|
67
67
|
|
|
68
|
-
# Attach local files (repeatable)
|
|
69
|
-
npx shadow-claw agent run "Compare these" -f a.png -f b.png
|
|
68
|
+
# Attach local files (repeatable) — images, PDFs, audio, code, text
|
|
69
|
+
npx shadow-claw agent run "Compare these" --no-tools -f a.png -f b.png
|
|
70
|
+
|
|
71
|
+
# Images > 3 MB fall back to a text reference by default.
|
|
72
|
+
# Raise the limit with --max-image-size (in MB) for larger images:
|
|
73
|
+
npx shadow-claw agent run "Describe this poster" --no-tools --max-image-size 10 -f big-photo.png
|
|
70
74
|
|
|
71
75
|
# Combine CLI prompt with piped document content and save to file
|
|
72
76
|
cat doc.txt | npx shadow-claw agent run "Summarize this" -o summary.txt
|
|
@@ -1800,7 +1800,7 @@ slug: "shadow-claw-pages"
|
|
|
1800
1800
|
(id, groupId, enabled, schedule, prompt, tools, lastRun, createdAt, type, freshContext, subagent, name, task_order, pushNotifications)
|
|
1801
1801
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);for(let e of i)a.run(fe(),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:fe(),groupId:n};o.put(t),c++,e.continue()}else r(c)},s.onerror=()=>i(s.error)})}function sW(e,t){return k(e,`messages`,`readwrite`,e=>e.delete(t)).then(()=>void 0)}function cW(e,t){return t?k(e,`tasks`,`readwrite`,e=>e.delete(t)).then(()=>void 0):Promise.reject(/* @__PURE__ */ Error(`Task ID is required for deletion.`))}function lW(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`sub-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function uW(e){if(!e)return lW();let t=await A(e,b.SUBSCRIBER_ID);if(typeof t==`string`&&t.trim().length>0)return t;let n=lW();return await pe(e,b.SUBSCRIBER_ID,n),n}function dW(e,t,n){let r=null,i,a;return typeof e==`string`?(i=e,a=t):(r=e,i=t,a=n??50),r&&O(r)?Promise.resolve().then(()=>(r.db.prepare(`SELECT * FROM messages WHERE groupId = ? ORDER BY timestamp DESC LIMIT ?`).all(i,a)??[]).reverse().map(fW)):new Promise(async(e,t)=>{try{let n=r??await ee();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 fW(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 pW=`group_metadata`;async function mW(e){let t=await A(e,pW);if(!t)return[];try{return JSON.parse(t)}catch{return[]}}async function hW(e,t){await pe(e,pW,JSON.stringify(t))}async function gW(e,t,n=`br:`,r){let i=await mW(e),a={groupId:`${n}${r??fe()}`,name:t,createdAt:Date.now()};return i.push(a),await hW(e,i),a}async function _W(e,t,n){let r=await mW(e),i=r.find(e=>e.groupId===t);i&&(i.name=n),await hW(e,r)}async function vW(e,t,n){let r=await mW(e),i=r.find(e=>e.groupId===t);i&&(n&&n.length>0?i.toolTags=n:delete i.toolTags),await hW(e,r)}async function yW(e,t){await hW(e,(await mW(e)).filter(e=>e.groupId!==t))}async function bW(e){let t=await mW(e);if(t.length===0){let t={groupId:v,name:`Main`,createdAt:0};return await hW(e,[t]),[t]}return t}async function xW(e,t){let n=await mW(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 hW(e,i)}async function SW(e,t){let n=await mW(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:`}${fe()}`,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 hW(e,n),a}async function CW(e,t,n,r,i){let a=await mW(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 hW(e,a)}async function wW(e,t,n,r,i,a){let o=await mW(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 hW(e,o)}async function TW(e,t,n){let r=await mW(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 hW(e,r)}function EW(e,t){return k(e,`messages`,`readwrite`,e=>e.put(t)).then(()=>void 0)}function DW(e,t){let n={...t,enabled:+!!t.enabled};return k(e,`tasks`,`readwrite`,e=>e.put(n)).then(()=>void 0)}function OW(e,t,n){let r=null,i,a;return typeof e==`string`?(i=e,a=t):(r=e,i=t,a=n),r&&O(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 ee();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 kW(e,t,n){let r=(await de(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 DW(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 DW(e,t),a.push(t);return a}async function AW(e,t,n,r){let i=await re(e,t),a=await re(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=[F(),`groups`,l,...o];try{await jW(e,n,s,c,u)}catch(e){throw o.length>0&&await a.removeEntry(o[0],{recursive:!0}).catch(()=>void 0),e}}async function jW(e,t,n,r,i){for await(let[a,o]of n.entries()){if(o.kind===`directory`){await jW(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 ye(s,n)}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await ae(e)).type===`opfs`))throw t;await he([...i,a],n)}}}async function MW(e,t,n=`.`){for(let r=0;r<2;r++)try{let r=await re(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&&oe(e)){ie();continue}throw e}return[]}function NW(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 PW(e){let t=await A(e,b.STORAGE_HANDLE);return!NW(t)||await t.requestPermission({mode:`readwrite`})===`granted`}function FW(e){let t=l();return t?`shadowclaw:${t}:${e}`:e}function IW(e){if(typeof localStorage>`u`)return null;let t=FW(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 LW(e,t){if(typeof localStorage>`u`)return;let n=FW(e);try{localStorage.setItem(n,t)}catch(e){console.warn(`Unable to write to localStorage:`,e)}}async function RW(e,t){let n=await re(e,t);for await(let[e]of n.entries())await n.removeEntry(e,{recursive:!0})}async function zW(e,t,n){let r=await re(e,t),{dirs:i,filename:a}=M(n.replace(/\/$/,``)),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a,{recursive:!0})}function BW(e,t){return`${e}:${t}`}async function VW(e){let t=await A(e,b.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 HW(e,t,n){let r=await VW(e),i=BW(t,n);return r.some(e=>BW(e.groupId,e.path)===i)}async function UW(e,t,n){let r=await VW(e),i=BW(t,n);if(!r.some(e=>BW(e.groupId,e.path)===i)){let i=[...r,{groupId:t,path:n}];await pe(e,b.SUPPRESSED_PAGES_LIST,JSON.stringify(i))}}async function WW(e,t,n){let r=await VW(e),i=BW(t,n),a=r.filter(e=>BW(e.groupId,e.path)!==i);a.length!==r.length&&await pe(e,b.SUPPRESSED_PAGES_LIST,JSON.stringify(a))}function GW(e){return Array.from(new Set(e.map(e=>e.trim()).filter(Boolean)))}function KW(e){let t=e.trim().replace(/\\/g,`/`);return t===`/`||/^\/+$/.test(t)?`/`:t.replace(/^\/+/,``).replace(/\/+$/,``)}const qW=/\.(md|markdown|html|xhtml|txt)$/i;function JW(e){return e===`/`?`/`:e.replace(qW,``)}function YW(e){let t=e.trim().replace(/\\/g,`/`);return t===`/`||/^\/+$/.test(t)?`/`:t.replace(/^\/+/,``).replace(/\/+$/,``)}function XW(e){return e?e.replace(/^br:/i,``).replace(/^br-/i,``).trim():`main`}function ZW(e,t){let n=YW(t);if(!n)return;e.add(n);let r=JW(n);r&&r!==n&&e.add(r)}function QW(e,t,n){let r=/* @__PURE__ */ new Set;if(!e)return r;let i=XW(t);if(e===`/`){if(r.add(`/`),ZW(r,`index.html`),n){let e=KW(n);e&&e!==`/`&&ZW(r,`${e}/index.html`)}return ZW(r,`pages/index.html`),ZW(r,`pages/${i}/index.html`),ZW(r,`${i}/index.html`),r}if(ZW(r,e),n){let t=KW(n);t&&t!==`/`&&ZW(r,`${t}/${e}`)}if(e.startsWith(`pages/`)){let t=e.slice(6);ZW(r,t),t.startsWith(`${i}/`)?ZW(r,t.slice(`${i}/`.length)):ZW(r,t.replace(/^[^/]+\//,``))}else ZW(r,`pages/${e}`),ZW(r,`pages/${i}/${e}`),ZW(r,`${i}/${e}`);for(let e of Array.from(r)){let t=JW(e);if(e===`index.html`||t===`index`){r.add(`/`);break}}return r}function $W(e,t){let n=t.toLowerCase(),r=JW(t).toLowerCase(),i=n===r?[n]:[n,r];for(let t of e){let e=t.toLowerCase(),n=JW(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 eG(e,t){for(let n of t){let t=KW(n);if(t&&$W(e,t))return!0}return!1}function tG(e,t,n,r){if(!e||typeof e!=`string`)return!1;let i=YW(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=GW(Array.from(n||[])),o=GW(Array.from(r||[])),s=e.groupId,c=e.basePathPrefix}else a=GW(Array.from(t||[])),o=GW(Array.from(n||[])),s=r?.groupId,c=r?.basePathPrefix;let l=QW(i,s,c);return o.length>0&&eG(l,o)?!1:a.length>0?eG(l,a):!0}function nG(e){if(!e)return``;let t=e.match(/^\r?\n([ \t]+)/);if(t){let n=t[1],r=RegExp(`^[ \\t]{1,${n.length}}`,`gm`);return e.replace(/^\r?\n/,``).replace(r,``).replace(/\r?\n[ \t]*$/,`
|
|
1802
1802
|
`)}if(/^(?:\r?\n)+[ \t]*---/.test(e))return e.replace(/^(?:\r?\n)+/,``);if(/^[ \t]+---/.test(e)){let t=e.match(/^[ \t]+/);if(t){let n=t[0],r=RegExp(`^[ \\t]{1,${n.length}}`,`gm`);return e.replace(r,``)}}return e}function rG(e=v){return e===`br:main`?b.STATIC_MAIN_SITE_SEEDED:`${b.STATIC_MAIN_SITE_SEEDED}:${e}`}async function iG(e,t=v){let n=rG(t),r=await A(e,n);return r===!0||r===`true`}async function aG(e,t=v,n=!0){let r=rG(t);await pe(e,r,n)}function oG(){let e=a(`/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 sG(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=a(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 cG(){if(typeof fetch!=`function`)return null;try{let e=oG(),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 lG(e){if(typeof fetch!=`function`)return null;try{let t=sG(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 uG(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 dG(e=`index.html`){let t=uG(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(`
|
|
1803
|
-
`)}\n${s}`}return s}async function fG(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=nG(r),!r.trim()&&/^memory\.(md|markdown)$/iu.test(n)&&(r=LU),!r.trim()&&(n===`index.html`||/^index\.(html?|xhtml)$/iu.test(n))&&(r=dG(n)??UU);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=LU:(t===`index.html`||/^index\.(html?|xhtml)$/iu.test(t))&&(r=dG(t)??UU),e.pages.some(e=>e.displayPath===t)||e.pages.push({displayPath:t,content:r})}}}catch{}let i=uG();if(i){e||={pages:[]};let t=i.getAttribute(`data-initial-path`)?.trim()||`index.html`;if(!e.pages.some(e=>e.displayPath===t)){let n=dG(t)??UU;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:LU})}}return e};if(e.preferEmbedded!==!1){let e=t();if(e)return e}if(e.fetchFallback!==!1){let e=await cG();if(e)return e}if(e.preferEmbedded===!1){let e=t();if(e)return e}return{pages:[{displayPath:`index.html`,content:UU},{displayPath:`MEMORY.md`,content:LU}]}}async function pG(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 zW(e,t,r):await RW(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await pG(e,i,[...n,r])}function mG(){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 hG(){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 gG(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);return{allowList:GW(t?.pages?.allowList??t?.pages?.allowlist??t?.allowList??t?.allowlist??[]),denyList:GW(t?.pages?.denyList??t?.pages?.denylist??t?.denyList??t?.denylist??[])}}}catch{}return{allowList:[],denyList:[]}}function _G(e,t){let n=t??mG();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 vG(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(IW(n)===i)return!0}catch{}try{if(await A(e,r)===i){try{LW(n,i)}catch{}return!0}await pe(e,r,i);try{LW(n,i)}catch{}}catch{try{LW(n,i)}catch{}}return!1}async function yG(e,t=v,n=[],r={}){await qU(e,t);let i=await fG(r),a=!1;i.preRenderedStaticPages&&(await vG(e,i.purgeId)||(a=!0,await pG(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await vG(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await zW(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}try{await zW(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 vG(e,i.purgeId)&&(a=!0,await RW(e,t));break}let s=t===`br:main`&&await BU(e),c=new Set(i.pages.map(e=>BW(t,e.displayPath))),l=a?n.filter(e=>e.groupId!==t||c.has(BW(e.groupId,e.path))):[...n],{allowList:u,denyList:d}=gG(),f=0;for(let n of i.pages)if(f++,f%5==0&&await new Promise(e=>setTimeout(e,0)),!n.content?.includes(`slug: "shadow-claw--purge-pages"`)&&tG(n.displayPath,{allowList:u,denyList:d,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!==LU?n.content:void 0;if(r===void 0?await HU(e,t):await HU(e,t,r)){let e=BW(t,n.displayPath);l.some(t=>BW(t.groupId,t.path)===e)||l.push({groupId:t,path:n.displayPath})}}else if(!await HW(e,t,n.displayPath))try{if(!await P(e,t,n.displayPath)){let r=n.content;(typeof r!=`string`||!r.trim())&&(r=n.displayPath===`index.html`?dG(`index.html`)??UU:await lG(n.displayPath)??``),await xe(e,t,n.displayPath,r)}let r=BW(t,n.displayPath);l.some(e=>BW(e.groupId,e.path)===r)||l.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 P(e,t,r)||await xe(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 P(e,t,r))&&await xe(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let p=typeof document<`u`&&(document.getElementById(`shadow-claw-static-manifest`)!==null||document.querySelector(`script[type="text/markdown"][data-shadow-claw-page]`)!==null||uG()!==null);r.preferEmbedded!==!1&&p||await aG(e,t,!0);let m=l.filter(e=>tG(e.path,{allowList:u,denyList:d,groupId:e.groupId}));return Object.defineProperty(m,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(m,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),_G(m)}var bG=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=fe(),n=e,r=fe();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=fe();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()}))}}}};const xG=new class{#e=new ve.State(0);#t=/* @__PURE__ */ new Map;#n=new ve.State([]);clear(){this.#t.forEach((e,t)=>this.clearTimer(t)),this.#t.clear(),this.#n.set([])}clearTimer(e){let t=this.#t.get(e);t?.timeoutId&&clearTimeout(t.timeoutId),this.#t.delete(e)}dismiss(e){this.clearTimer(e),this.#n.set(this.#n.get().filter(t=>t.id!==e))}pause(e){let t=this.#t.get(e);t&&t.timeoutId&&(clearTimeout(t.timeoutId),t.timeoutId=void 0,t.remaining=Math.max(0,t.remaining-(Date.now()-t.startedAt)),this.#t.set(e,t))}resolveAction(e){if(e&&typeof e.label==`string`&&typeof e.onClick==`function`)return e}resolveDuration(e){return typeof e!=`number`||Number.isNaN(e)||e<0?4e3:e}resolveType(e){return e&&[`success`,`warning`,`error`,`info`].includes(e)?e:`info`}resume(e){let t=this.#t.get(e);!t||t.timeoutId||t.remaining<=0||this.scheduleDismiss(e,t.remaining)}scheduleDismiss(e,t){this.clearTimer(e);let n=globalThis.setTimeout(()=>{this.dismiss(e)},t);this.#t.set(e,{timeoutId:n,remaining:t,startedAt:Date.now()})}show(e,t={}){let n=this.#e.get()+1;this.#e.set(n);let r={id:n,message:e,type:this.resolveType(t.type),duration:this.resolveDuration(t.duration),action:this.resolveAction(t.action),createdAt:Date.now()},i=[...this.#n.get(),r];if(i.length>5){let e=i[0];this.clearTimer(e.id),this.#n.set(i.slice(1))}else this.#n.set(i);return r.duration>0&&this.scheduleDismiss(r.id,r.duration),r.id}get toasts(){return this.#n.get()}async runAction(e){let t=this.#n.get().find(t=>t.id===e);t?.action&&await t.action.onClick()}};function SG(e,t={}){return xG.show(e,t)}function CG(e,t=4e3){return xG.show(e,{type:`success`,duration:t})}function wG(e,t=5e3){return xG.show(e,{type:`error`,duration:t})}function TG(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)EG(n,e);return n}function EG(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)?DG(s,o,n,i):OG(s,o,n,i))}function DG(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 OG(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}function kG(e){if(e==null)return null;let t=String(e).trim().toLowerCase();return[`1`,`true`,`yes`,`on`].includes(t)?!0:![`0`,`false`,`no`,`off`].includes(t)&&null}function AG(e,t=!1){if(e==null)return t;if(typeof e==`boolean`)return e;if(typeof e==`number`)return e===1;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return!1}function jG(e){if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t))return GW(t.map(e=>String(e)))}catch{}return GW(e.split(`,`))}let MG=/* @__PURE__ */ new Map;function NG(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 MG.delete(t),null;let r=MG.get(t);if(r&&r.rawText===n.textContent)return r.config;try{let e=JSON.parse(n.textContent);if(!e||typeof e!=`object`)return MG.delete(t),null;let r={...e};return MG.set(t,{rawText:n.textContent,config:r}),r}catch(e){return console.warn(`[ShadowClaw] Failed to parse site configuration from #${t}:`,e),null}}var PG=/* @__PURE__ */ t({OrchestratorStore:()=>HG,accumulateTokenUsage:()=>VG,orchestratorStore:()=>UG});function FG(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 IG(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 LG(e){return!!e}async function RG(e,t,n,r){if(!LG(r))return!0;if(!e.schedule)return await zG(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 zG(e,t,n,r){if(!LG(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 BG(e,t,n,r){if(!LG(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:FG(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 VG(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 HG=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 ve.State([]),this._isTyping=new ve.State(!1),this._storageStatus=new ve.State(null),this._toolActivity=new ve.State(null),this._modelDownloadProgress=new ve.State(null),this._activityLog=new ve.State([]),this._state=new ve.State(`idle`),this._tokenUsage=new ve.State(null),this._error=new ve.State(null),this._activeGroupId=new ve.State(v),this._ready=new ve.State(!1),this._tasks=new ve.State([]),this._files=new ve.State([]),this._currentPath=new ve.State(`.`),this._groups=new ve.State([]),this._unreadGroupIds=new ve.State(/* @__PURE__ */ new Set),this._streamingText=new ve.State(null),this._aguiEvent=new ve.State(null),this._contextUsage=new ve.State(null),this._useProxy=new ve.State(!1),this._proxyUrl=new ve.State(`/proxy`),this._gitProxyUrl=new ve.State(`/git-proxy`),this._vmBashFullInternetAccess=new ve.State(!1),this._activePage=new ve.State(`pages`);let e=NG()?.sidebar?.defaultPage,t=e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`;this._sidebarDefaultPage=new ve.State(t),this._pages=new ve.State([]),this._pagesAllowList=new ve.State([]),this._pagesDenyList=new ve.State([]),this._activePinnedPage=new ve.State(null),this._defaultPinnedPage=new ve.State(null),this._remoteAgentStatusByGroup=new ve.State(/* @__PURE__ */ new Map),this._remoteAgentTypingByGroup=new ve.State(/* @__PURE__ */ new Map),this._peerStateByGroup=new ve.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 tG(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 wG(e,4500),Error(e)}let a=this.orchestrator?.router;if(!a){let e=`Network router is not initialized.`;throw wG(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:fe(),groupId:t,sender:`You`,content:``,timestamp:Date.now(),channel:i?`room`:`peerjs`,attachments:[n],isFromMe:!1,isTrigger:!1};await EW(this._db,e),this.orchestrator?.events.emit(`message`,e)}CG(`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),wG(`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(){ZU(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){QU(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 pe(e,b.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 WW(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await VU(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await de(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r)await zG(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 cW(e,t.id);await this.loadTasks(e)}async cloneConversation(e,t){let n=await SW(e,t);if(!n)return null;await aW(e,t,n.groupId),await oW(e,t,n.groupId);try{let r=await I(e,t,`MEMORY.md`);r&&await xe(e,n.groupId,`MEMORY.md`,r)}catch{}try{await AW(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-CX4H8V57.js`);return t(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await gW(e,t);return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await yW(e,t),await iW(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 sW(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 zG(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 cW(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await bW(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 hW(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await PW(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,t){this._db=e,this.orchestrator=t,this._taskSyncOutbox=this.parseTaskSyncOutbox(await A(e,b.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)),t.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 EW(e,o)}else{let i=!t.startsWith(`peer:`),a={id:fe(),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 EW(e,a)}}),t.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])}),t.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),t.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)}),t.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),t.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))}),t.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)}),t.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),t.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`)}),t.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),t.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=VG(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),t.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),t.events.on(`ready`,()=>{this._ready.set(!0)}),t.events.on(`task-change`,()=>{this.loadTasks(e)}),t.events.on(`file-change`,()=>{this.loadFiles(e)}),t.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),t.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),t.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),t.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),t.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new bG(t.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=TG(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await ce(e),ue(),Ee(),await XU();let n=await A(e,b.PAGES_ALLOW_LIST),r=await A(e,b.PAGES_DENY_LIST);n&&this._pagesAllowList.set(jG(String(n))),r&&this._pagesDenyList.set(jG(String(r))),await XU();let i=typeof document<`u`&&document.getElementById(`shadow-claw-static-routing`)!==null,a=await A(e,b.PAGES_LIST),o=a==null?[]:this.parsePagesList(a),c=await yG(e,v,o);c.length>0?(this.setPages(c),await this.persistPages(e)):await this.ensureDefaultPage(e),await XU(),await this.applySiteConfigDefaults(e),await XU(),await this.loadGroups(e);let l=await A(e,b.LAST_ACTIVE_GROUP);l&&l!==this._activeGroupId.get()&&this._activeGroupId.set(l),await XU();let u=await A(e,b.LAST_ACTIVE_PAGE);u&&(this._activePage.set(u),this._hadPersistedActivePage=!0);let d=await A(e,b.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(d));let f=hG(),p=null;if(f&&(p=s(f)),!p){let t=await A(e,b.DEFAULT_PINNED_PAGE);t&&(p=s(t))}p&&this.isPageAllowed(p.path,p.groupId)&&this._defaultPinnedPage.set(p),await XU();let m=typeof window<`u`&&window.history?window.history.state:null,h=!!(m?.inFeedScroll||m?.scrollSpy||m?.suppressRouter)||typeof window<`u`&&window.location&&(()=>{let e=window.location.pathname||`/`,t=w();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`})(),g=!1;if(h&&p&&this.isPageAllowed(p.path,p.groupId)&&(this._activePinnedPage.set(p),g=!0),!g){let t=await A(e,b.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),g=!0)}catch{}}!g&&h&&this.effectiveDefaultPage&&this.isPageAllowed(this.effectiveDefaultPage.path,this.effectiveDefaultPage.groupId)&&(this._activePinnedPage.set(this.effectiveDefaultPage),g=!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[_,y,x]=await Promise.all([A(e,b.SIDEBAR_CHAT_HIDDEN),A(e,b.SIDEBAR_TASKS_HIDDEN),A(e,b.SIDEBAR_FILES_HIDDEN)]),S=NG(),C=S?.sidebar?.chatHidden,T=S?.sidebar?.tasksHidden,E=S?.sidebar?.filesHidden,ee=_==null?!!C:AG(_),D=y==null?!!T:AG(y),O=x==null?!!E:AG(x),k=()=>{let t=[];(!ee||this.activePage===`chat`)&&t.push(this.loadHistory()),(!D||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(i)typeof window.requestIdleCallback==`function`?window.requestIdleCallback(k,{timeout:2e3}):setTimeout(k,100);else{let t=[];(!ee||this.activePage===`chat`)&&t.push(this.loadHistory()),(!D||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),await Promise.all(t)}await XU(),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await ae(e));let r=await MW(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await bW(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await dW(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await de(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 BG(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 DW(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),wG(`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 UW(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await VU(t,!0);let c=s||await BU(t);if(o.length===0&&!c){if(await HU(t,`br:main`))o.push({groupId:v,path:e.DEFAULT_PAGE_PATH});else return}this.setPages(o);let l=this._defaultPinnedPage.get();l&&l.path===i&&l.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 UW(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await VU(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await _W(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await xW(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await kW(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await RG(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 RG(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await zG(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 OW(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:${fe()}`: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 pe(e,b.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await pe(e,b.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){t&&!this.isPageAllowed(t.path,t.groupId)&&(t=this.effectiveDefaultPage),this._activePinnedPage.set(t),t?await pe(e,b.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await pe(e,b.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 pe(e,b.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await pe(e,b.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 ae(e));let i=await MW(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await eW(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await tW(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await nW(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await rW(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 pe(e,b.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await DW(e,r),await this.loadTasks(e),await RG(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 CW(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await TW(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await wW(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await vW(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await DW(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await RG(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 uW(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:v,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:v,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 BU(t))return;let n=await HU(t,v);await qU(t,v),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:v,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 hW(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!IG(await A(this._db,b.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 iG(e,`br:main`))return;let t=await A(e,b.PAGES_LIST),n=t==null?[]:this.parsePagesList(t),r=await yG(e,v,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 pe(e,b.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await pe(e,b.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 t=NG();if(!t||typeof t!=`object`)return;me(t),ue(),Ee();let n=t.customElements;if((await bW(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await vW(e,v,void 0),(t.settings?.internetAccess??t.settings?.vm_bash_full_internet_access??t.settings?.fullInternetAccess??t.internetAccess)===!0&&await A(e,b.VM_BASH_FULL_INTERNET_ACCESS)!==`true`&&(await pe(e,b.VM_BASH_FULL_INTERNET_ACCESS,`true`),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=!0),this._vmBashFullInternetAccess.set(!0)),t.pages&&typeof t.pages==`object`){let{defaultPinnedPage:n}=t.pages;if(n&&typeof n==`string`){let t=s(n);t&&this.isPageAllowed(t.path,t.groupId)&&(this._defaultPinnedPage.set(t),await pe(e,b.DEFAULT_PINNED_PAGE,JSON.stringify(t)))}}let r=t.allowedCustomElements||(typeof n==`object`&&!Array.isArray(n)?n.allowedElements:void 0);r!==void 0&&(await A(e,b.ALLOWED_CUSTOM_ELEMENTS)??await pe(e,b.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(r)));let i=t.allowedCustomElementDomains||(typeof n==`object`&&!Array.isArray(n)?n.allowedDomains:void 0);if(i!==void 0&&(await A(e,b.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS)??await pe(e,b.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(i))),t.sidebar&&typeof t.sidebar==`object`){let{pagesHidden:n,chatHidden:r,tasksHidden:i,filesHidden:a,defaultPage:o}=t.sidebar;if(n!==void 0&&(await A(e,b.SIDEBAR_PAGES_HIDDEN)??await pe(e,b.SIDEBAR_PAGES_HIDDEN,String(!!n))),r!==void 0&&(await A(e,b.SIDEBAR_CHAT_HIDDEN)??await pe(e,b.SIDEBAR_CHAT_HIDDEN,String(!!r))),i!==void 0&&(await A(e,b.SIDEBAR_TASKS_HIDDEN)??await pe(e,b.SIDEBAR_TASKS_HIDDEN,String(!!i))),a!==void 0&&(await A(e,b.SIDEBAR_FILES_HIDDEN)??await pe(e,b.SIDEBAR_FILES_HIDDEN,String(!!a))),o&&typeof o==`string`){let t=this.normalizeSidebarDefaultPage(o);this._sidebarDefaultPage.set(t),await A(e,b.SIDEBAR_DEFAULT_PAGE)||await pe(e,b.SIDEBAR_DEFAULT_PAGE,o)}}if(t.settings&&typeof t.settings==`object`){let{assistantName:n,defaultProvider:r,provider:i,defaultModel:a,model:o}=t.settings;n&&typeof n==`string`&&(await A(e,b.ASSISTANT_NAME)||await pe(e,b.ASSISTANT_NAME,n));let s=r??i;if(typeof s==`string`&&s.trim().length>0&&!await A(e,b.PROVIDER)){let t=s.trim();await pe(e,b.PROVIDER,t),this.orchestrator&&(this.orchestrator.provider=t)}let c=a??o;if(typeof c==`string`&&c.trim().length>0&&!await A(e,b.MODEL)){let t=c.trim();await pe(e,b.MODEL,t),this.orchestrator&&(this.orchestrator.model=t)}let l=t.settings.internetAccess??t.settings.vm_bash_full_internet_access??t.settings.fullInternetAccess??t.internetAccess;typeof l==`boolean`&&(await A(e,b.VM_BASH_FULL_INTERNET_ACCESS)??(await pe(e,b.VM_BASH_FULL_INTERNET_ACCESS,String(l)),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=l),this._vmBashFullInternetAccess.set(l)))}let a=(t.settings&&typeof t.settings==`object`?t.settings.defaultToolsProfile:void 0)??t.defaultToolsProfile;if(typeof a==`string`&&a.trim().length>0&&!await A(e,b.ACTIVE_TOOL_PROFILE)){let t=a.trim();if(t.toLowerCase()===`none`)await we.deactivateProfile(e);else{let n=we.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await we.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(t.pages&&typeof t.pages==`object`){let{defaultPinnedPage:n}=t.pages;n&&typeof n==`string`&&(await A(e,b.DEFAULT_PINNED_PAGE)||await pe(e,b.DEFAULT_PINNED_PAGE,n))}let o=t.pages?.allowList??t.pages?.allowlist??t.allowList??t.allowlist,c=t.pages?.denyList??t.pages?.denylist??t.denyList??t.denylist;if(Array.isArray(o)&&await A(e,b.PAGES_ALLOW_LIST)==null){let t=GW(o.map(String));this._pagesAllowList.set(t),await pe(e,b.PAGES_ALLOW_LIST,JSON.stringify(t))}if(Array.isArray(c)&&await A(e,b.PAGES_DENY_LIST)==null){let t=GW(c.map(String));this._pagesDenyList.set(t),await pe(e,b.PAGES_DENY_LIST,JSON.stringify(t))}await pe(e,b.SITE_CONFIG_SEEDED,`true`);let l=this._pages.get(),u=l.filter(e=>this.isPageAllowed(e.path,e.groupId));u.length!==l.length&&(this.setPages(u),await this.persistPages(e));let d=this._activePinnedPage.get();d&&!this.isPageAllowed(d.path,d.groupId)&&await this.setActivePinnedPage(e,this.effectiveDefaultPage);let f=this._defaultPinnedPage.get();if(f&&!this.isPageAllowed(f.path,f.groupId)&&await this.setDefaultPinnedPage(e,null),Array.isArray(t.enabledTools)){let n=t.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await we.setAllEnabled(e,n),await we.setAllDeclarativeEnabled(e,n)}await pe(e,b.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const UG=new HG;async function WG(e,t,n){let r=await re(e,t),{dirs:i,filename:a}=M(n),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a),t===`br:main`&&i.length===0&&(a===`MEMORY.md`?await VU(e,!0):a===`index.html`&&await KU(e,!0));try{await UW(e,t,n)}catch{}try{await UG.removePage(e,n,t)}catch{}}async function GG(e,t,n){let r=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean);if(r.length===0)throw Error(`Empty directory path`);for(let n=0;n<2;n++)try{let n=await re(e,t);for(let e of r)n=await n.getDirectoryHandle(e,{create:!0});return}catch(e){if(n===0&&oe(e)){ie();continue}throw e}}var KG=class extends zL{db;groupId;workspacePrefix;constructor(e,t,n,r=`/home/user`){super(n),this.db=e,this.groupId=t,this.workspacePrefix=r}async appendFile(e,t){await super.appendFile(e,t);let n=this._toDbPath(e);if(n!==null){let t=await this._readPathContent(e);await xe(this.db,this.groupId,n,t)}}async cp(e,t,n){await super.cp(e,t,n);let r=this._toDbPath(t);if(r!==null)try{let e=await super.stat(t);if(!this._isDirectoryStat(e)){let e=await this._readPathContent(t);await xe(this.db,this.groupId,r,e)}}catch{}}async mkdir(e,t){await super.mkdir(e,t);let n=this._toDbPath(e);n!==null&&n!==``&&await GG(this.db,this.groupId,n)}async mv(e,t){await super.mv(e,t);let n=!1,r=t,i=this._toDbPath(t);if(i!==null)try{let i=await super.stat(t);if(this._isDirectoryStat(i)){let n=this._basename(e);n&&(r=this._joinPath(t,n))}let a=await super.stat(r);if(!this._isDirectoryStat(a)){let e=this._toDbPath(r);if(e!==null){let t=await this._readPathContent(r);await xe(this.db,this.groupId,e,t),n=!0}}}catch{}let a=this._toDbPath(e);if(a!==null)try{(i===null||n)&&await WG(this.db,this.groupId,a)}catch{}}async rm(e,t){await super.rm(e,t);let n=this._toDbPath(e);if(n!==null)try{await WG(this.db,this.groupId,n)}catch{}}async writeFile(e,t,n){await super.writeFile(e,t,n);let r=this._toDbPath(e);if(r!==null){let t=await this._readPathContent(e);await xe(this.db,this.groupId,r,t)}}_basename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]||``}_isDirectoryStat(e){return e&&typeof e.isDirectory==`function`?!!e.isDirectory():!!e?.isDirectory}_joinPath(e,t){let n=e.replace(/\/+$/,``);return n?`${n}/${t}`:`/${t}`}_toDbPath(e){return e.startsWith(this.workspacePrefix+`/`)?e.slice(this.workspacePrefix.length+1):e===this.workspacePrefix?``:null}async _readPathContent(e){try{return await super.readFileBuffer(e)}catch{return await super.readFile(e)}}};async function qG(e,t){let n={},r=/* @__PURE__ */ new Set,i=`/home/user`;async function a(o){let s=await MW(e,t,o);for(let c of s)if(c.endsWith(`/`)){let e=c.slice(0,-1),t=o===`.`?e:`${o}/${e}`;r.add(t),await a(t)}else{let r=o===`.`?c:`${o}/${c}`,a=`${i}/${r}`;n[a]=async()=>{try{return await IU(e,t,r)}catch{return``}}}}await a(`.`);let o=new KG(e,t,n,i);for(let e of[...r].sort((e,t)=>e.split(`/`).length-t.split(`/`).length))try{o.mkdirSync(`${i}/${e}`,{recursive:!0})}catch{}return o}async function JG(e,t,n,r={},i=30,a=!1){try{let i=await new MU({fs:await qG(e,n),network:{dangerouslyAllowFullInternetAccess:a,denyPrivateRanges:!a}}).exec(t,{env:{HOME:`/home/user`,PATH:`/usr/bin`,PWD:`/home/user`,...r}});return{stdout:i.stdout||``,stderr:i.stderr||``,exitCode:i.exitCode??0}}catch(e){return{stdout:``,stderr:e instanceof Error?e.message:String(e),exitCode:1}}}function YG(e){let t=e.stdout||``;return e.stderr&&(t+=(t?`
|
|
1803
|
+
`)}\n${s}`}return s}async function fG(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=nG(r),!r.trim()&&/^memory\.(md|markdown)$/iu.test(n)&&(r=LU),!r.trim()&&(n===`index.html`||/^index\.(html?|xhtml)$/iu.test(n))&&(r=dG(n)??UU);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=LU:(t===`index.html`||/^index\.(html?|xhtml)$/iu.test(t))&&(r=dG(t)??UU),e.pages.some(e=>e.displayPath===t)||e.pages.push({displayPath:t,content:r})}}}catch{}let i=uG();if(i){e||={pages:[]};let t=i.getAttribute(`data-initial-path`)?.trim()||`index.html`;if(!e.pages.some(e=>e.displayPath===t)){let n=dG(t)??UU;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:LU})}}return e};if(e.preferEmbedded!==!1){let e=t();if(e&&e.pages.length>0)return e}if(e.fetchFallback!==!1){let e=await cG();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:UU},{displayPath:`MEMORY.md`,content:LU}]}}async function pG(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 zW(e,t,r):await RW(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await pG(e,i,[...n,r])}function mG(){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 hG(){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 gG(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);return{allowList:GW(t?.pages?.allowList??t?.pages?.allowlist??t?.allowList??t?.allowlist??[]),denyList:GW(t?.pages?.denyList??t?.pages?.denylist??t?.denyList??t?.denylist??[])}}}catch{}return{allowList:[],denyList:[]}}function _G(e,t){let n=t??mG();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 vG(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(IW(n)===i)return!0}catch{}try{if(await A(e,r)===i){try{LW(n,i)}catch{}return!0}await pe(e,r,i);try{LW(n,i)}catch{}}catch{try{LW(n,i)}catch{}}return!1}async function yG(e,t=v,n=[],r={}){await qU(e,t);let i=await fG(r),a=!1;i.preRenderedStaticPages&&(await vG(e,i.purgeId)||(a=!0,await pG(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await vG(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await zW(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}try{await zW(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 vG(e,i.purgeId)&&(a=!0,await RW(e,t));break}let s=t===`br:main`&&await BU(e),c=new Set(i.pages.map(e=>BW(t,e.displayPath))),l=a?n.filter(e=>e.groupId!==t||c.has(BW(e.groupId,e.path))):[...n],{allowList:u,denyList:d}=gG(),f=0;for(let n of i.pages)if(f++,f%5==0&&await new Promise(e=>setTimeout(e,0)),!n.content?.includes(`slug: "shadow-claw--purge-pages"`)&&tG(n.displayPath,{allowList:u,denyList:d,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!==LU?n.content:void 0;if(r===void 0?await HU(e,t):await HU(e,t,r)){let e=BW(t,n.displayPath);l.some(t=>BW(t.groupId,t.path)===e)||l.push({groupId:t,path:n.displayPath})}}else if(!await HW(e,t,n.displayPath))try{if(!await P(e,t,n.displayPath)){let r=n.content;(typeof r!=`string`||!r.trim())&&(r=n.displayPath===`index.html`?dG(`index.html`)??UU:await lG(n.displayPath)??``),await xe(e,t,n.displayPath,r)}let r=BW(t,n.displayPath);l.some(e=>BW(e.groupId,e.path)===r)||l.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 P(e,t,r)||await xe(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 P(e,t,r))&&await xe(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let p=typeof document<`u`&&(document.getElementById(`shadow-claw-static-manifest`)!==null||document.querySelector(`script[type="text/markdown"][data-shadow-claw-page]`)!==null||uG()!==null);r.preferEmbedded!==!1&&p||await aG(e,t,!0);let m=l.filter(e=>tG(e.path,{allowList:u,denyList:d,groupId:e.groupId}));return Object.defineProperty(m,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(m,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),_G(m)}var bG=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=fe(),n=e,r=fe();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=fe();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()}))}}}};const xG=new class{#e=new ve.State(0);#t=/* @__PURE__ */ new Map;#n=new ve.State([]);clear(){this.#t.forEach((e,t)=>this.clearTimer(t)),this.#t.clear(),this.#n.set([])}clearTimer(e){let t=this.#t.get(e);t?.timeoutId&&clearTimeout(t.timeoutId),this.#t.delete(e)}dismiss(e){this.clearTimer(e),this.#n.set(this.#n.get().filter(t=>t.id!==e))}pause(e){let t=this.#t.get(e);t&&t.timeoutId&&(clearTimeout(t.timeoutId),t.timeoutId=void 0,t.remaining=Math.max(0,t.remaining-(Date.now()-t.startedAt)),this.#t.set(e,t))}resolveAction(e){if(e&&typeof e.label==`string`&&typeof e.onClick==`function`)return e}resolveDuration(e){return typeof e!=`number`||Number.isNaN(e)||e<0?4e3:e}resolveType(e){return e&&[`success`,`warning`,`error`,`info`].includes(e)?e:`info`}resume(e){let t=this.#t.get(e);!t||t.timeoutId||t.remaining<=0||this.scheduleDismiss(e,t.remaining)}scheduleDismiss(e,t){this.clearTimer(e);let n=globalThis.setTimeout(()=>{this.dismiss(e)},t);this.#t.set(e,{timeoutId:n,remaining:t,startedAt:Date.now()})}show(e,t={}){let n=this.#e.get()+1;this.#e.set(n);let r={id:n,message:e,type:this.resolveType(t.type),duration:this.resolveDuration(t.duration),action:this.resolveAction(t.action),createdAt:Date.now()},i=[...this.#n.get(),r];if(i.length>5){let e=i[0];this.clearTimer(e.id),this.#n.set(i.slice(1))}else this.#n.set(i);return r.duration>0&&this.scheduleDismiss(r.id,r.duration),r.id}get toasts(){return this.#n.get()}async runAction(e){let t=this.#n.get().find(t=>t.id===e);t?.action&&await t.action.onClick()}};function SG(e,t={}){return xG.show(e,t)}function CG(e,t=4e3){return xG.show(e,{type:`success`,duration:t})}function wG(e,t=5e3){return xG.show(e,{type:`error`,duration:t})}function TG(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)EG(n,e);return n}function EG(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)?DG(s,o,n,i):OG(s,o,n,i))}function DG(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 OG(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}function kG(e){if(e==null)return null;let t=String(e).trim().toLowerCase();return[`1`,`true`,`yes`,`on`].includes(t)?!0:![`0`,`false`,`no`,`off`].includes(t)&&null}function AG(e,t=!1){if(e==null)return t;if(typeof e==`boolean`)return e;if(typeof e==`number`)return e===1;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return!1}function jG(e){if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t))return GW(t.map(e=>String(e)))}catch{}return GW(e.split(`,`))}let MG=/* @__PURE__ */ new Map;function NG(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 MG.delete(t),null;let r=MG.get(t);if(r&&r.rawText===n.textContent)return r.config;try{let e=JSON.parse(n.textContent);if(!e||typeof e!=`object`)return MG.delete(t),null;let r={...e};return MG.set(t,{rawText:n.textContent,config:r}),r}catch(e){return console.warn(`[ShadowClaw] Failed to parse site configuration from #${t}:`,e),null}}var PG=/* @__PURE__ */ t({OrchestratorStore:()=>HG,accumulateTokenUsage:()=>VG,orchestratorStore:()=>UG});function FG(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 IG(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 LG(e){return!!e}async function RG(e,t,n,r){if(!LG(r))return!0;if(!e.schedule)return await zG(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 zG(e,t,n,r){if(!LG(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 BG(e,t,n,r){if(!LG(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:FG(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 VG(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 HG=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 ve.State([]),this._isTyping=new ve.State(!1),this._storageStatus=new ve.State(null),this._toolActivity=new ve.State(null),this._modelDownloadProgress=new ve.State(null),this._activityLog=new ve.State([]),this._state=new ve.State(`idle`),this._tokenUsage=new ve.State(null),this._error=new ve.State(null),this._activeGroupId=new ve.State(v),this._ready=new ve.State(!1),this._tasks=new ve.State([]),this._files=new ve.State([]),this._currentPath=new ve.State(`.`),this._groups=new ve.State([]),this._unreadGroupIds=new ve.State(/* @__PURE__ */ new Set),this._streamingText=new ve.State(null),this._aguiEvent=new ve.State(null),this._contextUsage=new ve.State(null),this._useProxy=new ve.State(!1),this._proxyUrl=new ve.State(`/proxy`),this._gitProxyUrl=new ve.State(`/git-proxy`),this._vmBashFullInternetAccess=new ve.State(!1),this._activePage=new ve.State(`pages`);let e=NG()?.sidebar?.defaultPage,t=e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`;this._sidebarDefaultPage=new ve.State(t),this._pages=new ve.State([]),this._pagesAllowList=new ve.State([]),this._pagesDenyList=new ve.State([]),this._activePinnedPage=new ve.State(null),this._defaultPinnedPage=new ve.State(null),this._remoteAgentStatusByGroup=new ve.State(/* @__PURE__ */ new Map),this._remoteAgentTypingByGroup=new ve.State(/* @__PURE__ */ new Map),this._peerStateByGroup=new ve.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 tG(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 wG(e,4500),Error(e)}let a=this.orchestrator?.router;if(!a){let e=`Network router is not initialized.`;throw wG(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:fe(),groupId:t,sender:`You`,content:``,timestamp:Date.now(),channel:i?`room`:`peerjs`,attachments:[n],isFromMe:!1,isTrigger:!1};await EW(this._db,e),this.orchestrator?.events.emit(`message`,e)}CG(`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),wG(`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(){ZU(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){QU(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 pe(e,b.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 WW(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await VU(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await de(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r)await zG(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 cW(e,t.id);await this.loadTasks(e)}async cloneConversation(e,t){let n=await SW(e,t);if(!n)return null;await aW(e,t,n.groupId),await oW(e,t,n.groupId);try{let r=await I(e,t,`MEMORY.md`);r&&await xe(e,n.groupId,`MEMORY.md`,r)}catch{}try{await AW(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-BQ2ZXoAc.js`);return t(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await gW(e,t);return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await yW(e,t),await iW(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 sW(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 zG(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 cW(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await bW(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 hW(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await PW(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,t){this._db=e,this.orchestrator=t,this._taskSyncOutbox=this.parseTaskSyncOutbox(await A(e,b.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)),t.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 EW(e,o)}else{let i=!t.startsWith(`peer:`),a={id:fe(),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 EW(e,a)}}),t.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])}),t.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),t.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)}),t.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),t.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))}),t.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)}),t.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),t.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`)}),t.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),t.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=VG(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),t.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),t.events.on(`ready`,()=>{this._ready.set(!0)}),t.events.on(`task-change`,()=>{this.loadTasks(e)}),t.events.on(`file-change`,()=>{this.loadFiles(e)}),t.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),t.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),t.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),t.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),t.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new bG(t.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=TG(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await ce(e),ue(),Ee(),await XU();let n=await A(e,b.PAGES_ALLOW_LIST),r=await A(e,b.PAGES_DENY_LIST);n&&this._pagesAllowList.set(jG(String(n))),r&&this._pagesDenyList.set(jG(String(r))),await XU();let i=typeof document<`u`&&document.getElementById(`shadow-claw-static-routing`)!==null,a=await A(e,b.PAGES_LIST),o=a==null?[]:this.parsePagesList(a),c=await yG(e,v,o);c.length>0?(this.setPages(c),await this.persistPages(e)):await this.ensureDefaultPage(e),await XU(),await this.applySiteConfigDefaults(e),await XU(),await this.loadGroups(e);let l=await A(e,b.LAST_ACTIVE_GROUP);l&&l!==this._activeGroupId.get()&&this._activeGroupId.set(l),await XU();let u=await A(e,b.LAST_ACTIVE_PAGE);u&&(this._activePage.set(u),this._hadPersistedActivePage=!0);let d=await A(e,b.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(d));let f=hG(),p=null;if(f&&(p=s(f)),!p){let t=await A(e,b.DEFAULT_PINNED_PAGE);t&&(p=s(t))}p&&this.isPageAllowed(p.path,p.groupId)&&this._defaultPinnedPage.set(p),await XU();let m=typeof window<`u`&&window.history?window.history.state:null,h=!!(m?.inFeedScroll||m?.scrollSpy||m?.suppressRouter)||typeof window<`u`&&window.location&&(()=>{let e=window.location.pathname||`/`,t=w();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`})(),g=!1;if(h&&p&&this.isPageAllowed(p.path,p.groupId)&&(this._activePinnedPage.set(p),g=!0),!g){let t=await A(e,b.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),g=!0)}catch{}}!g&&h&&this.effectiveDefaultPage&&this.isPageAllowed(this.effectiveDefaultPage.path,this.effectiveDefaultPage.groupId)&&(this._activePinnedPage.set(this.effectiveDefaultPage),g=!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[_,y,x]=await Promise.all([A(e,b.SIDEBAR_CHAT_HIDDEN),A(e,b.SIDEBAR_TASKS_HIDDEN),A(e,b.SIDEBAR_FILES_HIDDEN)]),S=NG(),C=S?.sidebar?.chatHidden,T=S?.sidebar?.tasksHidden,E=S?.sidebar?.filesHidden,ee=_==null?!!C:AG(_),D=y==null?!!T:AG(y),O=x==null?!!E:AG(x),k=()=>{let t=[];(!ee||this.activePage===`chat`)&&t.push(this.loadHistory()),(!D||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(i)typeof window.requestIdleCallback==`function`?window.requestIdleCallback(k,{timeout:2e3}):setTimeout(k,100);else{let t=[];(!ee||this.activePage===`chat`)&&t.push(this.loadHistory()),(!D||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),await Promise.all(t)}await XU(),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await ae(e));let r=await MW(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await bW(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await dW(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await de(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 BG(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 DW(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),wG(`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 UW(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await VU(t,!0);let c=s||await BU(t);if(o.length===0&&!c){if(await HU(t,`br:main`))o.push({groupId:v,path:e.DEFAULT_PAGE_PATH});else return}this.setPages(o);let l=this._defaultPinnedPage.get();l&&l.path===i&&l.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 UW(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await VU(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await _W(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await xW(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await kW(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await RG(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 RG(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await zG(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 OW(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:${fe()}`: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 pe(e,b.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await pe(e,b.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){t&&!this.isPageAllowed(t.path,t.groupId)&&(t=this.effectiveDefaultPage),this._activePinnedPage.set(t),t?await pe(e,b.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await pe(e,b.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 pe(e,b.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await pe(e,b.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 ae(e));let i=await MW(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await eW(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await tW(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await nW(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await rW(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 pe(e,b.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await DW(e,r),await this.loadTasks(e),await RG(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 CW(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await TW(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await wW(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await vW(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await DW(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await RG(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 uW(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:v,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:v,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 BU(t))return;let n=await HU(t,v);await qU(t,v),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:v,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 hW(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!IG(await A(this._db,b.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 iG(e,`br:main`))return;let t=await A(e,b.PAGES_LIST),n=t==null?[]:this.parsePagesList(t),r=await yG(e,v,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 pe(e,b.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await pe(e,b.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 t=NG();if(!t||typeof t!=`object`)return;me(t),ue(),Ee();let n=t.customElements;if((await bW(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await vW(e,v,void 0),(t.settings?.internetAccess??t.settings?.vm_bash_full_internet_access??t.settings?.fullInternetAccess??t.internetAccess)===!0&&await A(e,b.VM_BASH_FULL_INTERNET_ACCESS)!==`true`&&(await pe(e,b.VM_BASH_FULL_INTERNET_ACCESS,`true`),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=!0),this._vmBashFullInternetAccess.set(!0)),t.pages&&typeof t.pages==`object`){let{defaultPinnedPage:n}=t.pages;if(n&&typeof n==`string`){let t=s(n);t&&this.isPageAllowed(t.path,t.groupId)&&(this._defaultPinnedPage.set(t),await pe(e,b.DEFAULT_PINNED_PAGE,JSON.stringify(t)))}}let r=t.allowedCustomElements||(typeof n==`object`&&!Array.isArray(n)?n.allowedElements:void 0);r!==void 0&&(await A(e,b.ALLOWED_CUSTOM_ELEMENTS)??await pe(e,b.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(r)));let i=t.allowedCustomElementDomains||(typeof n==`object`&&!Array.isArray(n)?n.allowedDomains:void 0);if(i!==void 0&&(await A(e,b.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS)??await pe(e,b.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(i))),t.sidebar&&typeof t.sidebar==`object`){let{pagesHidden:n,chatHidden:r,tasksHidden:i,filesHidden:a,defaultPage:o}=t.sidebar;if(n!==void 0&&(await A(e,b.SIDEBAR_PAGES_HIDDEN)??await pe(e,b.SIDEBAR_PAGES_HIDDEN,String(!!n))),r!==void 0&&(await A(e,b.SIDEBAR_CHAT_HIDDEN)??await pe(e,b.SIDEBAR_CHAT_HIDDEN,String(!!r))),i!==void 0&&(await A(e,b.SIDEBAR_TASKS_HIDDEN)??await pe(e,b.SIDEBAR_TASKS_HIDDEN,String(!!i))),a!==void 0&&(await A(e,b.SIDEBAR_FILES_HIDDEN)??await pe(e,b.SIDEBAR_FILES_HIDDEN,String(!!a))),o&&typeof o==`string`){let t=this.normalizeSidebarDefaultPage(o);this._sidebarDefaultPage.set(t),await A(e,b.SIDEBAR_DEFAULT_PAGE)||await pe(e,b.SIDEBAR_DEFAULT_PAGE,o)}}if(t.settings&&typeof t.settings==`object`){let{assistantName:n,defaultProvider:r,provider:i,defaultModel:a,model:o}=t.settings;n&&typeof n==`string`&&(await A(e,b.ASSISTANT_NAME)||await pe(e,b.ASSISTANT_NAME,n));let s=r??i;if(typeof s==`string`&&s.trim().length>0&&!await A(e,b.PROVIDER)){let t=s.trim();await pe(e,b.PROVIDER,t),this.orchestrator&&(this.orchestrator.provider=t)}let c=a??o;if(typeof c==`string`&&c.trim().length>0&&!await A(e,b.MODEL)){let t=c.trim();await pe(e,b.MODEL,t),this.orchestrator&&(this.orchestrator.model=t)}let l=t.settings.internetAccess??t.settings.vm_bash_full_internet_access??t.settings.fullInternetAccess??t.internetAccess;typeof l==`boolean`&&(await A(e,b.VM_BASH_FULL_INTERNET_ACCESS)??(await pe(e,b.VM_BASH_FULL_INTERNET_ACCESS,String(l)),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=l),this._vmBashFullInternetAccess.set(l)))}let a=(t.settings&&typeof t.settings==`object`?t.settings.defaultToolsProfile:void 0)??t.defaultToolsProfile;if(typeof a==`string`&&a.trim().length>0&&!await A(e,b.ACTIVE_TOOL_PROFILE)){let t=a.trim();if(t.toLowerCase()===`none`)await we.deactivateProfile(e);else{let n=we.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await we.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(t.pages&&typeof t.pages==`object`){let{defaultPinnedPage:n}=t.pages;n&&typeof n==`string`&&(await A(e,b.DEFAULT_PINNED_PAGE)||await pe(e,b.DEFAULT_PINNED_PAGE,n))}let o=t.pages?.allowList??t.pages?.allowlist??t.allowList??t.allowlist,c=t.pages?.denyList??t.pages?.denylist??t.denyList??t.denylist;if(Array.isArray(o)&&await A(e,b.PAGES_ALLOW_LIST)==null){let t=GW(o.map(String));this._pagesAllowList.set(t),await pe(e,b.PAGES_ALLOW_LIST,JSON.stringify(t))}if(Array.isArray(c)&&await A(e,b.PAGES_DENY_LIST)==null){let t=GW(c.map(String));this._pagesDenyList.set(t),await pe(e,b.PAGES_DENY_LIST,JSON.stringify(t))}await pe(e,b.SITE_CONFIG_SEEDED,`true`);let l=this._pages.get(),u=l.filter(e=>this.isPageAllowed(e.path,e.groupId));u.length!==l.length&&(this.setPages(u),await this.persistPages(e));let d=this._activePinnedPage.get();d&&!this.isPageAllowed(d.path,d.groupId)&&await this.setActivePinnedPage(e,this.effectiveDefaultPage);let f=this._defaultPinnedPage.get();if(f&&!this.isPageAllowed(f.path,f.groupId)&&await this.setDefaultPinnedPage(e,null),Array.isArray(t.enabledTools)){let n=t.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await we.setAllEnabled(e,n),await we.setAllDeclarativeEnabled(e,n)}await pe(e,b.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const UG=new HG;async function WG(e,t,n){let r=await re(e,t),{dirs:i,filename:a}=M(n),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a),t===`br:main`&&i.length===0&&(a===`MEMORY.md`?await VU(e,!0):a===`index.html`&&await KU(e,!0));try{await UW(e,t,n)}catch{}try{await UG.removePage(e,n,t)}catch{}}async function GG(e,t,n){let r=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean);if(r.length===0)throw Error(`Empty directory path`);for(let n=0;n<2;n++)try{let n=await re(e,t);for(let e of r)n=await n.getDirectoryHandle(e,{create:!0});return}catch(e){if(n===0&&oe(e)){ie();continue}throw e}}var KG=class extends zL{db;groupId;workspacePrefix;constructor(e,t,n,r=`/home/user`){super(n),this.db=e,this.groupId=t,this.workspacePrefix=r}async appendFile(e,t){await super.appendFile(e,t);let n=this._toDbPath(e);if(n!==null){let t=await this._readPathContent(e);await xe(this.db,this.groupId,n,t)}}async cp(e,t,n){await super.cp(e,t,n);let r=this._toDbPath(t);if(r!==null)try{let e=await super.stat(t);if(!this._isDirectoryStat(e)){let e=await this._readPathContent(t);await xe(this.db,this.groupId,r,e)}}catch{}}async mkdir(e,t){await super.mkdir(e,t);let n=this._toDbPath(e);n!==null&&n!==``&&await GG(this.db,this.groupId,n)}async mv(e,t){await super.mv(e,t);let n=!1,r=t,i=this._toDbPath(t);if(i!==null)try{let i=await super.stat(t);if(this._isDirectoryStat(i)){let n=this._basename(e);n&&(r=this._joinPath(t,n))}let a=await super.stat(r);if(!this._isDirectoryStat(a)){let e=this._toDbPath(r);if(e!==null){let t=await this._readPathContent(r);await xe(this.db,this.groupId,e,t),n=!0}}}catch{}let a=this._toDbPath(e);if(a!==null)try{(i===null||n)&&await WG(this.db,this.groupId,a)}catch{}}async rm(e,t){await super.rm(e,t);let n=this._toDbPath(e);if(n!==null)try{await WG(this.db,this.groupId,n)}catch{}}async writeFile(e,t,n){await super.writeFile(e,t,n);let r=this._toDbPath(e);if(r!==null){let t=await this._readPathContent(e);await xe(this.db,this.groupId,r,t)}}_basename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]||``}_isDirectoryStat(e){return e&&typeof e.isDirectory==`function`?!!e.isDirectory():!!e?.isDirectory}_joinPath(e,t){let n=e.replace(/\/+$/,``);return n?`${n}/${t}`:`/${t}`}_toDbPath(e){return e.startsWith(this.workspacePrefix+`/`)?e.slice(this.workspacePrefix.length+1):e===this.workspacePrefix?``:null}async _readPathContent(e){try{return await super.readFileBuffer(e)}catch{return await super.readFile(e)}}};async function qG(e,t){let n={},r=/* @__PURE__ */ new Set,i=`/home/user`;async function a(o){let s=await MW(e,t,o);for(let c of s)if(c.endsWith(`/`)){let e=c.slice(0,-1),t=o===`.`?e:`${o}/${e}`;r.add(t),await a(t)}else{let r=o===`.`?c:`${o}/${c}`,a=`${i}/${r}`;n[a]=async()=>{try{return await IU(e,t,r)}catch{return``}}}}await a(`.`);let o=new KG(e,t,n,i);for(let e of[...r].sort((e,t)=>e.split(`/`).length-t.split(`/`).length))try{o.mkdirSync(`${i}/${e}`,{recursive:!0})}catch{}return o}async function JG(e,t,n,r={},i=30,a=!1){try{let i=await new MU({fs:await qG(e,n),network:{dangerouslyAllowFullInternetAccess:a,denyPrivateRanges:!a}}).exec(t,{env:{HOME:`/home/user`,PATH:`/usr/bin`,PWD:`/home/user`,...r}});return{stdout:i.stdout||``,stderr:i.stderr||``,exitCode:i.exitCode??0}}catch(e){return{stdout:``,stderr:e instanceof Error?e.message:String(e),exitCode:1}}}function YG(e){let t=e.stdout||``;return e.stderr&&(t+=(t?`
|
|
1804
1804
|
`:``)+e.stderr),e.exitCode!==0&&!t&&(t=`[exit code: ${e.exitCode}]`),t||`(no output)`}async function XG(e,t,n,r,i){return YG(await JG(e,t,n,{},r,i))}async function ZG(e){return kG(await A(e,b.VM_BASH_FULL_INTERNET_ACCESS))??!1}async function QG(e){if(bn())return!0;let t=Date.now()+e;for(;Date.now()<t;)if(await new Promise(e=>{setTimeout(e,50)}),bn())return!0;return bn()}async function $G(e,t,n){let r=await A(e,b.VM_BASH_TIMEOUT_SEC),i=Number(r),a=Number.isFinite(i)?Math.min(Math.max(i,1),_):900,o=Number(t.timeout),s=Number.isFinite(o)?Math.min(Math.max(o,1),_):a,c=await ZG(e),l=Cn(),u=t.stdin?String(t.stdin):``,d=u.length>0,f=`.shadowclaw_stdin`,p=t.command;if(te()){let e=globalThis.__headlessBashExecutor;if(typeof e==`function`)return e({command:p,stdin:u,timeoutSec:s});throw Error(`Headless bash executor is not configured. Register nativeBashExecutor before executing bash in headless mode.`)}if(d){if(l===`ext2`){let e=`EOF_SC_${Date.now()}`;p=`(cat << '${e}'\n${u}\n${e}\n) | (${p})`}else p=`{\n${p}\n} < /home/user/${f}; _code=$?; rm -f /home/user/${f}; exit $_code`}try{if(d&&l!==`ext2`&&await xe(e,n,f,u),l===`disabled`)return await XG(e,p,n,s,c);if(!bn()){await _n();let e=xn();!bn()&&e.booting&&await QG(Math.min(s*1e3,3e4))}if(bn())return await vn(p,s,{db:e,groupId:n});let t=xn();return B({type:`show-toast`,payload:{duration:7e3,message:`WebVM unavailable for this bash command. ${t.error?`Reason: ${t.error}`:t.booting?`Reason: WebVM is still booting.`:`Reason: WebVM is unavailable.`} Falling back to JavaScript Bash Emulator and retrying WebVM on the next command.`,type:`warning`}}),await XG(e,p,n,s,c)}finally{d&&l!==`ext2`&&await WG(e,n,f).catch(()=>{})}}async function eK(e,t,n,r){let{dirs:i,filename:a}=M(n);for(let n=0;n<2;n++)try{let n=await re(e,t);for(let e of i)n=await n.getDirectoryHandle(e,{create:!0});let o=await n.getFileHandle(a,{create:!0});try{await ye(o,r);return}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await ae(e)).type===`opfs`))throw t}let s=t.replace(/:/g,`-`);await he([F(),`groups`,s,...i,a],r);return}catch(e){if(n===0&&oe(e)){ie();continue}throw e}}const tK=[{id:`imap`,name:`IMAP Mail`,protocol:`imap`,description:`Read mailboxes and fetch message metadata/content.`,version:`0.1.0`,actions:[`messages.read`,`messages.send`],authTypes:[`basic_userpass`,`oauth`],serviceTypes:[`http_api`],configurableFields:[`host`,`port`,`secure`,`mailboxPath`,`smtpHost`,`smtpPort`,`smtpSecure`,`fromAddress`,`executionMode`,`pollIntervalSec`]}];function nK(){return[...tK].sort((e,t)=>e.id.localeCompare(t.id))}function rK(e){return e&&tK.find(t=>t.id===e)||null}function iK(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.serviceType||!t.authType?null:{serviceType:t.serviceType,authType:t.authType,providerId:t.providerId||void 0,accountId:t.accountId||void 0,username:t.username||void 0,headerName:t.headerName||void 0,encryptedSecret:t.encryptedSecret||void 0}}function aK(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.id||!t.label||!t.pluginId||typeof t.enabled!=`boolean`||typeof t.createdAt!=`number`||typeof t.updatedAt!=`number`||!rK(t.pluginId)?null:{id:t.id,label:t.label,pluginId:t.pluginId,enabled:t.enabled,config:t.config&&typeof t.config==`object`?{...t.config}:{},credentialRef:iK(t.credentialRef),createdAt:t.createdAt,updatedAt:t.updatedAt}}async function oK(e){let t=await A(e,b.INTEGRATION_CONNECTIONS);if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=aK(e);t&&n.push(t)}return n}async function sK(e,t){await pe(e,b.INTEGRATION_CONNECTIONS,t)}async function cK(e){return oK(e)}async function lK(e,t){if(!t)return null;let n=await oK(e);return n.find(e=>e.id===t)||n.find(e=>e.label.toLowerCase()===t.toLowerCase())||null}async function uK(e,t){if(!t.label?.trim())throw Error(`Email connection label is required`);let n=rK(t.pluginId);if(!n)throw Error(`Unknown email plugin: ${t.pluginId}`);let r=await oK(e),i=Date.now();if(t.id){let a=r.findIndex(e=>e.id===t.id);if(a!==-1){let o=r[a],s={...o,label:t.label.trim(),pluginId:n.id,enabled:t.enabled??o.enabled,config:t.config?{...t.config}:o.config,updatedAt:i};return r[a]=s,await sK(e,r),s}}let a={id:t.id||fe(),label:t.label.trim(),pluginId:n.id,enabled:t.enabled??!0,config:t.config?{...t.config}:{},credentialRef:null,createdAt:i,updatedAt:i};return r.push(a),await sK(e,r),a}async function dK(e,t,n){if(!t)return null;let r=await oK(e),i=r.findIndex(e=>e.id===t);if(i===-1)return null;let a={...r[i],credentialRef:n?iK(n):null,updatedAt:Date.now()};return r[i]=a,await sK(e,r),a}async function fK(e,t){if(!t)return!1;let n=await oK(e),r=n.filter(e=>e.id!==t);return r.length!==n.length&&(await sK(e,r),!0)}function pK(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n==`string`){let e=n.trim();e&&t.push({path:e});continue}if(!n||typeof n!=`object`)continue;let e=typeof n.path==`string`?n.path.trim():``;if(!e)continue;let r=typeof n.filename==`string`?n.filename.trim():``,i=typeof n.content_type==`string`?n.content_type.trim():``;t.push({path:e,filename:r||void 0,contentType:i||void 0})}return t}function mK(e,t,n){if(e==null||e===``||typeof e==`boolean`)return t;let r=typeof e==`number`?e:Number(e);if(!Number.isFinite(r))return t;let i=r;return typeof n?.min==`number`&&(i=Math.max(n.min,i)),typeof n?.max==`number`&&(i=Math.min(n.max,i)),i}function hK(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function gK(e){if(!Array.isArray(e))return[];let t=e.map(e=>typeof e==`number`?e:Number(e)).filter(e=>Number.isFinite(e)&&e>0).map(e=>Math.floor(e));return Array.from(new Set(t))}const _K=mK,vK=hK,yK=gK;function bK(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n){let i=e.subarray(r,r+n);t+=String.fromCharCode(...i)}return btoa(t)}function xK(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function SK(e,t=`attachment.bin`){if(!e)return t;let n=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);return n[n.length-1]||t}function CK(e,t={}){let n=t.replacement??`_`,r=t.fallback??`attachment.bin`,i=e.trim();t.stripControlChars&&(i=i.replace(/[\u0000-\u001f\u007f]+/g,``)),t.stripLeadingDots&&(i=i.replace(/^\.+/,``));let a=t.stripControlChars?/[\\/:*?"<>|]/g:/[\\/:*?"<>|\x00-\x1f\u007f]/g;if(t.collapseReplacement&&n){let e=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);i=i.replace(t.stripControlChars?/[\\/:*?"<>|]+/g:/[\\/:*?"<>|\x00-\x1f\u007f]+/g,n),i=i.replace(RegExp(`${e}+`,`g`),n)}else i=i.replace(a,n);return i=i.trim(),t.stripLeadingDots&&(i=i.replace(/^\.+/,``).trim()),i||r}const wK={apng:`image/apng`,avif:`image/avif`,bmp:`image/bmp`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,ico:`image/x-icon`,jpeg:`image/jpeg`,jpg:`image/jpeg`,png:`image/png`,svg:`image/svg+xml`,tif:`image/tiff`,tiff:`image/tiff`,webp:`image/webp`},TK={...wK,"3gp":`video/3gpp`,aac:`audio/aac`,avi:`video/x-msvideo`,bin:`application/octet-stream`,css:`text/css`,csv:`text/csv`,db:`application/vnd.sqlite3`,dll:`application/octet-stream`,dmg:`application/octet-stream`,dylib:`application/octet-stream`,exe:`application/vnd.microsoft.portable-executable`,flac:`audio/flac`,flv:`video/x-flv`,gz:`application/gzip`,htm:`text/html`,html:`text/html`,iso:`application/octet-stream`,js:`text/javascript`,json:`application/json`,m4a:`audio/mp4`,m4v:`video/mp4`,markdown:`text/markdown`,md:`text/markdown`,mjs:`text/javascript`,mkv:`video/x-matroska`,mov:`video/mp4`,mp3:`audio/mpeg`,mp4:`video/mp4`,oga:`audio/ogg`,ogg:`audio/ogg`,ogv:`video/ogg`,pdf:`application/pdf`,rar:`application/vnd.rar`,so:`application/octet-stream`,sqlite:`application/vnd.sqlite3`,sqlite3:`application/vnd.sqlite3`,tar:`application/x-tar`,ts:`text/typescript`,tsx:`text/typescript`,txt:`text/plain`,wasm:`application/wasm`,wav:`audio/wav`,weba:`audio/webm`,webm:`video/webm`,wmv:`video/x-ms-wmv`,xml:`application/xml`,yaml:`text/yaml`,yml:`text/yaml`,zip:`application/zip`};function EK(e){return e&&(e.split(/[?#]/,1)[0].replace(/\\/g,`/`).split(`/`).pop()||``).toLowerCase().split(`.`).pop()||``}function DK(e,t){let n=EK(e);return TK[n]??t}function OK(e){let t=EK(e);return wK[t]||null}function kK(e){return OK(e)!==null}function AK(e){let t=EK(e);if(t===`md`||t===`markdown`||t===`txt`)return`text/plain`;if(t===`pdf`)return`application/pdf`;if(wK[t])return wK[t]}async function jK(e,t,n,r=!1){let i=(typeof n.username==`string`?n.username.trim():``)||t.credentialRef?.username||(typeof t.config.username==`string`?t.config.username:``);if(!i)return`Error: Integration connection ${t.id} is missing username credentials.`;if(t.credentialRef?.authType===`oauth`){let n=t.credentialRef.accountId;if(!n)return`Error: Integration connection ${t.id} is missing linked OAuth account.`;let a=await L(e,void 0,{accountId:n,authMode:`oauth`,forceRefresh:r});if(!a||a.reauthRequired||!a.token){let e=t.credentialRef?.providerId||`the configured`;return`Error: OAuth account reconnect required for integration ${t.id}.\nOpen Settings -> Integrations, edit this email connection, and click Connect OAuth for ${e} to re-authorize.`}return{authType:`oauth`,username:i,accessToken:a.token}}let a=(typeof n.password==`string`?n.password.trim():``)||t.credentialRef?.encryptedSecret&&await Re(t.credentialRef.encryptedSecret)||``;return a?{authType:`basic_userpass`,username:i,password:a}:`Error: Integration connection ${t.id} is missing password credentials.`}async function MK(e,t,n,r){let i=CK(r),a=i.lastIndexOf(`.`),o=a>0?i.slice(0,a):i,s=a>0?i.slice(a):``,c=n.trim().replace(/^\/+|\/+$/g,``);for(let n=0;n<1e3;n++){let r=n===0?i:`${o}-${n+1}${s}`,a=c?`${c}/${r}`:r;if(!await P(e,t,a))return a}return c?`${c}/${fe()}-${i}`:`${fe()}-${i}`}async function NK(e,t,n){let r=typeof t.action==`string`?t.action.trim():``;if(!r)return`Error: manage_email requires action.`;if(r===`list_plugins`){let e=nK();return e.length?e.map(e=>`- ${e.id} (${e.protocol})\n Name: ${e.name}\n Actions: ${e.actions.join(`, `)}\n Auth: ${e.authTypes.join(`, `)}\n Fields: ${e.configurableFields.join(`, `)||`(none)`}`).join(`
|
|
1805
1805
|
|
|
1806
1806
|
`):`No integration plugins are available.`}if(r===`list_connections`){let t=await cK(e);return t.length?t.map(e=>{let t=rK(e.pluginId),n=Object.keys(e.config||{});return`- ${e.id} (${e.label})\n Plugin: ${e.pluginId}${t?` (${t.name})`:``}\n Enabled: ${e.enabled}\n Config keys: ${n.join(`, `)||`(none)`}`}).join(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{et as e}from"./config-C16fFWtP.js";import{n as t}from"./mime-ClqNyXPc.js";function n(e=``,n=``){let r=(e&&e!==`application/octet-stream`?e:t(n)||e).toLowerCase(),i=n.toLowerCase();return r.startsWith(`text/`)||r.includes(`json`)||r.includes(`xml`)||i.endsWith(`.md`)||i.endsWith(`.txt`)?`text`:r.startsWith(`image/`)?`image`:r.startsWith(`audio/`)?`audio`:r.startsWith(`video/`)?`video`:r===`application/pdf`||i.endsWith(`.pdf`)?`document`:`file`}function r(t){let n=(t||``).toLowerCase(),r=e.getModelInfo(n);if(r){let e=r.supportsImageInput===!0||r.routesByRequestFeatures===!0,t=r.supportsAudioInput===!0||r.routesByRequestFeatures===!0,n=r.supportsVideoInput===!0||r.routesByRequestFeatures===!0,i=r.supportsDocumentInput===!0||r.routesByRequestFeatures===!0;if(r.supportsImageInput!==void 0||r.supportsAudioInput!==void 0||r.supportsVideoInput!==void 0||r.supportsDocumentInput!==void 0||r.routesByRequestFeatures)return{images:e,audio:t,video:n,documents:i,routerByFeatures:!!r.routesByRequestFeatures,source:`metadata`}}let i=n.includes(`no-vision`)||n.includes(`non-vision`)||n.includes(`text-only`),a=n===`openrouter/free`||n===`openrouter/auto`,o=!i&&[`gpt-4o`,`gpt-4.1`,`gpt-5`,`gpt-6`,`astra`,`claude-3`,`claude-4`,`claude-5`,`claude-sonnet`,`claude-haiku`,`claude-opus`,`claude-fable`,`claude-mythos`,`gemini`,`omni`,`llava`,`qwen-vl`,`-vl`,`vision`,`pixtral`].some(e=>n.includes(e)),s=!i&&(n.includes(`claude-3-5`)||n.includes(`claude-3.5`)||n.includes(`claude-3-7`)||n.includes(`claude-3.7`)||n.includes(`claude-4`)||n.includes(`claude-5`)||n.includes(`claude-fable`)||n.includes(`claude-mythos`)||n.includes(`gemini`)||n.includes(`gpt-4.1`)||n.includes(`gpt-5`)||n.includes(`gpt-6`)||n.includes(`astra`)||/claude-(?:sonnet|haiku|opus|fable|mythos)-\d/.test(n));return o?{images:!0,audio:n.includes(`omni`)||n.includes(`audio`),video:n.includes(`omni`)||n.includes(`video`)||n.includes(`gemini`),documents:s,routerByFeatures:a,source:`heuristic`}:{images:!1,audio:!1,video:!1,documents:!1,routerByFeatures:a,source:`unknown`}}function i(e){let t=r(e),n=[t.images?`images native`:`images fallback`,t.audio?`audio native`:`audio fallback`,t.video?`video native`:`video fallback`,t.documents?`PDFs native`:`PDFs fallback`];return t.routerByFeatures&&n.push(`router can adapt by request features`),n.join(` · `)}export{n,r,i as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as e,r as t}from"./config-
|
|
1
|
+
import{o as e,r as t}from"./config-C16fFWtP.js";import{t as n}from"./get-config-Bkvl__ZS.js";import{c as r,t as i}from"./orchestrator-Li1UAsv7.js";import{t as a}from"./set-config-DSiuMe0k.js";import{r as o}from"./crypto-4ETeplbS.js";function s(e,t){return e.channelRegistry?.getChannelType(t)??`browser`}function c(e,t){switch(t){case`browser`:return e.browserChat;case`telegram`:return e.telegram;case`imessage`:return e.imessage;case`peerjs`:return e.peerjs;default:return null}}function l(e,t){return t===`browser`||e.channelEnabledByType[t]!==!1}function u(e){return{enabled:l(e,`peerjs`),myAlias:e.peerjsMyAlias,myPeerId:e.peerjsMyPeerId,peerAliases:{...e.peerjsPeerAliases},serverHost:e.peerjsServerHost,serverPath:e.peerjsServerPath,serverPort:e.peerjsServerPort,serverSecure:e.peerjsServerSecure,trustedPeerIds:[...e.peerjsTrustedPeerIds]}}function d(e){return{botToken:e.telegramBotToken,chatIds:[...e.telegramChatIds],enabled:l(e,`telegram`),useProxy:e.telegramUseProxy}}function f(e){return{apiKey:e.imessageApiKey,chatIds:[...e.imessageChatIds],enabled:l(e,`imessage`),serverUrl:e.imessageServerUrl}}function p(e){return`${t.CHANNEL_ENABLED_PREFIX}${e}`}function m(e,t){if(t===`browser`)return!0;if(!l(e,t))return!1;switch(t){case`telegram`:return e.telegramBotToken.length>0;case`imessage`:return e.imessageServerUrl.length>0;case`peerjs`:return e.peerjsMyPeerId.length>0;default:return!0}}function h(e,t,n=!1){let r=c(e,t);r&&(m(e,t)?r.running?typeof r.ensureConnected==`function`&&r.ensureConnected(n):r.start():r.stop())}function g(e,t=!1){h(e,`browser`,t),h(e,`telegram`,t),h(e,`imessage`,t),h(e,`peerjs`,t)}function _(e){i.setRemoteAgentTyping(e,!1)}async function v(e,t,r=n){let i=await r(t,p(e));return i?i!==`false`:!1}async function y(e,t,n,r,i=a){if(n===`browser`)return;let o=!!r;e.channelEnabledByType[n]=o,await i(t,p(n),o?`true`:`false`),h(e,n)}function b(t,n,r=e,i=[],a){t.browserChat.submit(n,r,i,a)}async function x(e,t,n,r=a){if(!n){await r(e,t,``);return}let i=await o(n);if(!i)throw Error(`Failed to encrypt secret config for ${t}`);await r(e,t,i)}async function S(e,n,i,o,s,c=a,u=x){let d=i.trim().replace(/\/+$/,``),f=o.trim(),p=r(s);e.imessageServerUrl=d,e.imessageApiKey=f,e.imessageChatIds=p,await c(n,t.IMESSAGE_SERVER_URL,d),await u(n,t.IMESSAGE_API_KEY,f),await c(n,t.IMESSAGE_CHAT_IDS,JSON.stringify(p)),e.imessage.stop(),e.imessage.configure(d,f,p),d&&l(e,`imessage`)&&e.imessage.start()}async function C(e,n,i,o,s=!1,c=a,u=x){let d=i.trim(),f=r(o),p=!!s;e.telegramBotToken=d,e.telegramChatIds=f,e.telegramUseProxy=p,await u(n,t.TELEGRAM_BOT_TOKEN,d),await c(n,t.TELEGRAM_CHAT_IDS,JSON.stringify(f)),await c(n,t.TELEGRAM_USE_PROXY,p?`true`:`false`),e.telegram.stop(),e.telegram.configure(d,f,p),d&&l(e,`telegram`)&&e.telegram.start()}export{l as a,u as c,y as d,b as f,C as i,d as l,_ as n,s as o,S as r,f as s,g as t,v as u};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{et as e}from"./config-C16fFWtP.js";import{n as t}from"./create-model-cache-fetch-B0mSCEk6.js";var n=Object.defineProperty,r=(e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,i=(e,t,n)=>(r(e,typeof t==`symbol`?t:t+``,n),n),a=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ExponentiationBinaryOperator:`ExponentiationBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`});a.OpenStatement,a.CloseStatement,a.OpenExpression,a.CloseExpression,a.OpenParen,a.CloseParen,a.OpenCurlyBracket,a.CloseCurlyBracket,a.OpenSquareBracket,a.CloseSquareBracket,a.Comma,a.Dot,a.Colon,a.Pipe,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.AdditiveBinaryOperator,a.AdditiveBinaryOperator,a.AdditiveBinaryOperator,a.ExponentiationBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.Equals;function o(e){return e.replace(/\b\w/g,e=>e.toUpperCase())}function s(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function c(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?/* @__PURE__ */ RegExp(`(?=)`,`gu`):new RegExp(s(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var l=/* @__PURE__ */ new Map,u=class{type=`RuntimeValue`;value;get builtins(){return l}constructor(e=void 0){this.value=e}__bool__(){return new m(!!this.value)}toString(){return String(this.value)}},d=class extends u{type=`IntegerValue`},f=class extends u{type=`FloatValue`;toString(){return Object.is(this.value,-0)?`-0.0`:this.value%1==0?this.value.toFixed(1):this.value.toString()}},p=class extends u{type=`StringValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`upper`,new S(()=>new p(this.value.toUpperCase()))],[`lower`,new S(()=>new p(this.value.toLowerCase()))],[`strip`,new S(()=>new p(this.value.trim()))],[`title`,new S(()=>new p(o(this.value)))],[`capitalize`,new S(()=>new p(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new d(this.value.length)],[`rstrip`,new S(()=>new p(this.value.trimEnd()))],[`lstrip`,new S(()=>new p(this.value.trimStart()))],[`startswith`,new S(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof p)return new m(this.value.startsWith(t.value));if(t instanceof x){for(let e of t.value){if(!(e instanceof p))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new m(!0)}return new m(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new S(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof p)return new m(this.value.endsWith(t.value));if(t instanceof x){for(let e of t.value){if(!(e instanceof p))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new m(!0)}return new m(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new S(e=>{let t=e[0]??new C;if(!(t instanceof p||t instanceof C))throw Error(`sep argument must be a string or null`);let n=e[1]??new d(-1);if(!(n instanceof d))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof C){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new x(r.map(e=>new p(e)))})],[`replace`,new S(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof p&&n instanceof p))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new C:e[2]:new C,!(r instanceof d||r instanceof C))throw Error(`replace() count argument must be a number or null`);return new p(c(this.value,t.value,n.value,r.value))})]])}},m=class extends u{type=`BooleanValue`},h=/[\x7f-\uffff]/g;function g(e){return e.replace(h,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function _(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=g(t)),t}case`ArrayValue`:case`NamespaceValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=`
|
|
2
2
|
`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>_(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=g(s));let c=`${s}${l}${_(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var v=class extends u{type=`ObjectValue`;_builtins;__bool__(){return new m(this.value.size>0)}get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`get`,new S(([e,t])=>{if(!(e instanceof p))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new C})],[`items`,new S(()=>this.items())],[`keys`,new S(()=>this.keys())],[`values`,new S(()=>this.values())],[`dictsort`,new S(e=>{let t=/* @__PURE__ */ new Map,n=e.filter(e=>e instanceof y?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new m(!1);if(!(r instanceof m))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new p(`key`);if(!(i instanceof p))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new m(!1);if(!(a instanceof m))throw Error(`reverse must be a boolean`);return new x(Array.from(this.value.entries()).map(([e,t])=>new x([new p(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=k(o,s,r.value);return a.value?-c:c}))})]])}items(){return new x(Array.from(this.value.entries()).map(([e,t])=>new x([new p(e),t])))}keys(){return new x(Array.from(this.value.keys()).map(e=>new p(e)))}values(){return new x(Array.from(this.value.values()))}toString(){return _(this,{},0,!1)}},y=class extends v{type=`KeywordArgumentsValue`},b=class extends u{type=`NamespaceValue`;toString(){return _(this,{},0,!1)}},x=class extends u{type=`ArrayValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`length`,new d(this.value.length)]])}__bool__(){return new m(this.value.length>0)}toString(){return _(this,{},0,!1)}},S=class extends u{type=`FunctionValue`},C=class extends u{type=`NullValue`},w=class extends u{type=`UndefinedValue`};function T(e){let t;if(e instanceof x?t=e.value:e instanceof p&&(t=Array.from(e.value,e=>new p(e))),!t||t.length!==2)throw Error(`namespace expected an object or an iterable of [key, value] pairs`);let[n,r]=t;if(!(n instanceof p))throw Error(`namespace keys must be strings`);return[n,r]}var E=class{constructor(e){this.parent=e}variables=/* @__PURE__ */ new Map([[`namespace`,new S(e=>{let t=e.slice(),n;if(t.at(-1)instanceof y&&(n=t.pop()),t.length>1)throw Error(`namespace expected at most 1 argument, got ${t.length}`);let r=/* @__PURE__ */ new Map;if(t.length===1){let e=t[0];if(e instanceof v)for(let[t,n]of e.value)r.set(t,n);else if(e instanceof x)for(let t of e.value){let[e,n]=T(t);r.set(e.value,n)}else throw Error(`'${e.type}' object is not iterable`)}if(n)for(let[e,t]of n.value)r.set(e,t);return new b(r)})]]);tests=E.TESTS;set(e,t){return this.declareVariable(e,A(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new w}catch{return new w}}};i(E,`TESTS`,/* @__PURE__ */ new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof S],[`odd`,e=>{if(!(e instanceof d))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof d))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof d||e instanceof f],[`integer`,e=>e instanceof d],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof v],[`sequence`,e=>e instanceof x||e instanceof v||e instanceof p],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]));function D(e){return e instanceof d||e instanceof f||e instanceof m}function O(e){return e instanceof m?Number(e.value):e.value}function k(e,t,n=!1){if(e instanceof C&&t instanceof C)return 0;if(e instanceof C||t instanceof C)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof w&&t instanceof w)return 0;if(e instanceof w||t instanceof w)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(D(e)&&D(t)){let n=O(e),r=O(t);return n<r?-1:+(n>r)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),r<i?-1:+(r>i)}default:throw Error(`Cannot compare type: ${e.type}`)}}function A(e){switch(typeof e){case`number`:return Number.isInteger(e)?new d(e):new f(e);case`string`:return new p(e);case`boolean`:return new m(e);case`undefined`:return new w;case`object`:return e===null?new C:Array.isArray(e)?new x(e.map(A)):new v(new Map(Object.entries(e).map(([e,t])=>[e,A(t)])));case`function`:return new S((t,n)=>A(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});const j=/* @__PURE__ */ new Map;function M(e){return typeof e==`string`?e:e?Array.isArray(e)?e.map(e=>{if(!e)return``;if(typeof e==`string`)return e;if(e.type===`text`)return e.text||e.value||``;if(e.type===`tool_use`)return`[TOOL_CALL ${e.name}] ${JSON.stringify(e.input||{})}`;if(e.type===`tool_result`){let t=typeof e.content==`string`?e.content:JSON.stringify(e.content||``);return`[TOOL_RESULT ${e.tool_use_id||``}] ${t}`}return e.type===`attachment`?`[ATTACHMENT ${e.mediaType||`file`}] ${e.fileName||`attachment`}`:``}).filter(Boolean).join(`
|
|
3
3
|
`):typeof e==`object`?JSON.stringify(e):String(e):``}async function N(n,r){let i=String(n||``).trim();if(!i)return null;if(j.has(i))return j.get(i);let a=r||(typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0);if(!a)return null;let o=r||t(a),s=`https://huggingface.co/${encodeURI(i)}/resolve/main/tokenizer_config.json`;try{let t=await o(s);if(t.ok){let n=await t.json();if(n&&typeof n==`object`){if(!n.chat_template)try{let e=await o(`https://huggingface.co/${encodeURI(i)}/resolve/main/chat_template.jinja`);if(e.ok){let t=await e.text();t&&t.trim()&&(n.chat_template=t.trim())}}catch{}if(typeof n.model_max_length==`number`&&Number.isFinite(n.model_max_length)&&n.model_max_length>0&&n.model_max_length<=2097152){let t=e.getModelInfo(i);e.registerModelInfo(i,{contextWindow:n.model_max_length,maxOutput:t?.maxOutput??null,...t||{}})}return j.set(i,n),n}}}catch{}return null}function P(e,t){let n=String(t||``).trim(),r=[],i=/* @__PURE__ */ new Map;for(let t of e){if(t?.tool_calls&&Array.isArray(t.tool_calls))for(let e of t.tool_calls){let t=e?.id||e?.tool_call_id,n=e?.function?.name||e?.name;t&&n&&i.set(t,n)}if(Array.isArray(t?.content))for(let e of t.content)e?.type===`tool_use`&&e.id&&e.name&&i.set(e.id,e.name)}for(let t of e){if(!t)continue;let e=String(t.role||`user`).toLowerCase(),a=M(t.content);if(e===`system`)n=n?`${n}\n\n${a}`:a;else if(e===`tool`){let e=t.name||(t.tool_call_id?i.get(t.tool_call_id):void 0)||`unknown`;r.push({role:`tool`,content:a,...t.tool_call_id?{tool_call_id:t.tool_call_id}:{},name:e})}else if(e===`assistant`||e===`model`){let e=t.tool_calls,n=a;if(Array.isArray(t.content)){let r=t.content.filter(e=>e?.type===`tool_use`);r.length>0&&(e||=r.map(e=>({id:e.id||`call_${Math.random().toString(36).slice(2,9)}`,type:`function`,function:{name:e.name,arguments:typeof e.input==`object`&&e.input!==null?e.input:{}}})),n=M(t.content.filter(e=>e?.type!==`tool_use`)))}Array.isArray(e)&&(e=e.map(e=>{if(!e||typeof e!=`object`)return e;let t=e.function;if(t&&typeof t==`object`&&typeof t.arguments==`string`)try{let n=JSON.parse(t.arguments);if(n&&typeof n==`object`&&!Array.isArray(n))return{...e,function:{...t,arguments:n}}}catch{}return e})),r.push({role:`assistant`,content:n,...e?{tool_calls:e}:{}})}else if(Array.isArray(t.content)&&t.content.some(e=>e?.type===`tool_result`))for(let e of t.content)if(e?.type===`tool_result`){let t=typeof e.content==`string`?e.content:JSON.stringify(e.content||``),n=e.name||(e.tool_use_id?i.get(e.tool_use_id):void 0)||`unknown`;r.push({role:`tool`,content:t,...e.tool_use_id?{tool_call_id:e.tool_use_id}:{},name:n})}else{let t=M([e]);t&&r.push({role:`user`,content:t})}else r.push({role:`user`,content:a})}let a=[];for(let e of r)if(a.length>0&&a[a.length-1].role===e.role&&e.role!==`tool`){let t=a[a.length-1];t.content=t.content?`${t.content}\n\n${e.content}`:e.content,e.tool_calls&&(t.tool_calls=[...t.tool_calls||[],...e.tool_calls])}else a.push({...e});a.length>0&&a[0].role===`assistant`&&a.unshift({role:`user`,content:`Hello`}),a.length===0&&!n&&a.push({role:`user`,content:`Hello`});let o=[];return n&&o.push({role:`system`,content:n}),o.push(...a),o}export{P as n,N as t};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{b as e,h as t,o as n,r}from"./config-CDttEBqp.js";import{n as i}from"./db-BUuJo1Gf.js";import{t as a}from"./get-config-CL2_eFkq.js";import{c as o,d as s,f as c,t as l,x as u}from"./tools-2TxJ2IVJ.js";import{B as d,C as f,R as p,S as m,V as h,_ as g,a as _,b as v,c as y,d as b,f as x,g as S,i as C,l as w,m as T,n as E,o as ee,p as D,r as O,s as k,t as A,u as j,v as M,x as N,y as P,z as F}from"./agent.worker.js";function I(e,t,n){let r=(t||``).toLowerCase();return r?n&&(r.includes(`api key not configured`)||r.includes(`go to settings to add your api key`)||r.includes(`missing api key`)||r.includes(`no api key`))?`api-key-missing`:n&&(r.includes(`invalid api key`)||r.includes(`incorrect api key`)||r.includes(`authentication failed`)||r.includes(`401`)||r.includes(`403`)||r.includes(`unauthorized`)||r.includes(`forbidden`))?`api-key-invalid`:r.includes(`429`)||r.includes(`rate limit`)||r.includes(`too many requests`)?`rate-limited`:r.includes(`failed to fetch`)||r.includes(`networkerror`)||r.includes(`network error`)||r.includes(`econnrefused`)||r.includes(`connection refused`)||r.includes(`enotfound`)||r.includes(`timed out`)||r.includes(`timeout`)||r.includes(`503`)||r.includes(`502`)?`provider-unreachable`:null:null}async function L(e=[],t,n={}){let r=n.maxInlineTextBytes??102400,i=n.maxImageBytes??3145728,a=[];for(let n of e){let e=n.mimeType||`application/octet-stream`,o=w(e,n.fileName),s=o===`text`?`file`:o===`document`?`document`:o,c=null;try{c=await t(n)}catch{c=null}let l=c?.length??(typeof n.size==`number`?n.size:0);if(o===`text`&&c&&l<=r)try{let e=new TextDecoder(`utf-8`).decode(c),t=e.includes("```")?`~~~~`:"```";a.push({type:`text`,text:`Attachment: ${n.fileName}\n${t}\n${e}\n${t}`});continue}catch{}let u={type:`attachment`,mediaType:s,fileName:n.fileName,mimeType:e,size:n.size,path:n.path};c&&(s===`image`&&l<=i||s===`audio`&&l<=5242880||s===`document`&&l<=20971520)&&(u.data=D(c)),a.push(u)}return a}async function R(e,t){let n=await v(e,t),r=await i();return await Promise.all(n.map(async t=>{if(t.isFromMe)return{role:`assistant`,content:t.content};let n=`${t.sender}: ${t.content}`,i=t.attachments||[];if(i.length===0)return{role:`user`,content:n};let a=await L(i,async t=>!r||!t.path?null:f(r,e,t.path));return a.length===0?{role:`user`,content:n}:{role:`user`,content:[{type:`text`,text:n},...a]}}))}function z(){try{return}catch(e){console.warn(`Audio chime failed:`,e)}}function B(e,t){return e.channelRegistry?.getChannelType(t)??`browser`}async function V(e,t,n,r){let i=B(e,n),a={channel:i,content:r,groupId:n,id:s(),isFromMe:!0,isTrigger:!1,sender:e.assistantName,timestamp:Date.now()};if(await M(t,a),i!==`browser`)try{await e.router?.send(n,r)}catch(t){let r=t instanceof Error?t:Error(String(t));console.error(`Failed to deliver intermediate channel response:`,r),e.events.emit(`error`,{groupId:n,error:`Failed to deliver response to ${i}: ${r.message}`})}e.events.emit(`message`,a)}async function H(e,t,n,r){let i={channel:B(e,n),content:r,groupId:n,id:s(),isFromMe:!0,isTrigger:!1,sender:e.assistantName,timestamp:Date.now()};await M(t,i);let a=null;try{await e.router?.send(n,r)}catch(e){a=e instanceof Error?e:Error(String(e)),console.error(`Failed to deliver channel response:`,a)}e.pendingScheduledTasks.has(n)&&(e.pendingScheduledTasks.delete(n),z()),e.events.emit(`message`,i),e.events.emit(`typing`,{groupId:n,typing:!1}),e.setState(`idle`,n),e.router?.setTyping(n,!1),n.startsWith(`peer:`)&&!a&&e.peerjs.completeActiveTask(n)&&e.peerCompletedContexts.add(n),a&&e.events.emit(`error`,{groupId:n,error:`Failed to deliver response to ${B(e,n)}: ${a.message}`})}function U(e){let t=e.toLowerCase();return t.includes(`assets/cache/llamafile`)||t.includes(`missing or invalid 'model' parameter for cli mode`)||t.includes(`failed to list llamafile binaries`)}function W(e){let t=e.toLowerCase();return t.includes(`transformers.js runtime is not installed`)||t.includes(`transformers.js runtime is unavailable`)||t.includes(`no supported transformers.js model loader`)||t.includes(`cannot find package`)&&t.includes(`@huggingface/transformers`)}function G(e,t,n,r){return{accessTokenExpiresAt:e.expiresIn?Date.now()+e.expiresIn*1e3:t.accessTokenExpiresAt,oauthReauthRequired:!1,oauthReauthRequiredAt:void 0,oauthRefreshFailureCount:0,refreshToken:r,scopes:e.scope?e.scope.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean):t.scopes,token:n,tokenType:e.tokenType||t.tokenType}}async function te(e,t,n,i,a,o,s){if(!t.refreshToken)return{success:!1,error:`No refresh token available.`};let l=await d(t.refreshToken);if(!l)return{success:!1,error:`Failed to decrypt refresh token.`};let u=t.oauthClientSecret?await d(t.oauthClientSecret):void 0;try{let d=await fetch(`/oauth/refresh`,{body:JSON.stringify({clientId:t.oauthClientId,clientSecret:u||void 0,providerId:t.oauthProviderId,refreshToken:l,scope:t.scopes,tokenUrl:t.oauthCustomTokenUrl}),headers:{"content-type":`application/json`},method:`POST`});if(!d.ok)return{success:!1,error:`Token refresh request failed.`};let f=await d.json();if(!f.accessToken)return{success:!1,error:`No access token in refresh response.`};let m=await h(f.accessToken);if(!m)return{success:!1,error:`Failed to encrypt access token.`};let g=t.refreshToken;if(f.refreshToken){let e=await h(f.refreshToken);e&&(g=e)}let _=G({accessToken:f.accessToken,expiresIn:f.expiresIn,refreshToken:f.refreshToken,scope:f.scope,tokenType:f.tokenType},t,m,g);if(n===`service`&&o.accountId){let t=i.findIndex(e=>e.id===o.accountId);t!==-1&&(Object.assign(i[t],_),await c(e,r.SERVICE_ACCOUNTS,i))}else if(n===`git`&&o.gitAccountId){let t=a.findIndex(e=>e.id===o.gitAccountId);t!==-1&&(Object.assign(a[t],_),await c(e,r.GIT_ACCOUNTS,a))}return p(s),{success:!0}}catch(e){return{success:!1,error:`Silent refresh failed: ${e instanceof Error?e.message:String(e)}`}}}async function K(e,n,i={}){let o=await F(e,n);if(!o?.credentialRef)return{success:!1,error:`Connection not found.`};let s=o.credentialRef;if(s.authType!==`oauth`)return{success:!1,error:`This connection does not use OAuth authentication.`};let l=await a(e,r.SERVICE_ACCOUNTS),u=Array.isArray(l)?l:[],f=await a(e,r.GIT_ACCOUNTS),m=Array.isArray(f)?f:[],g,_=null;if(s.accountId?(g=u.find(e=>e.id===s.accountId),_=`service`):s.gitAccountId&&(g=m.find(e=>e.id===s.gitAccountId),_=`git`),!g||!_)return{error:`Linked account not found. Edit the connection to re-configure authentication.`,success:!1};let v=g.oauthClientId,y=g.oauthProviderId;if(!y||!v)return{error:`Account is missing OAuth provider or client ID. Edit the account in Settings → Accounts to fix.`,success:!1};if(g.refreshToken){let t=await te(e,g,_,u,m,s,n);if(t.success)return t}if(i.silentOnly)return{error:`Silent token refresh failed. Use Settings → Remote MCP → Reconnect OAuth for full re-authorization.`,success:!1};let b=g.oauthClientSecret?await d(g.oauthClientSecret):void 0,x=g.scopes,S=t[y],C=y===`custom_mcp`,w=C&&g.oauthCustomRedirectUri?g.oauthCustomRedirectUri:S?.redirectUri?S.redirectUri:`${globalThis.location?.origin||``}/oauth/callback`;try{let t=await fetch(`/oauth/authorize`,{body:JSON.stringify({providerId:y,clientId:v,clientSecret:b||void 0,redirectUri:w,scope:x,...C&&g.oauthCustomAuthorizeUrl?{authorizeUrl:g.oauthCustomAuthorizeUrl}:{},...C&&g.oauthCustomTokenUrl?{tokenUrl:g.oauthCustomTokenUrl}:{},...C&&typeof g.oauthCustomUsePkce==`boolean`?{usePkce:g.oauthCustomUsePkce}:{}}),headers:{"content-type":`application/json`},method:`POST`}),i=await t.json();if(!t.ok||!i.state||!i.authorizeUrl)throw Error(i.error||`OAuth authorize failed`);let a=window.open(i.authorizeUrl,`shadowclaw-oauth`,`popup=yes,width=540,height=720`);if(!a||a.closed||a.closed===void 0)throw Error(`OAuth popup was blocked by the browser. Please enable popups for this site and try again.`);let o=i.state,l=`pending`;for(let e=0;e<60;e++){let e=await fetch(`/oauth/session/${encodeURIComponent(o)}`),t=await e.json();if(!e.ok)throw Error(t.error||`OAuth session not found`);if(l=t.status||`pending`,l===`authorized`)break;if(l===`error`)throw Error(t.error||`OAuth authorization failed`);await new Promise(e=>setTimeout(e,1e3))}if(l!==`authorized`)throw Error(`OAuth authorization timed out`);let d=await fetch(`/oauth/token`,{body:JSON.stringify({state:o}),headers:{"content-type":`application/json`},method:`POST`}),f=await d.json();if(!d.ok||!f.accessToken)throw Error(f.error||`OAuth token exchange failed`);let S=await h(f.accessToken);if(!S)throw Error(`Failed to encrypt access token`);let T=g.refreshToken;if(f.refreshToken){let e=await h(f.refreshToken);e&&(T=e)}let E=G({accessToken:f.accessToken,expiresIn:f.expiresIn,refreshToken:f.refreshToken,scope:f.scope,tokenType:f.tokenType},g,S,T);if(_===`service`&&s.accountId){let t=u.findIndex(e=>e.id===s.accountId);t!==-1&&(Object.assign(u[t],E),await c(e,r.SERVICE_ACCOUNTS,u))}else if(_===`git`&&s.gitAccountId){let t=m.findIndex(e=>e.id===s.gitAccountId);t!==-1&&(Object.assign(m[t],E),await c(e,r.GIT_ACCOUNTS,m))}return p(n),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function ne(e){let t=await i(),n=await a(t,r.PUSH_PROXY_URL);if(!n&&typeof localStorage<`u`)try{n=localStorage.getItem(r.PUSH_PROXY_URL)||void 0}catch{}if(!n)return e;let o=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${o}`}async function q(e){return await e.getApiKey()||``}function J(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,t){let n=e.transformersProgressPollers.get(t);typeof n==`number`&&(clearInterval(n),e.transformersProgressPollers.delete(t))}function re(e,t){let n=e.roomManager.createRoom(t);return e.events.emit(`rooms-changed`,e.roomManager.list()),n}function ie(e,t,n){return e.roomManager.invite(t,n)}function ae(e,t){e.roomManager.leaveRoom(t),e.events.emit(`rooms-changed`,e.roomManager.list())}function X(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}async function Z(e,t,n){if(!e.taskServerEnabled)return!0;if(!t.schedule)return Q(e,t.id,n);try{let r=`${e.taskServerUrl.replace(/\/$/,``)}/tasks`,i=await fetch(r,X(r,{body:JSON.stringify({...t,pushNotifications:!!t.pushNotifications,...n?{subscriberId:n}:{}}),headers:{"Content-Type":`application/json`},method:`POST`}));return i.ok?!0:(console.error(`Server rejected task sync:`,i.status),!1)}catch(e){return console.error(`Failed to sync task to server:`,e),!1}finally{oe(e)}}async function Q(e,t,n){if(!e.taskServerEnabled)return!0;try{let r=e.taskServerUrl.replace(/\/$/,``),i=n?`?subscriberId=${encodeURIComponent(n)}`:``,a=`${r}/tasks/${encodeURIComponent(t)}${i}`,o=await fetch(a,X(a,{method:`DELETE`}));return o.ok?!0:(console.error(`Server rejected task deletion:`,o.status),!1)}catch(e){return console.error(`Failed to delete task from server:`,e),!1}}async function oe(e){if(!e.pushSubscriptionWarned&&typeof navigator<`u`&&navigator.serviceWorker)try{await(await navigator.serviceWorker.ready).pushManager.getSubscription()||(e.pushSubscriptionWarned=!0,S(`Push notifications are not enabled. Scheduled tasks will only run while the app is open. Enable push in Settings for background execution.`,{type:`warning`}))}catch{}}const $=/* @__PURE__ */ new Map;$.set(`response`,async(e,t,n)=>{let{groupId:r,text:i}=n;Y(e,r),e.clearProviderRequest(r),e.inFlightTriggerByGroup.delete(r),e.inFlightEffectiveProviderByGroup.delete(r),await H(e,t,r,i)}),$.set(`streaming-start`,(e,t,n)=>{let{groupId:r}=n;e.setState(`responding`,r),e.events.emit(`streaming-start`,{groupId:r})}),$.set(`streaming-chunk`,(e,t,n)=>{let{groupId:r,text:i}=n;e.events.emit(`streaming-chunk`,{groupId:r,text:i})}),$.set(`intermediate-response`,async(e,t,n)=>{let{groupId:r,text:i}=n;await V(e,t,r,i)}),$.set(`streaming-end`,(e,t,n)=>{let{groupId:r}=n;e.events.emit(`streaming-end`,{groupId:r}),e.setState(`thinking`,r)}),$.set(`streaming-done`,(e,t,n)=>{let{groupId:r}=n;e.events.emit(`streaming-done`,{groupId:r})}),$.set(`streaming-error`,(e,t,n)=>{let{groupId:r,error:i}=n;e.events.emit(`streaming-error`,{groupId:r,error:i})}),$.set(`run-task`,(e,t,n)=>{let{task:r}=n;T.runTask(r,!0)}),$.set(`task-created`,async(e,t,n)=>{let{task:r}=n;if(r.groupId&&e.schedulerTriggeredGroups.has(r.groupId))S(`⚠️ Task creation blocked — scheduled tasks cannot create new tasks (recursion prevention).`,{type:`warning`,duration:8e3});else try{if(!await Z(e,r,await N(t))){S(`Failed to sync task to server — task was not saved.`,{type:`error`});return}await g(t,r),e.events.emit(`task-change`,{type:`created`,task:r})}catch(e){console.error(`Failed to save task from agent:`,e),S(`Failed to save task.`,{type:`error`})}}),$.set(`task-list-request`,async(e,t,n)=>{let{groupId:r}=n,i=(await o(t)).filter(e=>e.groupId===r);e.agentWorker?.postMessage({type:`task-list-response`,payload:{groupId:r,tasks:i}})}),$.set(`update-task`,async(e,t,n)=>{let{task:r}=n;if(r.groupId&&e.schedulerTriggeredGroups.has(r.groupId))S(`⚠️ Task update blocked — scheduled tasks cannot modify tasks (recursion prevention).`,{type:`warning`,duration:8e3});else try{if(!await Z(e,r,await N(t))){S(`Failed to sync task update to server — task was not updated.`,{type:`error`});return}await g(t,r),e.events.emit(`task-change`,{type:`updated`,task:r})}catch(e){console.error(`Failed to update task from agent:`,e),S(`Failed to update task.`,{type:`error`})}}),$.set(`delete-task`,async(e,t,n)=>{let{id:r,groupId:i}=n;if(i&&e.schedulerTriggeredGroups.has(i))S(`⚠️ Task deletion blocked — scheduled tasks cannot delete tasks (recursion prevention).`,{type:`warning`,duration:8e3});else try{if(!await Q(e,r,await N(t))){S(`Failed to delete task from server — task kept in view.`,{type:`error`});return}await m(t,r),e.events.emit(`task-change`,{type:`deleted`,id:r})}catch(e){console.error(`Failed to delete task from agent:`,e)}}),$.set(`room-action`,(e,t,n)=>{let r=n?.action;try{r===`create`?re(e,String(n.name||``).trim()):r===`invite`?ie(e,String(n.roomId),String(n.peerId)):r===`leave`&&ae(e,String(n.roomId))}catch(e){console.error(`Failed to handle room action from agent:`,e)}}),$.set(`error`,async(e,t,n)=>{let{groupId:r,error:i}=n;Y(e,r),e.clearProviderRequest(r),e.inFlightTriggerByGroup.delete(r);let a=i,o=!1,s=e.inFlightEffectiveProviderByGroup.get(r);e.inFlightEffectiveProviderByGroup.delete(r);let c=s?.providerId??e.provider,l=s?.providerConfig??e.providerConfig;if((i.includes(`413`)||i.includes(`tokens_limit_reached`)||i.includes(`context_length_exceeded`)||i.includes(`too many tokens`))&&(a+=`
|
|
2
|
+
|
|
3
|
+
⚠️ This model has a small context window. Try clicking **'Compact'** in the header to summarize the conversation and reduce token usage.`),c===`llamafile`&&U(i)&&(o=!0,e.events.emit(`provider-help`,{providerId:`llamafile`,reason:i})),c===`transformers_js_local`&&W(i)&&(o=!0,e.events.emit(`provider-help`,{providerId:`transformers_js_local`,reason:i})),!o){let t=I(c,i,l?.requiresApiKey!==!1);t&&e.events.emit(`provider-help`,{providerId:c,reason:i,helpType:t})}await H(e,t,r,`⚠️ Error: ${a}`)}),$.set(`typing`,(e,t,n)=>{let{groupId:r}=n;e.router?.setTyping(r,!0),e.events.emit(`typing`,{groupId:r,typing:!0})}),$.set(`tool-activity`,(e,t,n)=>{e.events.emit(`tool-activity`,n),(n.tool===`write_file`&&n.status===`done`||n.tool===`bash`&&n.status===`done`)&&e.events.emit(`file-change`,{groupId:n.groupId})}),$.set(`model-download-progress`,(e,t,n)=>{e.events.emit(`model-download-progress`,n)}),$.set(`thinking-log`,(e,t,n)=>{e.events.emit(`thinking-log`,n)}),$.set(`compact-done`,async(e,t,n)=>{e.clearProviderRequest(n.groupId),await e.handleCompactDone(t,n.groupId,n.summary)}),$.set(`token-usage`,(e,t,n)=>{e.events.emit(`token-usage`,n)}),$.set(`clear-chat`,async(e,t,n)=>{let{groupId:r}=n;try{await e.newSession(t,r)}catch(e){console.error(`Failed to clear chat from agent:`,e)}}),$.set(`show-toast`,(e,t,n)=>{let{message:r,type:i,duration:a}=n;S(r,{type:i||`info`,duration:a})}),$.set(`mcp-reauth-required`,async(e,t,n)=>{let{connectionId:r}=n,i=await F(t,r),a=i?.label||r;if(i?.autoReconnectOAuth){S(`🔑 MCP connection "${a}" returned 401 — auto-reconnecting OAuth…`,{type:`info`,duration:5e3});let n=await K(t,r,{silentOnly:!0});n.success?S(`🔑 OAuth reconnected for "${a}"`,{type:`success`,duration:5e3}):S(`🔑 OAuth auto-reconnect failed for "${a}": ${n.error}`,{action:{label:`Reconnect Now`,onClick:async()=>{let e=await K(t,r);e.success?S(`🔑 OAuth reconnected for "${a}"`,{type:`success`,duration:5e3}):S(`🔑 OAuth reconnect failed for "${a}": ${e.error}`,{type:`error`,duration:1e4})}},duration:15e3,type:`error`}),e.agentWorker?.postMessage({payload:{connectionId:r,success:n.success},type:`mcp-reauth-result`})}else S(`🔑 MCP connection "${a}" returned 401 — OAuth re-authentication required. Go to Settings → Remote MCP to reconnect.`,{type:`warning`,duration:1e4}),e.agentWorker?.postMessage({payload:{connectionId:r,success:!1},type:`mcp-reauth-result`});e.events.emit(`mcp-reauth-required`,{connectionId:r,label:a})}),$.set(`manage-tools`,async(e,t,n)=>{let{action:r,toolNames:i,profileId:a}=n;if(r===`activate_profile`&&a)await l.activateProfile(t,a);else if((r===`enable`||r===`disable`)&&i){let e=r===`enable`;for(let n of i)await l.setToolEnabled(t,n,e)}let o=n.groupId||`br:main`;e.agentWorker?.postMessage({type:`update-tools`,payload:{enabledTools:l.enabledTools,groupId:o,systemPromptOverride:l.systemPromptOverride}})}),$.set(`send-notification`,(e,t,n)=>{let{title:r,body:i,groupId:a}=n;a&&e.schedulerTriggeredGroups.has(a)?S(`⚠️ Notification blocked — scheduled tasks triggered via push cannot send push notifications (recursion prevention).`,{type:`warning`,duration:8e3}):ne(`/push/broadcast`).then(e=>{fetch(e,{body:JSON.stringify({title:r,body:i}),headers:{"Content-Type":`application/json`},method:`POST`}).catch(e=>console.error(`Failed to broadcast push notification:`,e))})}),$.set(`vm-status`,(e,t,n)=>{e.vmStatus={...n},e.events.emit(`vm-status`,e.vmStatus)}),$.set(`vm-terminal-opened`,(e,t,n)=>{e.events.emit(`vm-terminal-opened`,n)}),$.set(`vm-terminal-output`,(e,t,n)=>{e.events.emit(`vm-terminal-output`,n)}),$.set(`vm-terminal-closed`,(e,t,n)=>{e.events.emit(`vm-terminal-closed`,n)}),$.set(`vm-workspace-synced`,(e,t,n)=>{e.events.emit(`file-change`,{groupId:n?.groupId})}),$.set(`vm-terminal-error`,(e,t,n)=>{e.events.emit(`vm-terminal-error`,n)}),$.set(`open-file`,(e,t,n)=>{e.events.emit(`open-file`,n)}),$.set(`send-file`,(e,t,n)=>{let{groupId:r,path:i}=n;(async()=>{e.router?.setTyping(r,!0);try{await e.router?.send(r,``,[{path:i,fileName:i.split(`/`).pop()||i,mimeType:`application/octet-stream`,size:0}])}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`send-file: delivery failed:`,e),S(`Failed to send file to peer: ${t}`,{type:`error`,duration:6e3})}finally{e.router?.setTyping(r,!1)}})()}),$.set(`render-component`,(e,t,n)=>{let{groupId:r,envelope:i}=n;if(e.events.emit(`a2ui-surface`,{groupId:r,envelope:i}),r.startsWith(`peer:`)){let t=e.router?.findChannel(r);t&&`sendA2UI`in t&&t.sendA2UI(r,i).catch(e=>console.error(`render-component: peer delivery failed:`,e))}r.startsWith(`room:`)&&e.roomManager.broadcastA2UI(x(r),i)}),$.set(`request-native-ai-task`,(e,t,n)=>{let{id:r,groupId:i,taskType:a,input:o}=n;(async()=>{try{let n=t=>{e.events.emit(`model-download-progress`,{groupId:i,status:t.status,progress:t.progress,message:t.message})},s=i?e.inFlightEffectiveProviderByGroup?.get(i):void 0,c=s?.providerId||e.provider,l=s?.model||s?.providerConfig?.defaultModel||e.model,u=await q(e)||``,d=J(e,c,``),f=await k({taskType:a,input:o,groupId:i,db:t,providerId:c,model:l,apiKey:u,headers:d,maxTokens:e.maxTokens,onProgress:n});i&&e.events.emit(`model-download-progress`,{groupId:i,status:`done`,progress:1});let p=globalThis.pendingNativeAiResolvers;p&&p[r]&&(p[r].resolve(f),delete p[r]),e.agentWorker?.postMessage({type:`native-ai-task-response`,payload:{id:r,response:f}})}catch(t){i&&e.events.emit(`model-download-progress`,{groupId:i,status:`error`,progress:null,message:t?.message||String(t)});let n=globalThis.pendingNativeAiResolvers;n&&n[r]&&(n[r].reject(t instanceof Error?t:Error(String(t))),delete n[r]),e.agentWorker?.postMessage({type:`native-ai-task-response`,payload:{id:r,error:t?.message||String(t)}})}})()}),$.set(`ask-user`,(e,t,n)=>{e.events.emit(`ask-user`,n)});async function se(e,t,n){let r=$.get(n?.type);r&&await r(e,t,n?.payload,n)}async function ce(t,i,o=n){let s=(await P(i)).find(e=>e.groupId===o),c=s?.pinnedProvider??t.provider,d=s?.pinnedModel??(s?.pinnedProvider?e(s.pinnedProvider)?.defaultModel??t.model:t.model),f=(e(c)??t.providerConfig)?.requiresApiKey!==!1,p=c===t.provider?await q(t):await t.getApiKeyForSpecificProvider(i,c);if(f&&!p){let e=`API key not configured. Cannot compact context.`;t.events.emit(`provider-help`,{providerId:c,reason:e,helpType:I(c,e,f)}),t.events.emit(`error`,{groupId:o,error:e});return}if(t.state!==`idle`){t.events.emit(`error`,{groupId:o,error:`Cannot compact while processing. Wait for the current response to finish.`});return}t.setState(`thinking`,o),t.events.emit(`typing`,{groupId:o,typing:!0});let m=``;try{m=await u(i,o,`MEMORY.md`)}catch{}let h=l.enabledTools,g=T.getPeerState(o)||void 0,v=A(t.assistantName,m,h,l.systemPromptOverride,g,void 0,{groupId:o}),x=d;c===`prompt_api`&&(d===`browser-built-in`||!d)&&!O()&&(x=await a(i,r.PROMPT_API_FALLBACK_MODEL)||`onnx-community/Qwen3-0.6B-ONNX`);let S=y(x),w=_(v),D=await R(o,200),k=C(D,{contextLimit:S,systemPromptTokens:w,maxOutputTokens:4096,skimTop:t.contextCompressionEnabled}).messages;if(await a(i,r.COMPACTION_ENGINE_PREFERENCE)===`builtin_task_api`)try{let e=k.map(e=>`${e.role.toUpperCase()}: ${typeof e.content==`string`?e.content:JSON.stringify(e.content)}`).join(`
|
|
4
|
+
|
|
5
|
+
`),n=await b(e,{type:`key-points`,format:`markdown`,length:`medium`});await t.handleCompactDone(i,o,n);return}catch(e){await H(t,i,o,`⚠️ Built-in Task API compaction failed, falling back to provider: ${e instanceof Error?e.message:String(e)}`)}if(c===`prompt_api`){if(O()||await j(),!O()){t.events.emit(`error`,{groupId:o,error:`Prompt API is not available in this browser. Switch provider or enable experimental browser flags.`}),t.events.emit(`typing`,{groupId:o,typing:!1}),t.setState(`idle`,o);return}let e=new AbortController;t.promptControllers.set(o,e);try{let n=await E(ee(v),k,e.signal,async e=>{await se(t,i,e)},o);await t.handleCompactDone(i,o,n)}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;await H(t,i,o,`⚠️ Error: Compaction failed: ${e instanceof Error?e.message:String(e)}`)}finally{t.promptControllers.delete(o)}return}let M=t.createProviderRequestId(o);t.agentWorker?.postMessage({type:`compact`,payload:{apiKey:p,assistantName:t.assistantName,contextCompression:t.contextCompressionEnabled,contextLimit:y(x),groupId:o,memory:m,messages:k,model:d,provider:c,providerHeaders:J(t,c,M,s?.providerRuntimeOverrides),rateLimitAutoAdapt:t.rateLimitAutoAdapt,rateLimitCallsPerMinute:t.rateLimitCallsPerMinute,storageHandle:await a(i,r.STORAGE_HANDLE),systemPrompt:v}})}export{ce as compactContext};
|