shadow-claw 1.59.7 → 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.
Files changed (253) hide show
  1. package/.well-known/mcp/server-card.json +4 -12
  2. package/.well-known/mcp.json +4 -12
  3. package/README.md +6 -2
  4. package/dist/cli/build/build.js +1 -1
  5. package/dist/cli/{chunk-DDvuLVfW.js → chunk-3C5izdQW.js} +1 -1
  6. package/dist/cli/chunk-B-75h9gX.js +1 -0
  7. package/dist/cli/{chunk-hVf839t7.js → chunk-B7Kn-otm.js} +1 -1
  8. package/dist/cli/{chunk-YX32FcN7.js → chunk-BBczgswQ.js} +1 -1
  9. package/dist/cli/{chunk-DcNxjqH6.js → chunk-BE-lYWcn.js} +1 -1
  10. package/dist/cli/{chunk-CQaCgswD.js → chunk-BECr0WxI.js} +11 -11
  11. package/dist/cli/chunk-BEz1PD1_.js +1 -0
  12. package/dist/cli/chunk-BLzI1Fp2.js +1 -0
  13. package/dist/cli/{chunk-B3TrWbca.js → chunk-BVSC1MNQ.js} +11 -11
  14. package/dist/cli/{chunk-D_te8ufL.js → chunk-BdWcep6o.js} +1 -1
  15. package/dist/cli/{chunk-SRBRVorc.js → chunk-BfTpnSS4.js} +1 -1
  16. package/dist/cli/{chunk-D2_eAO83.js → chunk-BgvqTf7w.js} +1 -1
  17. package/dist/cli/chunk-BwsJfUT3.js +1 -0
  18. package/dist/cli/{chunk--PFY91kE.js → chunk-C9b4b7c_.js} +1 -1
  19. package/dist/cli/{chunk-SxK79JmB.js → chunk-CAw9XYFe.js} +1 -1
  20. package/dist/cli/chunk-CFCcbFs2.js +396 -0
  21. package/dist/cli/{chunk-Cnjb8Usu.js → chunk-CTarF4FC.js} +1 -1
  22. package/dist/cli/{chunk-3vNYrs_L.js → chunk-Cbq5hpjb.js} +4 -4
  23. package/dist/cli/chunk-CjTjKy_v.js +310 -0
  24. package/dist/cli/chunk-Cjyu4cr_.js +36 -0
  25. package/dist/cli/{chunk-DUGZPka_.js → chunk-ClMKygjZ.js} +1 -1
  26. package/dist/cli/chunk-Cppnq1KF.js +1 -0
  27. package/dist/cli/{chunk-DvemF16v.js → chunk-D9QCNFMO.js} +1 -1
  28. package/dist/cli/{chunk-iB8OoMmW.js → chunk-DB21BMqt.js} +1 -1
  29. package/dist/cli/{chunk-_Vo-o_e3.js → chunk-DHoIWvCc.js} +1 -1
  30. package/dist/cli/chunk-DZEN9T5y.js +1 -0
  31. package/dist/cli/{chunk-5rLO4DWS.js → chunk-Dl14OyYO.js} +9 -9
  32. package/dist/cli/chunk-Dl_vv0dI.js +1 -0
  33. package/dist/cli/chunk-Dpmfhlyl.js +1 -0
  34. package/dist/cli/{chunk-BrR1DOBS.js → chunk-Du7Xtucq.js} +1 -1
  35. package/dist/cli/{chunk-B88Z8T_9.js → chunk-DxcDFUi_.js} +1 -1
  36. package/dist/cli/{chunk-Dt7-hzJU.js → chunk-DyyEWbV7.js} +1 -1
  37. package/dist/cli/chunk-N0x3mXU0.js +1 -0
  38. package/dist/cli/{chunk-CGoE4llV.js → chunk-V-w0Bata.js} +1 -1
  39. package/dist/cli/{chunk-CncW6_WL.js → chunk-ZxDxSSn-.js} +1 -1
  40. package/dist/cli/{chunk-CZdCRqNe.js → chunk-lPvFUkd5.js} +1 -1
  41. package/dist/cli/{chunk-66BvqAV0.js → chunk-n5s-sCdU.js} +1 -1
  42. package/dist/cli/{chunk-CAAeGOdy.js → chunk-nD9VPVMq.js} +1 -1
  43. package/dist/cli/{chunk-DMs7kREC.js → chunk-rFuy8aS_.js} +1 -1
  44. package/dist/cli/{chunk-B0qusANw.js → chunk-wjM6JXWa.js} +1 -1
  45. package/dist/cli/{chunk-DhOU6GYX.js → chunk-zcES9rut.js} +1 -1
  46. package/dist/cli/cli.js +3 -3
  47. package/dist/headless-agent.js +1 -1
  48. package/dist/lib/{channel-mmdGzPkT.js → channel-DB77spML.js} +2 -2
  49. package/dist/lib/{channel-mmdGzPkT.js.map → channel-DB77spML.js.map} +1 -1
  50. package/dist/lib/{compact-context-CY9BBlUQ.js → compact-context-Q9t9aL1e.js} +7 -7
  51. package/dist/lib/{compact-context-CY9BBlUQ.js.map → compact-context-Q9t9aL1e.js.map} +1 -1
  52. package/dist/lib/components/index.js +21 -21
  53. package/dist/lib/components/settings/shadow-claw-channel-config.js +1 -1
  54. package/dist/lib/components/settings/shadow-claw-control-plane.js +1 -1
  55. package/dist/lib/components/settings/shadow-claw-git.js +1 -1
  56. package/dist/lib/components/settings/shadow-claw-llm.js +1 -1
  57. package/dist/lib/components/settings/shadow-claw-networking.js +1 -1
  58. package/dist/lib/components/settings/shadow-claw-notifications.js +1 -1
  59. package/dist/lib/components/settings/shadow-claw-peerjs.js +1 -1
  60. package/dist/lib/components/settings/shadow-claw-storage.js +1 -1
  61. package/dist/lib/components/settings/shadow-claw-task-server.js +1 -1
  62. package/dist/lib/components/settings/shadow-claw-webvm.js +1 -1
  63. package/dist/lib/components/shadow-claw-channel-config.js +1 -1
  64. package/dist/lib/components/shadow-claw-channels.js +1 -1
  65. package/dist/lib/components/shadow-claw-chat.js +1 -1
  66. package/dist/lib/components/shadow-claw-control-plane.js +1 -1
  67. package/dist/lib/components/shadow-claw-conversations.js +1 -1
  68. package/dist/lib/components/shadow-claw-file-viewer.js +1 -1
  69. package/dist/lib/components/shadow-claw-files.js +1 -1
  70. package/dist/lib/components/shadow-claw-git.js +1 -1
  71. package/dist/lib/components/shadow-claw-llm.js +1 -1
  72. package/dist/lib/components/shadow-claw-networking.js +1 -1
  73. package/dist/lib/components/shadow-claw-notifications.js +1 -1
  74. package/dist/lib/components/shadow-claw-pages.js +1 -1
  75. package/dist/lib/components/shadow-claw-peerjs.js +1 -1
  76. package/dist/lib/components/shadow-claw-settings.js +1 -1
  77. package/dist/lib/components/shadow-claw-storage.js +1 -1
  78. package/dist/lib/components/shadow-claw-task-server.js +1 -1
  79. package/dist/lib/components/shadow-claw-tasks.js +1 -1
  80. package/dist/lib/components/shadow-claw-terminal.js +1 -1
  81. package/dist/lib/components/shadow-claw-tools.js +1 -1
  82. package/dist/lib/components/shadow-claw-webvm.js +1 -1
  83. package/dist/lib/components/shadow-claw.js +1 -1
  84. package/dist/lib/{configure-peer-js-ccNvax2N.js → configure-peer-js-CgFiwoxY.js} +2 -2
  85. package/dist/lib/{configure-peer-js-ccNvax2N.js.map → configure-peer-js-CgFiwoxY.js.map} +1 -1
  86. package/dist/lib/content/build-attachment-content-blocks.d.ts +2 -0
  87. package/dist/lib/{discover-skills-OwlQ2sXA.js → discover-skills-CXyaWHKi.js} +5 -5
  88. package/dist/lib/{discover-skills-OwlQ2sXA.js.map → discover-skills-CXyaWHKi.js.map} +1 -1
  89. package/dist/lib/{git-D2J_j9X9.js → git-CogDRlEz.js} +2 -2
  90. package/dist/lib/{git-D2J_j9X9.js.map → git-CogDRlEz.js.map} +1 -1
  91. package/dist/lib/index.js +21 -21
  92. package/dist/lib/{init-control-plane-B7blDVIE.js → init-control-plane-CEGdzgWX.js} +7 -7
  93. package/dist/lib/{init-control-plane-B7blDVIE.js.map → init-control-plane-CEGdzgWX.js.map} +1 -1
  94. package/dist/lib/{invoke-agent-SxvudiDT.js → invoke-agent-cac3gCsj.js} +6 -6
  95. package/dist/lib/{invoke-agent-SxvudiDT.js.map → invoke-agent-cac3gCsj.js.map} +1 -1
  96. package/dist/lib/{move-group-entry-DDpjxa10.js → move-group-entry-D8dptMg0.js} +2 -2
  97. package/dist/lib/{move-group-entry-DDpjxa10.js.map → move-group-entry-D8dptMg0.js.map} +1 -1
  98. package/dist/lib/{orchestrator-C7fkh7T7.js → orchestrator-BBAwy9Nm.js} +12 -12
  99. package/dist/lib/{orchestrator-C7fkh7T7.js.map → orchestrator-BBAwy9Nm.js.map} +1 -1
  100. package/dist/lib/{orchestrator-CCARkxQC.js → orchestrator-cRBe3lhq.js} +2 -2
  101. package/dist/lib/{orchestrator-CCARkxQC.js.map → orchestrator-cRBe3lhq.js.map} +1 -1
  102. package/dist/lib/{peerjs-Bfw_FWLB.js → peerjs-BLg8aGUj.js} +3 -3
  103. package/dist/lib/{peerjs-Bfw_FWLB.js.map → peerjs-BLg8aGUj.js.map} +1 -1
  104. package/dist/lib/{process-peer-query-param-BxYiZNdf.js → process-peer-query-param-BnsVnxzH.js} +5 -5
  105. package/dist/lib/{process-peer-query-param-BxYiZNdf.js.map → process-peer-query-param-BnsVnxzH.js.map} +1 -1
  106. package/dist/lib/{process-pending-shared-payloads-DPIbwRb3.js → process-pending-shared-payloads-DBZfZOOa.js} +2 -2
  107. package/dist/lib/{process-pending-shared-payloads-DPIbwRb3.js.map → process-pending-shared-payloads-DBZfZOOa.js.map} +1 -1
  108. package/dist/lib/{process-room-query-param-B2_d50nE.js → process-room-query-param-B8EYg_-r.js} +4 -4
  109. package/dist/lib/{process-room-query-param-B2_d50nE.js.map → process-room-query-param-B8EYg_-r.js.map} +1 -1
  110. package/dist/lib/{push-client-rrjTdc-U.js → push-client-CAm6UMvE.js} +3 -3
  111. package/dist/lib/{push-client-rrjTdc-U.js.map → push-client-CAm6UMvE.js.map} +1 -1
  112. package/dist/lib/{rooms-bwGoYb1q.js → rooms-Dzphx3rK.js} +2 -2
  113. package/dist/lib/{rooms-bwGoYb1q.js.map → rooms-Dzphx3rK.js.map} +1 -1
  114. package/dist/lib/{shadow-claw-CypGVlVO.js → shadow-claw-CGl8tXtG.js} +6 -6
  115. package/dist/lib/{shadow-claw-CypGVlVO.js.map → shadow-claw-CGl8tXtG.js.map} +1 -1
  116. package/dist/lib/{shadow-claw-channel-config-DJpDovkF.js → shadow-claw-channel-config-BNIWCdsL.js} +4 -4
  117. package/dist/lib/{shadow-claw-channel-config-DJpDovkF.js.map → shadow-claw-channel-config-BNIWCdsL.js.map} +1 -1
  118. package/dist/lib/{shadow-claw-channels-DJLwRovH.js → shadow-claw-channels-C2QSn4Ew.js} +2 -2
  119. package/dist/lib/{shadow-claw-channels-DJLwRovH.js.map → shadow-claw-channels-C2QSn4Ew.js.map} +1 -1
  120. package/dist/lib/{shadow-claw-chat-B92cPaft.js → shadow-claw-chat-Wx3y9y6c.js} +3 -3
  121. package/dist/lib/{shadow-claw-chat-B92cPaft.js.map → shadow-claw-chat-Wx3y9y6c.js.map} +1 -1
  122. package/dist/lib/{shadow-claw-control-plane-fvn-qyHj.js → shadow-claw-control-plane-D5E4cFGu.js} +6 -6
  123. package/dist/lib/{shadow-claw-control-plane-fvn-qyHj.js.map → shadow-claw-control-plane-D5E4cFGu.js.map} +1 -1
  124. package/dist/lib/{shadow-claw-conversations-CsVyDOny.js → shadow-claw-conversations-BtDv7GRW.js} +2 -2
  125. package/dist/lib/{shadow-claw-conversations-CsVyDOny.js.map → shadow-claw-conversations-BtDv7GRW.js.map} +1 -1
  126. package/dist/lib/{shadow-claw-file-viewer-DFfyP7s5.js → shadow-claw-file-viewer-CG40kwWV.js} +2 -2
  127. package/dist/lib/{shadow-claw-file-viewer-DFfyP7s5.js.map → shadow-claw-file-viewer-CG40kwWV.js.map} +1 -1
  128. package/dist/lib/{shadow-claw-files-cT6HL7ye.js → shadow-claw-files-BOUULrlX.js} +3 -3
  129. package/dist/lib/{shadow-claw-files-cT6HL7ye.js.map → shadow-claw-files-BOUULrlX.js.map} +1 -1
  130. package/dist/lib/{shadow-claw-git-Cv9mQgTx.js → shadow-claw-git-BeHV73_9.js} +3 -3
  131. package/dist/lib/{shadow-claw-git-Cv9mQgTx.js.map → shadow-claw-git-BeHV73_9.js.map} +1 -1
  132. package/dist/lib/{shadow-claw-llm-CKOYzPDp.js → shadow-claw-llm-KONyWKZM.js} +2 -2
  133. package/dist/lib/{shadow-claw-llm-CKOYzPDp.js.map → shadow-claw-llm-KONyWKZM.js.map} +1 -1
  134. package/dist/lib/{shadow-claw-networking-DYfiUQaH.js → shadow-claw-networking-Diy3JJkc.js} +2 -2
  135. package/dist/lib/{shadow-claw-networking-DYfiUQaH.js.map → shadow-claw-networking-Diy3JJkc.js.map} +1 -1
  136. package/dist/lib/{shadow-claw-notifications-JJlzriuX.js → shadow-claw-notifications-C-upPa-4.js} +2 -2
  137. package/dist/lib/{shadow-claw-notifications-JJlzriuX.js.map → shadow-claw-notifications-C-upPa-4.js.map} +1 -1
  138. package/dist/lib/{shadow-claw-pages-BCo3ihZI.js → shadow-claw-pages-CfAjUKgd.js} +2 -2
  139. package/dist/lib/{shadow-claw-pages-BCo3ihZI.js.map → shadow-claw-pages-CfAjUKgd.js.map} +1 -1
  140. package/dist/lib/{shadow-claw-peerjs-CFNjfrY5.js → shadow-claw-peerjs-t4YibS9s.js} +5 -5
  141. package/dist/lib/{shadow-claw-peerjs-CFNjfrY5.js.map → shadow-claw-peerjs-t4YibS9s.js.map} +1 -1
  142. package/dist/lib/{shadow-claw-settings-BMwne0bh.js → shadow-claw-settings-Cg5V0e9g.js} +2 -2
  143. package/dist/lib/{shadow-claw-settings-BMwne0bh.js.map → shadow-claw-settings-Cg5V0e9g.js.map} +1 -1
  144. package/dist/lib/{shadow-claw-storage-DUY8B9m-.js → shadow-claw-storage-C7tCnsSG.js} +2 -2
  145. package/dist/lib/{shadow-claw-storage-DUY8B9m-.js.map → shadow-claw-storage-C7tCnsSG.js.map} +1 -1
  146. package/dist/lib/{shadow-claw-task-server-yWeoA3eL.js → shadow-claw-task-server-BObsRdf8.js} +2 -2
  147. package/dist/lib/{shadow-claw-task-server-yWeoA3eL.js.map → shadow-claw-task-server-BObsRdf8.js.map} +1 -1
  148. package/dist/lib/{shadow-claw-tasks-Bg0uM15I.js → shadow-claw-tasks-B2EEqrcY.js} +3 -3
  149. package/dist/lib/{shadow-claw-tasks-Bg0uM15I.js.map → shadow-claw-tasks-B2EEqrcY.js.map} +1 -1
  150. package/dist/lib/{shadow-claw-terminal-fyJPppY_.js → shadow-claw-terminal-DSHfO2b9.js} +2 -2
  151. package/dist/lib/{shadow-claw-terminal-fyJPppY_.js.map → shadow-claw-terminal-DSHfO2b9.js.map} +1 -1
  152. package/dist/lib/{shadow-claw-tools-D0T8m3go.js → shadow-claw-tools-DwPBADua.js} +3 -3
  153. package/dist/lib/{shadow-claw-tools-D0T8m3go.js.map → shadow-claw-tools-DwPBADua.js.map} +1 -1
  154. package/dist/lib/{shadow-claw-webvm-CQvzJwKI.js → shadow-claw-webvm-CY4qGaMB.js} +2 -2
  155. package/dist/lib/{shadow-claw-webvm-CQvzJwKI.js.map → shadow-claw-webvm-CY4qGaMB.js.map} +1 -1
  156. package/dist/lib/{sync-web-mcp-registration-BFtG_4kx.js → sync-web-mcp-registration-BiOZvW-R.js} +3 -3
  157. package/dist/lib/{sync-web-mcp-registration-BFtG_4kx.js.map → sync-web-mcp-registration-BiOZvW-R.js.map} +1 -1
  158. package/dist/lib/{system-prompt-bhGRLoL2.js → system-prompt-CxJ3Nx4c.js} +4 -3
  159. package/dist/lib/system-prompt-CxJ3Nx4c.js.map +1 -0
  160. package/dist/public/.well-known/mcp/server-card.json +4 -12
  161. package/dist/public/.well-known/mcp.json +4 -12
  162. package/dist/public/AGENTS.md +3 -1
  163. package/dist/public/README.md +6 -2
  164. package/dist/public/agent.worker.js +1 -1
  165. package/dist/public/{channel-Dk7wl-Av.js → channel-DIpDQekL.js} +1 -1
  166. package/dist/public/{chat-template-BwAnTFKf.js → chat-template-CXKs8lFR.js} +1 -1
  167. package/dist/public/compact-context-BQ2ZXoAc.js +5 -0
  168. package/dist/public/{compact-context-fOTqwKF6.js → compact-context-dHitmPsV.js} +2 -2
  169. package/dist/public/{configure-peer-js-BOV0tR6G.js → configure-peer-js-DV1rqvFX.js} +1 -1
  170. package/dist/public/{create-model-cache-fetch-DSAFjOwc.js → create-model-cache-fetch-B0mSCEk6.js} +1 -1
  171. package/dist/public/{discover-skills-D1sNTy2r.js → discover-skills-BWJB8HUA.js} +1 -1
  172. package/dist/public/docs/architecture/overview.md +1 -1
  173. package/dist/public/docs/example/article/index.html +21 -21
  174. package/dist/public/docs/example/article.html +21 -21
  175. package/dist/public/docs/publishing/index.html +21 -21
  176. package/dist/public/docs/publishing.html +21 -21
  177. package/dist/public/docs/skill-creator/index.html +21 -21
  178. package/dist/public/docs/skill-creator.html +21 -21
  179. package/dist/public/docs/subsystems/attachment-capabilities.md +14 -1
  180. package/dist/public/docs/subsystems/cli.md +95 -51
  181. package/dist/public/docs/subsystems/pages.md +5 -0
  182. package/dist/public/e2e/README.md +1 -1
  183. package/dist/public/{e2e-bridge-Cz95DLlb.js → e2e-bridge-lP2qqiv3.js} +1 -1
  184. package/dist/public/{git-BmMlwIMP.js → git-DjmQ16rm.js} +1 -1
  185. package/dist/public/{iframe-bridge-scripts-Cibg0m6A.js → iframe-bridge-scripts-CO0izGjW.js} +1 -1
  186. package/dist/public/index.html +21 -21
  187. package/dist/public/index.js +1 -1
  188. package/dist/public/{init-control-plane-Cb31yLTY.js → init-control-plane-Ctz7FI8M.js} +1 -1
  189. package/dist/public/{invoke-agent-CN7mSV0Z.js → invoke-agent-C_geruwq.js} +1 -1
  190. package/dist/public/llms.txt +1 -1
  191. package/dist/public/main/index.html +21 -21
  192. package/dist/public/main/memory/index.html +21 -21
  193. package/dist/public/main/memory.html +21 -21
  194. package/dist/public/main.html +21 -21
  195. package/dist/public/{move-group-entry-CXneuNVa.js → move-group-entry-QQ9Hkk54.js} +1 -1
  196. package/dist/public/{orchestrator-Dyylc8IU.js → orchestrator-C1kaTltu.js} +2 -2
  197. package/dist/public/{orchestrator-DBO4NZqd.js → orchestrator-Li1UAsv7.js} +1 -1
  198. package/dist/public/{peerjs-l0jiBoh6.js → peerjs-DbBryE-9.js} +1 -1
  199. package/dist/public/{process-peer-query-param-s-aSP1Rq.js → process-peer-query-param-DQIgr3KL.js} +1 -1
  200. package/dist/public/{process-pending-shared-payloads-BN3GigPT.js → process-pending-shared-payloads-Ctb-TFqB.js} +1 -1
  201. package/dist/public/{process-room-query-param-B2Qe0F0M.js → process-room-query-param-F-XnIVoZ.js} +1 -1
  202. package/dist/public/{push-client-B2LC8Qp9.js → push-client-DRx9Eggz.js} +1 -1
  203. package/dist/public/{rooms-ChCEOvkw.js → rooms-BurBI7is.js} +1 -1
  204. package/dist/public/service-worker/init.js +1 -1
  205. package/dist/public/service-worker.js +1 -1
  206. package/dist/public/{shadow-claw-Br8mWDUx.js → shadow-claw-Bg9AQ5x_.js} +2 -2
  207. package/dist/public/{shadow-claw-accounts-Dm6G7KMP.js → shadow-claw-accounts-B3mjYI0M.js} +1 -1
  208. package/dist/public/{shadow-claw-card-CggS8uSa.js → shadow-claw-card-tcXRS1GF.js} +1 -1
  209. package/dist/public/{shadow-claw-channels-088vhuWO.js → shadow-claw-channels-BiSfLvWv.js} +1 -1
  210. package/dist/public/{shadow-claw-chat-BRwRlq-n.js → shadow-claw-chat-N5jMsXZZ.js} +1 -1
  211. package/dist/public/{shadow-claw-control-plane-rhKACK85.js → shadow-claw-control-plane-DFVe_Xdq.js} +2 -2
  212. package/dist/public/{shadow-claw-conversations-CF_yUfKl.js → shadow-claw-conversations-wAR06_ya.js} +1 -1
  213. package/dist/public/{shadow-claw-empty-state-CkpOSXCS.js → shadow-claw-empty-state-CnPm3NVM.js} +1 -1
  214. package/dist/public/{shadow-claw-file-viewer-DWCejuY3.js → shadow-claw-file-viewer-sZN_FCDW.js} +2 -2
  215. package/dist/public/{shadow-claw-files-L6_ioyzh.js → shadow-claw-files-CnvkCbd4.js} +2 -2
  216. package/dist/public/{shadow-claw-git-DsdkwLqQ.js → shadow-claw-git-BBHfClGk.js} +2 -2
  217. package/dist/public/{shadow-claw-integrations-CSbRTOm3.js → shadow-claw-integrations-DvdBqzRJ.js} +1 -1
  218. package/dist/public/{shadow-claw-llm-BitaeAVc.js → shadow-claw-llm-YfohG519.js} +1 -1
  219. package/dist/public/{shadow-claw-mcp-remote-gSbV5riy.js → shadow-claw-mcp-remote-BAVbf5pi.js} +1 -1
  220. package/dist/public/{shadow-claw-networking-Dn_y6Cl9.js → shadow-claw-networking-CZ4LWPW7.js} +1 -1
  221. package/dist/public/{shadow-claw-notifications-Cj4Lqx8U.js → shadow-claw-notifications-BHwyREkG.js} +1 -1
  222. package/dist/public/{shadow-claw-page-header-DR4OZFt2.js → shadow-claw-page-header-De6Qf6eY.js} +1 -1
  223. package/dist/public/{shadow-claw-page-header-action-button-BnCV_2Kb.js → shadow-claw-page-header-action-button-FSOhTc9z.js} +1 -1
  224. package/dist/public/{shadow-claw-pages-mpDOtNYj.js → shadow-claw-pages-D_oPyDca.js} +1 -1
  225. package/dist/public/{shadow-claw-pdf-viewer-DZ_84qJH.js → shadow-claw-pdf-viewer-CrU4wqRq.js} +1 -1
  226. package/dist/public/{shadow-claw-settings-CfFTYTEy.js → shadow-claw-settings-DkUhvxVr.js} +2 -2
  227. package/dist/public/{shadow-claw-storage-DLmiT4bG.js → shadow-claw-storage-D0o56Tjw.js} +1 -1
  228. package/dist/public/{shadow-claw-task-server-BoMBCsiS.js → shadow-claw-task-server-4rkroO9K.js} +1 -1
  229. package/dist/public/{shadow-claw-tasks-ChEp1j7x.js → shadow-claw-tasks-BdP7lmvu.js} +1 -1
  230. package/dist/public/{shadow-claw-terminal-BaoVbOda.js → shadow-claw-terminal-DVHX7Fsu.js} +1 -1
  231. package/dist/public/{shadow-claw-toast-e8oz7z6Z.js → shadow-claw-toast-B9Y9tSkW.js} +1 -1
  232. package/dist/public/{shadow-claw-tools-BYjUBiJz.js → shadow-claw-tools-BwwY53Lr.js} +1 -1
  233. package/dist/public/{shadow-claw-webvm-xGb13TME.js → shadow-claw-webvm-CXGdkCNM.js} +1 -1
  234. package/dist/public/{sync-web-mcp-registration-CQluj-Kz.js → sync-web-mcp-registration-DVK_IhXZ.js} +1 -1
  235. package/dist/public/{system-prompt-CTJn0tK-.js → system-prompt-BmswoQwF.js} +2 -2
  236. package/dist/public/{workbox-92eae37e.js → workbox-e4022e15.js} +1 -1
  237. package/dist/public/{zip-reader-DN7FB-Q0.js → zip-reader-JHoTbATw.js} +1 -1
  238. package/dist/server.js +5 -5
  239. package/package.json +1 -1
  240. package/dist/cli/chunk-2gZFafgY.js +0 -1
  241. package/dist/cli/chunk-BCjL0JXf.js +0 -1
  242. package/dist/cli/chunk-BNcu1oiT.js +0 -1
  243. package/dist/cli/chunk-BUNoeMKY.js +0 -36
  244. package/dist/cli/chunk-C5ypckWC.js +0 -225
  245. package/dist/cli/chunk-CFxww5Yz.js +0 -1
  246. package/dist/cli/chunk-CGIgtL6R.js +0 -1
  247. package/dist/cli/chunk-CafdvLx-.js +0 -1
  248. package/dist/cli/chunk-Dhap1VwA.js +0 -1
  249. package/dist/cli/chunk-Ds5-K-9o.js +0 -1
  250. package/dist/cli/chunk-DwvavohW.js +0 -1
  251. package/dist/cli/chunk-_a0CkUNS.js +0 -139
  252. package/dist/lib/system-prompt-bhGRLoL2.js.map +0 -1
  253. package/dist/public/compact-context-CX4H8V57.js +0 -5
@@ -1,3 +1,3 @@
1
- import{u as e}from"./custom-element-security-B2daIE5r.js";import{D as t,E as n,I as r,L as i,M as a,O as o,P as s,T as c,_ as l,et as u,g as d,j as f,l as p,o as m,r as h,s as g,t as _,v,w as y}from"./config-C16fFWtP.js";import{n as b,r as x}from"./db-BUuJo1Gf.js";import{n as S}from"./tx-promise-DNVEN3Wa.js";import{t as C}from"./get-config-Bkvl__ZS.js";import{t as ee}from"./dist-CeFyqf9k.js";import{C as w,E as te,H as ne,Q as T,i as E,k as D,r as re,t as O,x as ie}from"./orchestrator-DBO4NZqd.js";import{t as k}from"./set-config-DSiuMe0k.js";import{t as A}from"./ulid-BSJxYh6W.js";import{s as ae,t as j}from"./tools-D-52Zmfc.js";import{t as M}from"./get-or-create-subscriber-id-jVHnQfbr.js";import{r as oe}from"./get-group-dir-D--BiEyk.js";import{i as se,r as ce}from"./write-group-file-R67DjJ-q.js";import{t as N}from"./parse-boolean-config-BigJ9U46.js";import{S as P,a as le,b as F,i as ue,l as de,n as fe,r as pe,t as me}from"./provider-YPZmsuHR.js";import{n as I,r as L}from"./crypto-4ETeplbS.js";import{t as he}from"./chat-template-BwAnTFKf.js";import{a as ge,i as _e,s as ve}from"./transformers-CQ9ss9rD.js";import{a as ye}from"./push-client-B2LC8Qp9.js";import{f as be,n as xe,t as Se,u as R}from"./channel-Dk7wl-Av.js";import{a as z,i as B,n as Ce,o as we,r as Te}from"./rooms-ChCEOvkw.js";import{i as Ee}from"./mime-ClqNyXPc.js";import{i as De,r as V,t as Oe}from"./peerjs-l0jiBoh6.js";import{setWebMcpMode as ke,unregisterWebMcpTools as Ae}from"./webmcp-DIUZjVF5.js";import{a as je,i as Me,p as Ne,r as Pe,t as Fe}from"./discover-skills-D1sNTy2r.js";import{r as H}from"./sync-web-mcp-registration-CQluj-Kz.js";import{i as U,n as Ie,r as Le,t as Re}from"./system-prompt-CTJn0tK-.js";import{ensureControlPlaneConnected as ze}from"./init-control-plane-Cb31yLTY.js";async function Be(e){if(e&&e.name!==`shadowclaw`){try{if(await C(e,h.DB_MIGRATED_FROM_LEGACY)===`true`)return}catch{}try{let t=await new Promise(e=>{let t=indexedDB.open(l);t.onsuccess=()=>{let n=t.result;!n.objectStoreNames||n.objectStoreNames.length===0?(n.close(),e(null)):e(n)},t.onerror=()=>e(null)});if(t){let n=Array.from(t.objectStoreNames).filter(t=>e.objectStoreNames.contains(t));for(let r of n)await new Promise(n=>{try{let i=t.transaction(r,`readonly`).objectStore(r).getAll();i.onsuccess=()=>{let t=i.result||[];if(t.length>0)try{let i=e.transaction(r,`readwrite`),a=i.objectStore(r);for(let e of t)a.put(e);i.oncomplete=()=>n(),i.onerror=()=>n(),i.onabort=()=>n()}catch{n()}else n()},i.onerror=()=>n()}catch{n()}});t.close()}}catch(e){console.warn(`Legacy IndexedDB migration warning:`,e)}finally{try{await k(e,h.DB_MIGRATED_FROM_LEGACY,`true`)}catch{}}}}async function W(e,t,n){for await(let[r,i]of e.entries())if(i.kind===`directory`)await W(i,await t.getDirectoryHandle(r,{create:!0}),[...n,r]);else if(i.kind===`file`){let e=await i.getFile(),a=await t.getFileHandle(r,{create:!0});try{await ce(a,e)}catch(t){if(!(t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`))throw t;await se([...n,r],e)}}}async function Ve(e){if(!e)return;try{if(await C(e,h.OPFS_MIGRATED_FROM_LEGACY)===`true`)return}catch{}let t=oe();if(t!==`shadowclaw`&&typeof navigator<`u`&&navigator.storage&&typeof navigator.storage.getDirectory==`function`)try{let n=await navigator.storage.getDirectory(),r;try{r=await n.getDirectoryHandle(v)}catch{try{await k(e,h.OPFS_MIGRATED_FROM_LEGACY,`true`)}catch{}return}let i=await n.getDirectoryHandle(t,{create:!0});await W(r,i,[t])}catch(e){console.warn(`Legacy OPFS migration warning:`,e)}finally{try{await k(e,h.OPFS_MIGRATED_FROM_LEGACY,`true`)}catch{}}}function He(){return new Promise(async(e,t)=>{let n,r=f(),i=indexedDB.open(r,2);i.onupgradeneeded=()=>{let e=i.result;if(!e.objectStoreNames.contains(`messages`)){let t=e.createObjectStore(`messages`,{keyPath:`id`});t.createIndex(`by-group-time`,[`groupId`,`timestamp`]),t.createIndex(`by-group`,`groupId`)}if(e.objectStoreNames.contains(`sessions`)||e.createObjectStore(`sessions`,{keyPath:`groupId`}),!e.objectStoreNames.contains(`tasks`)){let t=e.createObjectStore(`tasks`,{keyPath:`id`});t.createIndex(`by-group`,`groupId`),t.createIndex(`by-enabled`,`enabled`)}e.objectStoreNames.contains(`config`)||e.createObjectStore(`config`,{keyPath:`key`}),e.objectStoreNames.contains(`pendingShares`)||e.createObjectStore(`pendingShares`,{keyPath:`id`}).createIndex(`by-createdAt`,`createdAt`)},i.onsuccess=async()=>{n=i.result,x(n);try{await Be(n),await Ve(n)}catch(e){console.warn(`Error running legacy migration:`,e)}e(n)},i.onerror=()=>{t(/* @__PURE__ */ Error(`Failed to open IndexedDB: ${i.error?.message}`))}})}var Ue=class{activeGroupId;displayCallback;messageCallback;type;typingCallback;constructor(){this.type=`browser`,this.messageCallback=null,this.typingCallback=null,this.displayCallback=null,this.activeGroupId=m}getActiveGroup(){return this.activeGroupId}onDisplay(e){this.displayCallback=e}onMessage(e){this.messageCallback=e}onTyping(e){this.typingCallback=e}setActiveGroup(e){this.activeGroupId=e}setTyping(e,t){this.typingCallback?.(e,t)}start(){}stop(){}submit(e,t,n=[],r,i,a){let o=t||this.activeGroupId,s={id:A(),groupId:o,sender:`You`,content:e,timestamp:Date.now(),channel:`browser`,attachments:n,a2uiAction:r,freshContext:i,subagent:a};this.messageCallback?.(s)}async send(e,t,n){this.displayCallback?.(e,t,!0)}},G=class{_entries;constructor(){this._entries=[]}find(e){return this.resolve(e)?.channel??null}get(e){return this._entries.find(t=>t.prefix===e)?.channel}getBadge(e){return this.resolve(e)?.badge??``}getChannelType(e){return this.resolve(e)?.channel.type??null}onMessage(e){for(let t of this._entries)t.channel.onMessage(e)}onTyping(e){for(let t of this._entries)t.channel.onTyping&&t.channel.onTyping(e)}prefixes(){return this._entries.map(e=>e.prefix)}register(e,t,n){let r=typeof n==`string`?{badge:n}:n??{};this._entries.push({prefix:e,channel:t,badge:r.badge??e.replace(/:$/,``),autoTrigger:r.autoTrigger??!1}),this._entries.sort((e,t)=>t.prefix.length-e.prefix.length)}resolve(e){for(let t of this._entries)if(e.startsWith(t.prefix))return t;return null}shouldAutoTrigger(e){return this.resolve(e)?.autoTrigger??!1}startAll(){for(let e of this._entries)e.channel.start()}stopAll(){for(let e of this._entries)e.channel.stop()}},We=class{abortController=null;apiKey=``;apiMode=`unknown`;cursor=null;fileReader=null;messageCallback=null;reconnectDelayMs=1e3;registeredChatIds=/* @__PURE__ */ new Set;running=!1;seenMessageIds=/* @__PURE__ */ new Map;serverUrl=``;type=`imessage`;configure(e,t,n){this.serverUrl=Ge(e),this.apiKey=t.trim(),this.registeredChatIds=new Set(n.map(e=>e.trim()).filter(Boolean)),this.cursor=null,this.apiMode=`unknown`}handleIncomingMessage(e){this.pruneSeenMessageIds();let t=String(e.chatId||e.conversationId||``).trim();if(!t||this.registeredChatIds.size>0&&!this.registeredChatIds.has(t))return;let n=`${e.text||e.body||``}`.trim();if(!n)return;let r=`${e.id||e.guid||`${t}:${e.timestamp||e.createdAt||n}`}`;if(this.seenMessageIds.has(r))return;this.seenMessageIds.set(r,Date.now());let i={id:r,groupId:`im:${t}`,sender:`${e.sender||e.handle||e.from||`iMessage`}`,content:n,timestamp:K(e.timestamp||e.createdAt),channel:`imessage`};this.messageCallback?.(i)}handlePollResponse(e){e.nextCursor!==void 0&&e.nextCursor!==null?this.cursor=String(e.nextCursor):e.cursor!==void 0&&e.cursor!==null&&(this.cursor=String(e.cursor));let t=Array.isArray(e.messages)?e.messages:[];for(let e of t)this.handleIncomingMessage(e)}isConfigured(){return this.serverUrl.length>0}onMessage(e){this.messageCallback=e}pruneSeenMessageIds(){let e=Date.now();for(let[t,n]of this.seenMessageIds.entries())e-n>6e4&&this.seenMessageIds.delete(t)}setTyping(e,t){if(!t)return;let n=e.replace(/^im:/,``);this.requestJson(`/messages/typing`,{method:`POST`,body:JSON.stringify({chatId:n,typing:!0})}).catch(()=>{})}start(){this.isConfigured()&&!this.running&&(this.running=!0,this.abortController=new AbortController,this.poll())}ensureConnected(){this.isConfigured()&&this.running&&(this.reconnectDelayMs=1e3,this.abortController?.abort(),this.abortController=new AbortController,this.poll())}stop(){this.running=!1,this.abortController?.abort(),this.abortController=null}async ensureApiMode(){if(this.apiMode!==`unknown`)return this.apiMode;try{await this.requestJson(`/v1/info`,{method:`GET`}),this.apiMode=`beeper-desktop`}catch{this.apiMode=`legacy`}return this.apiMode}async poll(){for(;this.running&&this.abortController&&!this.abortController.signal.aborted;)try{let e=new URLSearchParams({timeout:`25`});this.cursor&&e.set(`cursor`,this.cursor);let t=await this.requestJson(`/messages?${e.toString()}`,{method:`GET`},d+5e3,this.abortController.signal);this.reconnectDelayMs=1e3,this.handlePollResponse(t)}catch(e){if(e instanceof Error&&e.name===`AbortError`)break;console.error(`iMessage bridge poll error:`,e),await Ke(this.reconnectDelayMs),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,3e4)}}async requestJson(e,t,n=d,r){let i=new AbortController,a=setTimeout(()=>i.abort(),n),o=()=>i.abort();r?.addEventListener(`abort`,o,{once:!0});try{let n=new Headers(t.headers);n.set(`Accept`,`application/json`),!n.has(`Content-Type`)&&t.body&&!(t.body instanceof FormData)&&n.set(`Content-Type`,`application/json`),this.apiKey&&(n.set(`Authorization`,`Bearer ${this.apiKey}`),n.set(`X-API-Key`,this.apiKey));let r=await fetch(`${this.serverUrl}${e}`,{...t,headers:n,signal:i.signal});if(!r.ok){let e=await r.text();throw Error(`iMessage bridge request failed: ${r.status} ${e}`)}return r.status===204?{messages:[]}:await r.json()}finally{clearTimeout(a),r?.removeEventListener(`abort`,o)}}async send(e,t,n){let r=e.replace(/^im:/,``),{remainingText:i,attachments:a}=qe(t);for(let t of a)if(!this.fileReader)await this.sendText(r,`[${t.alt}] (file: ${t.path})`);else try{let n=await this.fileReader(e,t.path);if(!n||n.size===0)throw Error(`Attachment file is empty or unavailable.`);await this.sendAttachment(r,n,t)}catch(e){console.warn(`iMessage attachment send failed for ${t.path}:`,e),await this.sendText(r,`[${t.alt}] (file: ${t.path})`)}let o=i.trim();o&&await this.sendText(r,o)}async sendAttachment(e,t,n){await this.ensureApiMode()===`beeper-desktop`?await this.sendAttachmentViaBeeperDesktop(e,t,n):await this.sendAttachmentViaLegacyBridge(e,t,n)}async sendAttachmentViaBeeperDesktop(e,t,n){let r=n.path.split(`/`).pop()||`attachment.bin`,i=new FormData;i.append(`file`,t,r),i.append(`fileName`,r),t.type&&i.append(`mimeType`,t.type);let a=`${(await this.requestJson(`/v1/assets/upload`,{method:`POST`,body:i})).uploadID||``}`.trim();if(!a)throw Error(`Beeper asset upload failed: missing uploadID`);await this.requestJson(`/v1/chats/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify({text:n.alt||void 0,attachment:{uploadID:a,fileName:r,mimeType:t.type||void 0}})})}async sendAttachmentViaLegacyBridge(e,t,n){let r=n.path.split(`/`).pop()||`attachment.bin`,i=new FormData;i.append(`chatId`,e),n.alt&&i.append(`text`,n.alt),i.append(`file`,t,r),await this.requestJson(`/messages/send`,{method:`POST`,body:i})}async sendText(e,t){await this.ensureApiMode()===`beeper-desktop`?await this.requestJson(`/v1/chats/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify({text:t})}):await this.requestJson(`/messages/send`,{method:`POST`,body:JSON.stringify({chatId:e,text:t})})}};function Ge(e){return e.trim().replace(/\/+$/,``)}function K(e){if(typeof e==`number`&&Number.isFinite(e))return e>0xe8d4a51000?e:e*1e3;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return K(t);let n=Date.parse(e);if(Number.isFinite(n))return n}return Date.now()}function Ke(e){return new Promise(t=>setTimeout(t,e))}function qe(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r=null,i=e;for(;(r=n.exec(e))!==null;){let e=r[1]||``,n=Je((r[2]||``).trim());n&&(t.push({alt:e,path:n}),i=i.replace(r[0],``))}return{remainingText:i,attachments:t}}function Je(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}var Ye=class{messageCallback=null;running=!1;type=`room`;typingCallback=null;_manager=null;_peerjs=null;deliverInbound(e){this.messageCallback?.(e)}onMessage(e){this.messageCallback=e}onTyping(e){this.typingCallback=e}setManager(e){this._manager=e}setPeerJs(e){this._peerjs=e}setTyping(e,t){}start(){this.running=!0}stop(){this.running=!1}async send(e,t,n){if(!this._manager)return;let r=z(e);if(n&&n.length>0&&this._peerjs){let t=this._manager.get(r);t&&await this._peerjs.sendAttachmentsToRoom(t,e,n)}this._manager.broadcast(r,t,n)}};const q=1e3;var Xe=class{abortController=null;fileReader=null;messageCallback=null;offset=0;pollRetryDelayMs=q;pollSessionId=0;registeredChatIds=/* @__PURE__ */ new Set;running=!1;token=``;type=`telegram`;useProxy=!1;buildFileUrl(e){let t=e.split(`/`).filter(Boolean).map(e=>encodeURIComponent(e)).join(`/`);return`${this.useProxy?`/telegram/file/bot`:`https://api.telegram.org/file/bot`}${this.token}/${t}`}buildMethodUrl(e){let n=e.replace(/^\/+/,``);return`${this.useProxy?t:c}${this.token}/${n}`}configure(e,t,n=!1){this.token=e.trim(),this.registeredChatIds=new Set(t.map(e=>e.trim()).filter(Boolean)),this.useProxy=!!n}isConfigured(){return this.token.length>0}nextPollRetryDelay(){let e=this.pollRetryDelayMs;return this.pollRetryDelayMs=Math.min(this.pollRetryDelayMs*2,6e4),e}onMessage(e){this.messageCallback=e}registerChatId(e){let t=e.trim();t&&this.registeredChatIds.add(t)}resetPollBackoff(){this.pollRetryDelayMs=q}setTyping(e,t){if(!t)return;let n=e.replace(/^tg:/,``);this.apiCall(`sendChatAction`,{chat_id:n,action:`typing`}).catch(()=>{})}start(){if(!this.token||this.running)return;this.running=!0,this.resetPollBackoff();let e=++this.pollSessionId,t=new AbortController;this.abortController=t,this.poll(e,t)}ensureConnected(){if(!this.token||!this.running)return;this.resetPollBackoff(),this.abortController?.abort();let e=++this.pollSessionId,t=new AbortController;this.abortController=t,this.poll(e,t)}stop(){this.running=!1,this.resetPollBackoff(),this.pollSessionId+=1,this.abortController?.abort(),this.abortController=null}async apiCall(e,t){let n=await fetch(this.buildMethodUrl(e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let t=await n.text();throw Error(`Telegram API ${e} failed: ${n.status} ${t}`)}return await n.json()}async extractAttachments(e){let t=[],n=Array.isArray(e.photo)?e.photo.at(-1):null;n?.file_id&&t.push({id:n.file_id,fileName:`photo-${e.message_id}.png`,mimeType:`image/png`,previewDisposition:`inline`}),e.document?.file_id&&t.push({id:e.document.file_id,fileName:e.document.file_name||`document-${e.message_id}`,mimeType:e.document.mime_type}),e.video?.file_id&&t.push({id:e.video.file_id,fileName:e.video.file_name||`video-${e.message_id}.mp4`,mimeType:e.video.mime_type||`video/mp4`}),e.audio?.file_id&&t.push({id:e.audio.file_id,fileName:e.audio.file_name||`audio-${e.message_id}.mp3`,mimeType:e.audio.mime_type||`audio/mpeg`}),e.voice?.file_id&&t.push({id:e.voice.file_id,fileName:`voice-${e.message_id}.ogg`,mimeType:e.voice.mime_type||`audio/ogg`}),e.animation?.file_id&&t.push({id:e.animation.file_id,fileName:e.animation.file_name||`animation-${e.message_id}.mp4`,mimeType:e.animation.mime_type||`video/mp4`}),e.sticker?.file_id&&t.push({id:e.sticker.file_id,fileName:`sticker-${e.message_id}.${$e(e.sticker)}`,mimeType:e.sticker.is_animated?`application/x-tgsticker`:e.sticker.is_video?`video/webm`:`image/webp`});let r=[];for(let e of t){let t=await this.fetchTelegramFileInfo(e.id);r.push({id:e.id,fileName:e.fileName,mimeType:e.mimeType,size:t.file_size,previewDisposition:e.previewDisposition,source:{kind:`remote-url`,url:this.buildFileUrl(t.file_path)}})}return r}async fetchTelegramFileInfo(e){let t=await this.apiCall(`getFile`,{file_id:e});if(!t.ok||!t.result?.file_path)throw Error(`Telegram getFile failed for attachment ${e}`);return t.result}async handleUpdate(e){let t=e.message;if(!t)return;let n=String(t.chat.id);if(t.text===`/chatid`){this.apiCall(`sendMessage`,{chat_id:n,text:`Chat ID: ${n}\nRegister this ID in ShadowClaw settings.`}).catch(console.error);return}if(t.text===`/ping`){this.apiCall(`sendMessage`,{chat_id:n,text:`Pong! ShadowClaw is running.`}).catch(console.error);return}if(!this.registeredChatIds.has(n))return;let r=await this.extractAttachments(t),i=`${t.text||t.caption||``}`.trim()||(t.photo?.length?`[Photo]`:null)||(t.voice?`[Voice message]`:null)||(t.video?`[Video]`:null)||(t.audio?`[Audio]`:null)||(t.animation?`[Animation]`:null)||(t.document?`[Document: ${t.document.file_name||`unnamed`}]`:null)||(t.sticker?`[Sticker: ${t.sticker.emoji||``}]`:null)||(t.location?`[Location: ${t.location.latitude}, ${t.location.longitude}]`:null)||(t.contact?`[Contact: ${t.contact.first_name}]`:null)||`[Unsupported message type]`,a=t.from?.first_name||t.from?.username||String(t.from?.id||`Unknown`),o={id:String(t.message_id),groupId:`tg:${n}`,sender:a,content:i,timestamp:t.date*1e3,channel:`telegram`,attachments:r};this.messageCallback?.(o)}async poll(e,t){for(;this.running&&this.pollSessionId===e&&!t.signal.aborted;)try{let e=await fetch(this.buildMethodUrl(`getUpdates?offset=${this.offset}&timeout=30`),{signal:t.signal});if(!e.ok){console.error(`Telegram poll error: HTTP ${e.status}`),await this.waitForRetry(this.nextPollRetryDelay());continue}let n=await e.json();if(!n.ok||!Array.isArray(n.result)){await this.waitForRetry(this.nextPollRetryDelay());continue}this.resetPollBackoff();for(let e of n.result)this.offset=e.update_id+1,await this.handleUpdate(e)}catch(e){if(e instanceof Error&&e.name===`AbortError`)break;console.error(`Telegram poll error:`,e),await this.waitForRetry(this.nextPollRetryDelay())}}async send(e,t,r){let i=e.replace(/^tg:/,``),{remainingText:a,attachments:o}=et(t);for(let t of o){if(this.fileReader)try{let n=await this.fileReader(e,t.path);if(n&&n.size>0){let e=t.path.toLowerCase();e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.gif`)||e.endsWith(`.webp`)?await this.sendPhoto(i,n,t.alt,t.path):await this.sendDocument(i,n,t.alt,t.path);continue}}catch(e){console.warn(`TelegramChannel: failed to read file ${t.path}:`,e)}await this.apiCall(`sendMessage`,{chat_id:i,text:`[${t.alt}] (file: ${t.path})`})}let s=a.trim();if(s){let e=Ze(s,n);for(let t of e)await this.apiCall(`sendMessage`,{chat_id:i,text:t})}}async sendDocument(e,t,n,r){let i=r.split(`/`).pop()||`document.file`,a=new FormData;a.append(`chat_id`,e),a.append(`document`,t,i),n&&a.append(`caption`,n);let o=await fetch(this.buildMethodUrl(`sendDocument`),{method:`POST`,body:a});if(!o.ok){let e=await o.text();throw Error(`Telegram sendDocument failed: ${o.status} ${e}`)}}async sendPhoto(e,t,n,r){let i=r.split(`/`).pop()||`image.png`,a=new FormData;a.append(`chat_id`,e),a.append(`photo`,t,i),n&&a.append(`caption`,n);let o=await fetch(this.buildMethodUrl(`sendPhoto`),{method:`POST`,body:a});if(!o.ok){let e=await o.text();throw Error(`Telegram sendPhoto failed: ${o.status} ${e}`)}}async waitForRetry(e){await Qe(e)}};function Ze(e,t){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let e=t,i=r.lastIndexOf(`
1
+ import{u as e}from"./custom-element-security-B2daIE5r.js";import{D as t,E as n,I as r,L as i,M as a,O as o,P as s,T as c,_ as l,et as u,g as d,j as f,l as p,o as m,r as h,s as g,t as _,v,w as y}from"./config-C16fFWtP.js";import{n as b,r as x}from"./db-BUuJo1Gf.js";import{n as S}from"./tx-promise-DNVEN3Wa.js";import{t as C}from"./get-config-Bkvl__ZS.js";import{t as ee}from"./dist-CeFyqf9k.js";import{C as w,E as te,H as ne,Q as T,i as E,k as D,r as re,t as O,x as ie}from"./orchestrator-Li1UAsv7.js";import{t as k}from"./set-config-DSiuMe0k.js";import{t as A}from"./ulid-BSJxYh6W.js";import{s as ae,t as j}from"./tools-D-52Zmfc.js";import{t as M}from"./get-or-create-subscriber-id-jVHnQfbr.js";import{r as oe}from"./get-group-dir-D--BiEyk.js";import{i as se,r as ce}from"./write-group-file-R67DjJ-q.js";import{t as N}from"./parse-boolean-config-BigJ9U46.js";import{S as P,a as le,b as F,i as ue,l as de,n as fe,r as pe,t as me}from"./provider-YPZmsuHR.js";import{n as I,r as L}from"./crypto-4ETeplbS.js";import{t as he}from"./chat-template-CXKs8lFR.js";import{a as ge,i as _e,s as ve}from"./transformers-CQ9ss9rD.js";import{a as ye}from"./push-client-DRx9Eggz.js";import{f as be,n as xe,t as Se,u as R}from"./channel-DIpDQekL.js";import{a as z,i as B,n as Ce,o as we,r as Te}from"./rooms-BurBI7is.js";import{i as Ee}from"./mime-ClqNyXPc.js";import{i as De,r as V,t as Oe}from"./peerjs-DbBryE-9.js";import{setWebMcpMode as ke,unregisterWebMcpTools as Ae}from"./webmcp-DIUZjVF5.js";import{a as je,i as Me,p as Ne,r as Pe,t as Fe}from"./discover-skills-BWJB8HUA.js";import{r as H}from"./sync-web-mcp-registration-DVK_IhXZ.js";import{i as U,n as Ie,r as Le,t as Re}from"./system-prompt-BmswoQwF.js";import{ensureControlPlaneConnected as ze}from"./init-control-plane-Ctz7FI8M.js";async function Be(e){if(e&&e.name!==`shadowclaw`){try{if(await C(e,h.DB_MIGRATED_FROM_LEGACY)===`true`)return}catch{}try{let t=await new Promise(e=>{let t=indexedDB.open(l);t.onsuccess=()=>{let n=t.result;!n.objectStoreNames||n.objectStoreNames.length===0?(n.close(),e(null)):e(n)},t.onerror=()=>e(null)});if(t){let n=Array.from(t.objectStoreNames).filter(t=>e.objectStoreNames.contains(t));for(let r of n)await new Promise(n=>{try{let i=t.transaction(r,`readonly`).objectStore(r).getAll();i.onsuccess=()=>{let t=i.result||[];if(t.length>0)try{let i=e.transaction(r,`readwrite`),a=i.objectStore(r);for(let e of t)a.put(e);i.oncomplete=()=>n(),i.onerror=()=>n(),i.onabort=()=>n()}catch{n()}else n()},i.onerror=()=>n()}catch{n()}});t.close()}}catch(e){console.warn(`Legacy IndexedDB migration warning:`,e)}finally{try{await k(e,h.DB_MIGRATED_FROM_LEGACY,`true`)}catch{}}}}async function W(e,t,n){for await(let[r,i]of e.entries())if(i.kind===`directory`)await W(i,await t.getDirectoryHandle(r,{create:!0}),[...n,r]);else if(i.kind===`file`){let e=await i.getFile(),a=await t.getFileHandle(r,{create:!0});try{await ce(a,e)}catch(t){if(!(t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`))throw t;await se([...n,r],e)}}}async function Ve(e){if(!e)return;try{if(await C(e,h.OPFS_MIGRATED_FROM_LEGACY)===`true`)return}catch{}let t=oe();if(t!==`shadowclaw`&&typeof navigator<`u`&&navigator.storage&&typeof navigator.storage.getDirectory==`function`)try{let n=await navigator.storage.getDirectory(),r;try{r=await n.getDirectoryHandle(v)}catch{try{await k(e,h.OPFS_MIGRATED_FROM_LEGACY,`true`)}catch{}return}let i=await n.getDirectoryHandle(t,{create:!0});await W(r,i,[t])}catch(e){console.warn(`Legacy OPFS migration warning:`,e)}finally{try{await k(e,h.OPFS_MIGRATED_FROM_LEGACY,`true`)}catch{}}}function He(){return new Promise(async(e,t)=>{let n,r=f(),i=indexedDB.open(r,2);i.onupgradeneeded=()=>{let e=i.result;if(!e.objectStoreNames.contains(`messages`)){let t=e.createObjectStore(`messages`,{keyPath:`id`});t.createIndex(`by-group-time`,[`groupId`,`timestamp`]),t.createIndex(`by-group`,`groupId`)}if(e.objectStoreNames.contains(`sessions`)||e.createObjectStore(`sessions`,{keyPath:`groupId`}),!e.objectStoreNames.contains(`tasks`)){let t=e.createObjectStore(`tasks`,{keyPath:`id`});t.createIndex(`by-group`,`groupId`),t.createIndex(`by-enabled`,`enabled`)}e.objectStoreNames.contains(`config`)||e.createObjectStore(`config`,{keyPath:`key`}),e.objectStoreNames.contains(`pendingShares`)||e.createObjectStore(`pendingShares`,{keyPath:`id`}).createIndex(`by-createdAt`,`createdAt`)},i.onsuccess=async()=>{n=i.result,x(n);try{await Be(n),await Ve(n)}catch(e){console.warn(`Error running legacy migration:`,e)}e(n)},i.onerror=()=>{t(/* @__PURE__ */ Error(`Failed to open IndexedDB: ${i.error?.message}`))}})}var Ue=class{activeGroupId;displayCallback;messageCallback;type;typingCallback;constructor(){this.type=`browser`,this.messageCallback=null,this.typingCallback=null,this.displayCallback=null,this.activeGroupId=m}getActiveGroup(){return this.activeGroupId}onDisplay(e){this.displayCallback=e}onMessage(e){this.messageCallback=e}onTyping(e){this.typingCallback=e}setActiveGroup(e){this.activeGroupId=e}setTyping(e,t){this.typingCallback?.(e,t)}start(){}stop(){}submit(e,t,n=[],r,i,a){let o=t||this.activeGroupId,s={id:A(),groupId:o,sender:`You`,content:e,timestamp:Date.now(),channel:`browser`,attachments:n,a2uiAction:r,freshContext:i,subagent:a};this.messageCallback?.(s)}async send(e,t,n){this.displayCallback?.(e,t,!0)}},G=class{_entries;constructor(){this._entries=[]}find(e){return this.resolve(e)?.channel??null}get(e){return this._entries.find(t=>t.prefix===e)?.channel}getBadge(e){return this.resolve(e)?.badge??``}getChannelType(e){return this.resolve(e)?.channel.type??null}onMessage(e){for(let t of this._entries)t.channel.onMessage(e)}onTyping(e){for(let t of this._entries)t.channel.onTyping&&t.channel.onTyping(e)}prefixes(){return this._entries.map(e=>e.prefix)}register(e,t,n){let r=typeof n==`string`?{badge:n}:n??{};this._entries.push({prefix:e,channel:t,badge:r.badge??e.replace(/:$/,``),autoTrigger:r.autoTrigger??!1}),this._entries.sort((e,t)=>t.prefix.length-e.prefix.length)}resolve(e){for(let t of this._entries)if(e.startsWith(t.prefix))return t;return null}shouldAutoTrigger(e){return this.resolve(e)?.autoTrigger??!1}startAll(){for(let e of this._entries)e.channel.start()}stopAll(){for(let e of this._entries)e.channel.stop()}},We=class{abortController=null;apiKey=``;apiMode=`unknown`;cursor=null;fileReader=null;messageCallback=null;reconnectDelayMs=1e3;registeredChatIds=/* @__PURE__ */ new Set;running=!1;seenMessageIds=/* @__PURE__ */ new Map;serverUrl=``;type=`imessage`;configure(e,t,n){this.serverUrl=Ge(e),this.apiKey=t.trim(),this.registeredChatIds=new Set(n.map(e=>e.trim()).filter(Boolean)),this.cursor=null,this.apiMode=`unknown`}handleIncomingMessage(e){this.pruneSeenMessageIds();let t=String(e.chatId||e.conversationId||``).trim();if(!t||this.registeredChatIds.size>0&&!this.registeredChatIds.has(t))return;let n=`${e.text||e.body||``}`.trim();if(!n)return;let r=`${e.id||e.guid||`${t}:${e.timestamp||e.createdAt||n}`}`;if(this.seenMessageIds.has(r))return;this.seenMessageIds.set(r,Date.now());let i={id:r,groupId:`im:${t}`,sender:`${e.sender||e.handle||e.from||`iMessage`}`,content:n,timestamp:K(e.timestamp||e.createdAt),channel:`imessage`};this.messageCallback?.(i)}handlePollResponse(e){e.nextCursor!==void 0&&e.nextCursor!==null?this.cursor=String(e.nextCursor):e.cursor!==void 0&&e.cursor!==null&&(this.cursor=String(e.cursor));let t=Array.isArray(e.messages)?e.messages:[];for(let e of t)this.handleIncomingMessage(e)}isConfigured(){return this.serverUrl.length>0}onMessage(e){this.messageCallback=e}pruneSeenMessageIds(){let e=Date.now();for(let[t,n]of this.seenMessageIds.entries())e-n>6e4&&this.seenMessageIds.delete(t)}setTyping(e,t){if(!t)return;let n=e.replace(/^im:/,``);this.requestJson(`/messages/typing`,{method:`POST`,body:JSON.stringify({chatId:n,typing:!0})}).catch(()=>{})}start(){this.isConfigured()&&!this.running&&(this.running=!0,this.abortController=new AbortController,this.poll())}ensureConnected(){this.isConfigured()&&this.running&&(this.reconnectDelayMs=1e3,this.abortController?.abort(),this.abortController=new AbortController,this.poll())}stop(){this.running=!1,this.abortController?.abort(),this.abortController=null}async ensureApiMode(){if(this.apiMode!==`unknown`)return this.apiMode;try{await this.requestJson(`/v1/info`,{method:`GET`}),this.apiMode=`beeper-desktop`}catch{this.apiMode=`legacy`}return this.apiMode}async poll(){for(;this.running&&this.abortController&&!this.abortController.signal.aborted;)try{let e=new URLSearchParams({timeout:`25`});this.cursor&&e.set(`cursor`,this.cursor);let t=await this.requestJson(`/messages?${e.toString()}`,{method:`GET`},d+5e3,this.abortController.signal);this.reconnectDelayMs=1e3,this.handlePollResponse(t)}catch(e){if(e instanceof Error&&e.name===`AbortError`)break;console.error(`iMessage bridge poll error:`,e),await Ke(this.reconnectDelayMs),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,3e4)}}async requestJson(e,t,n=d,r){let i=new AbortController,a=setTimeout(()=>i.abort(),n),o=()=>i.abort();r?.addEventListener(`abort`,o,{once:!0});try{let n=new Headers(t.headers);n.set(`Accept`,`application/json`),!n.has(`Content-Type`)&&t.body&&!(t.body instanceof FormData)&&n.set(`Content-Type`,`application/json`),this.apiKey&&(n.set(`Authorization`,`Bearer ${this.apiKey}`),n.set(`X-API-Key`,this.apiKey));let r=await fetch(`${this.serverUrl}${e}`,{...t,headers:n,signal:i.signal});if(!r.ok){let e=await r.text();throw Error(`iMessage bridge request failed: ${r.status} ${e}`)}return r.status===204?{messages:[]}:await r.json()}finally{clearTimeout(a),r?.removeEventListener(`abort`,o)}}async send(e,t,n){let r=e.replace(/^im:/,``),{remainingText:i,attachments:a}=qe(t);for(let t of a)if(!this.fileReader)await this.sendText(r,`[${t.alt}] (file: ${t.path})`);else try{let n=await this.fileReader(e,t.path);if(!n||n.size===0)throw Error(`Attachment file is empty or unavailable.`);await this.sendAttachment(r,n,t)}catch(e){console.warn(`iMessage attachment send failed for ${t.path}:`,e),await this.sendText(r,`[${t.alt}] (file: ${t.path})`)}let o=i.trim();o&&await this.sendText(r,o)}async sendAttachment(e,t,n){await this.ensureApiMode()===`beeper-desktop`?await this.sendAttachmentViaBeeperDesktop(e,t,n):await this.sendAttachmentViaLegacyBridge(e,t,n)}async sendAttachmentViaBeeperDesktop(e,t,n){let r=n.path.split(`/`).pop()||`attachment.bin`,i=new FormData;i.append(`file`,t,r),i.append(`fileName`,r),t.type&&i.append(`mimeType`,t.type);let a=`${(await this.requestJson(`/v1/assets/upload`,{method:`POST`,body:i})).uploadID||``}`.trim();if(!a)throw Error(`Beeper asset upload failed: missing uploadID`);await this.requestJson(`/v1/chats/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify({text:n.alt||void 0,attachment:{uploadID:a,fileName:r,mimeType:t.type||void 0}})})}async sendAttachmentViaLegacyBridge(e,t,n){let r=n.path.split(`/`).pop()||`attachment.bin`,i=new FormData;i.append(`chatId`,e),n.alt&&i.append(`text`,n.alt),i.append(`file`,t,r),await this.requestJson(`/messages/send`,{method:`POST`,body:i})}async sendText(e,t){await this.ensureApiMode()===`beeper-desktop`?await this.requestJson(`/v1/chats/${encodeURIComponent(e)}/messages`,{method:`POST`,body:JSON.stringify({text:t})}):await this.requestJson(`/messages/send`,{method:`POST`,body:JSON.stringify({chatId:e,text:t})})}};function Ge(e){return e.trim().replace(/\/+$/,``)}function K(e){if(typeof e==`number`&&Number.isFinite(e))return e>0xe8d4a51000?e:e*1e3;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return K(t);let n=Date.parse(e);if(Number.isFinite(n))return n}return Date.now()}function Ke(e){return new Promise(t=>setTimeout(t,e))}function qe(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r=null,i=e;for(;(r=n.exec(e))!==null;){let e=r[1]||``,n=Je((r[2]||``).trim());n&&(t.push({alt:e,path:n}),i=i.replace(r[0],``))}return{remainingText:i,attachments:t}}function Je(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}var Ye=class{messageCallback=null;running=!1;type=`room`;typingCallback=null;_manager=null;_peerjs=null;deliverInbound(e){this.messageCallback?.(e)}onMessage(e){this.messageCallback=e}onTyping(e){this.typingCallback=e}setManager(e){this._manager=e}setPeerJs(e){this._peerjs=e}setTyping(e,t){}start(){this.running=!0}stop(){this.running=!1}async send(e,t,n){if(!this._manager)return;let r=z(e);if(n&&n.length>0&&this._peerjs){let t=this._manager.get(r);t&&await this._peerjs.sendAttachmentsToRoom(t,e,n)}this._manager.broadcast(r,t,n)}};const q=1e3;var Xe=class{abortController=null;fileReader=null;messageCallback=null;offset=0;pollRetryDelayMs=q;pollSessionId=0;registeredChatIds=/* @__PURE__ */ new Set;running=!1;token=``;type=`telegram`;useProxy=!1;buildFileUrl(e){let t=e.split(`/`).filter(Boolean).map(e=>encodeURIComponent(e)).join(`/`);return`${this.useProxy?`/telegram/file/bot`:`https://api.telegram.org/file/bot`}${this.token}/${t}`}buildMethodUrl(e){let n=e.replace(/^\/+/,``);return`${this.useProxy?t:c}${this.token}/${n}`}configure(e,t,n=!1){this.token=e.trim(),this.registeredChatIds=new Set(t.map(e=>e.trim()).filter(Boolean)),this.useProxy=!!n}isConfigured(){return this.token.length>0}nextPollRetryDelay(){let e=this.pollRetryDelayMs;return this.pollRetryDelayMs=Math.min(this.pollRetryDelayMs*2,6e4),e}onMessage(e){this.messageCallback=e}registerChatId(e){let t=e.trim();t&&this.registeredChatIds.add(t)}resetPollBackoff(){this.pollRetryDelayMs=q}setTyping(e,t){if(!t)return;let n=e.replace(/^tg:/,``);this.apiCall(`sendChatAction`,{chat_id:n,action:`typing`}).catch(()=>{})}start(){if(!this.token||this.running)return;this.running=!0,this.resetPollBackoff();let e=++this.pollSessionId,t=new AbortController;this.abortController=t,this.poll(e,t)}ensureConnected(){if(!this.token||!this.running)return;this.resetPollBackoff(),this.abortController?.abort();let e=++this.pollSessionId,t=new AbortController;this.abortController=t,this.poll(e,t)}stop(){this.running=!1,this.resetPollBackoff(),this.pollSessionId+=1,this.abortController?.abort(),this.abortController=null}async apiCall(e,t){let n=await fetch(this.buildMethodUrl(e),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let t=await n.text();throw Error(`Telegram API ${e} failed: ${n.status} ${t}`)}return await n.json()}async extractAttachments(e){let t=[],n=Array.isArray(e.photo)?e.photo.at(-1):null;n?.file_id&&t.push({id:n.file_id,fileName:`photo-${e.message_id}.png`,mimeType:`image/png`,previewDisposition:`inline`}),e.document?.file_id&&t.push({id:e.document.file_id,fileName:e.document.file_name||`document-${e.message_id}`,mimeType:e.document.mime_type}),e.video?.file_id&&t.push({id:e.video.file_id,fileName:e.video.file_name||`video-${e.message_id}.mp4`,mimeType:e.video.mime_type||`video/mp4`}),e.audio?.file_id&&t.push({id:e.audio.file_id,fileName:e.audio.file_name||`audio-${e.message_id}.mp3`,mimeType:e.audio.mime_type||`audio/mpeg`}),e.voice?.file_id&&t.push({id:e.voice.file_id,fileName:`voice-${e.message_id}.ogg`,mimeType:e.voice.mime_type||`audio/ogg`}),e.animation?.file_id&&t.push({id:e.animation.file_id,fileName:e.animation.file_name||`animation-${e.message_id}.mp4`,mimeType:e.animation.mime_type||`video/mp4`}),e.sticker?.file_id&&t.push({id:e.sticker.file_id,fileName:`sticker-${e.message_id}.${$e(e.sticker)}`,mimeType:e.sticker.is_animated?`application/x-tgsticker`:e.sticker.is_video?`video/webm`:`image/webp`});let r=[];for(let e of t){let t=await this.fetchTelegramFileInfo(e.id);r.push({id:e.id,fileName:e.fileName,mimeType:e.mimeType,size:t.file_size,previewDisposition:e.previewDisposition,source:{kind:`remote-url`,url:this.buildFileUrl(t.file_path)}})}return r}async fetchTelegramFileInfo(e){let t=await this.apiCall(`getFile`,{file_id:e});if(!t.ok||!t.result?.file_path)throw Error(`Telegram getFile failed for attachment ${e}`);return t.result}async handleUpdate(e){let t=e.message;if(!t)return;let n=String(t.chat.id);if(t.text===`/chatid`){this.apiCall(`sendMessage`,{chat_id:n,text:`Chat ID: ${n}\nRegister this ID in ShadowClaw settings.`}).catch(console.error);return}if(t.text===`/ping`){this.apiCall(`sendMessage`,{chat_id:n,text:`Pong! ShadowClaw is running.`}).catch(console.error);return}if(!this.registeredChatIds.has(n))return;let r=await this.extractAttachments(t),i=`${t.text||t.caption||``}`.trim()||(t.photo?.length?`[Photo]`:null)||(t.voice?`[Voice message]`:null)||(t.video?`[Video]`:null)||(t.audio?`[Audio]`:null)||(t.animation?`[Animation]`:null)||(t.document?`[Document: ${t.document.file_name||`unnamed`}]`:null)||(t.sticker?`[Sticker: ${t.sticker.emoji||``}]`:null)||(t.location?`[Location: ${t.location.latitude}, ${t.location.longitude}]`:null)||(t.contact?`[Contact: ${t.contact.first_name}]`:null)||`[Unsupported message type]`,a=t.from?.first_name||t.from?.username||String(t.from?.id||`Unknown`),o={id:String(t.message_id),groupId:`tg:${n}`,sender:a,content:i,timestamp:t.date*1e3,channel:`telegram`,attachments:r};this.messageCallback?.(o)}async poll(e,t){for(;this.running&&this.pollSessionId===e&&!t.signal.aborted;)try{let e=await fetch(this.buildMethodUrl(`getUpdates?offset=${this.offset}&timeout=30`),{signal:t.signal});if(!e.ok){console.error(`Telegram poll error: HTTP ${e.status}`),await this.waitForRetry(this.nextPollRetryDelay());continue}let n=await e.json();if(!n.ok||!Array.isArray(n.result)){await this.waitForRetry(this.nextPollRetryDelay());continue}this.resetPollBackoff();for(let e of n.result)this.offset=e.update_id+1,await this.handleUpdate(e)}catch(e){if(e instanceof Error&&e.name===`AbortError`)break;console.error(`Telegram poll error:`,e),await this.waitForRetry(this.nextPollRetryDelay())}}async send(e,t,r){let i=e.replace(/^tg:/,``),{remainingText:a,attachments:o}=et(t);for(let t of o){if(this.fileReader)try{let n=await this.fileReader(e,t.path);if(n&&n.size>0){let e=t.path.toLowerCase();e.endsWith(`.png`)||e.endsWith(`.jpg`)||e.endsWith(`.jpeg`)||e.endsWith(`.gif`)||e.endsWith(`.webp`)?await this.sendPhoto(i,n,t.alt,t.path):await this.sendDocument(i,n,t.alt,t.path);continue}}catch(e){console.warn(`TelegramChannel: failed to read file ${t.path}:`,e)}await this.apiCall(`sendMessage`,{chat_id:i,text:`[${t.alt}] (file: ${t.path})`})}let s=a.trim();if(s){let e=Ze(s,n);for(let t of e)await this.apiCall(`sendMessage`,{chat_id:i,text:t})}}async sendDocument(e,t,n,r){let i=r.split(`/`).pop()||`document.file`,a=new FormData;a.append(`chat_id`,e),a.append(`document`,t,i),n&&a.append(`caption`,n);let o=await fetch(this.buildMethodUrl(`sendDocument`),{method:`POST`,body:a});if(!o.ok){let e=await o.text();throw Error(`Telegram sendDocument failed: ${o.status} ${e}`)}}async sendPhoto(e,t,n,r){let i=r.split(`/`).pop()||`image.png`,a=new FormData;a.append(`chat_id`,e),a.append(`photo`,t,i),n&&a.append(`caption`,n);let o=await fetch(this.buildMethodUrl(`sendPhoto`),{method:`POST`,body:a});if(!o.ok){let e=await o.text();throw Error(`Telegram sendPhoto failed: ${o.status} ${e}`)}}async waitForRetry(e){await Qe(e)}};function Ze(e,t){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let e=t,i=r.lastIndexOf(`
2
2
  `,t);i>t*.5&&(e=i),n.push(r.slice(0,e)),r=r.slice(e)}return n}function Qe(e){return new Promise(t=>setTimeout(t,e))}function $e(e){return e?.is_animated?`tgs`:e?.is_video?`webm`:`webp`}function et(e){let t=[],n=/!?\[([^\]]*)\]\(([^)]+)\)/g,r,i=e;for(;(r=n.exec(e))!==null;){let e=r[1],n=tt((r[2]||``).trim());n&&(t.push({alt:e,path:n}),i=i.replace(r[0],``))}return{remainingText:i,attachments:t}}function tt(e){if(!e)return null;let t=e.trim();if(/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.replace(/\\/g,`/`).replace(/^\/+/,``).replace(/^\.\//,``);if(!n)return null;let r=n.split(`/`).filter(Boolean);return r.some(e=>e===`..`)?null:r.join(`/`)}function J(e,t){let n=JSON.stringify(e.dataModel??{},null,2),r=t?`${t}`:`The user`;return`[A2UI ACTION]\nsurfaceId: "${e.surfaceId}"\nactionId: "${e.actionId}"\n`+(t?`firedBy: "${t}"\n`:``)+`dataModel:\n${n}\n\nInstructions: ${r} triggered the "${e.actionId}" action on surface "${e.surfaceId}". The dataModel above contains the current form values. Use the appropriate tool(s) to fulfill the action based on the actionId and dataModel values. After you have a result, call render_component with action "updateDataModel" on surfaceId "${e.surfaceId}" to update the surface (e.g. set path "/result" to the output value). Do NOT respond with plain text only — always update the surface via render_component.`}var nt=class{static formatMessagesXml(e){let t=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`);return`<messages>\n${e.map(e=>`<message sender="${t(e.sender)}" time="${new Date(e.timestamp).toISOString()}">${t(e.content)}</message>`).join(`
3
- `)}\n</messages>`}static formatOutbound(e){return e.replace(/<internal>[\s\S]*?<\/internal>/g,``).trim()}registry;constructor(e){this.registry=e}findChannel(e){return this.registry.find(e)}setTyping(e,t){this.findChannel(e)?.setTyping(e,t)}async send(e,t,n){let r=this.findChannel(e);r?await r.send(e,t,n):console.warn(`No channel for groupId: ${e}`)}};function rt(e,t,n){if(!e.enabledChannelTypes.includes(n.channel))return null;let r=n.content.trim(),i=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=r;if(e.requireMention){let e=RegExp(`^@${i}\\b\\s*(?:-|:)?\\s*`,`i`);if(!e.test(a))return null;a=a.replace(e,``).trim()}let o=a.match(/^\/([a-zA-Z0-9_]+)(?:\s+([\s\S]+))?$/);if(!o)return null;let s=o[1];if(!e.allowedTools.includes(s))return null;let c=(o[2]||``).trim();if(!c)return{toolName:s,input:{}};let l=c.startsWith(`'`)&&c.endsWith(`'`)||c.startsWith(`"`)&&c.endsWith(`"`)?c.slice(1,-1).trim():c;try{let e=JSON.parse(l);return e&&typeof e==`object`?{toolName:s,input:e}:null}catch{return null}}function it(e,t){let n=e.trim().match(/^\/([a-z0-9](?:[a-z0-9]|-(?!-))*[a-z0-9]|[a-z0-9])(?:\s+([\s\S]+))?$/u);if(!n)return null;let r=t.find(e=>e.name===n[1]&&e.userInvocable!==!1);return r?{skill:r,arguments:(n[2]||``).trim()}:null}async function Y(e,t,n){if(n.a2uiEnvelopes&&n.a2uiEnvelopes.length>0)for(let t of n.a2uiEnvelopes)e.events.emit(`a2ui-surface`,{groupId:n.groupId,envelope:t});n.a2uiAction&&e.events.emit(`a2ui-action`,{groupId:n.groupId,action:n.a2uiAction});let r=!!n.content,i=(n.attachments?.length??0)>0;if(!r&&!i&&(n.a2uiEnvelopes?.length??0)>0)return;let a=rt(e.directToolCommandPolicy,e.assistantName,n),o=a?null:it(n.content,(await Fe(t,n.groupId)).skills),s=n.channel===`browser`,c=e.channelRegistry.shouldAutoTrigger(n.groupId),l=!1;(n.channel===`browser`||n.groupId.startsWith(`room:`))&&(l=e.triggerPattern.test(n.content.trim())),o&&(l=!0),s&&n.groupId.startsWith(`peer:`)&&e.peerCompletedContexts.delete(n.groupId);let u=!!a;if(!l&&e.peerjsMyPeerId){if(n.content.includes(`@${e.peerjsMyPeerId}`))l=!0;else if(e.peerjsMyAlias&&n.content.includes(`@${e.peerjsMyAlias}`))l=!0;else for(let[t,r]of Object.entries(e.peerjsPeerAliases))if(r===e.peerjsMyPeerId&&n.content.includes(`@${t}`)){l=!0;break}}n.content.trim().startsWith(`[SCHEDULED TASK]`)&&(l=!0),n.content.trim().startsWith(`[A2UI ACTION]`)&&(l=!0);let d=!1;d=u||l?!0:s?!(n.groupId.startsWith(`peer:`)||n.groupId.startsWith(`room:`)):c,d&&!s&&!o&&n.groupId.startsWith(`peer:`)&&e.peerCompletedContexts.has(n.groupId)&&(d=!1);let f=await De(t,n.groupId,n.attachments||[]),p={...n,attachments:f,isFromMe:!1,isTrigger:d};if(d&&!u&&!o?.skill.execution&&e.messageQueue.push(o?{...n,content:`[SKILL COMMAND] Activate the "${o.skill.name}" skill and follow its instructions.\n${o.arguments}`}:n),await w(t,p),e.events.emit(`message`,p),o?.skill.execution){if(await e.ensureWorkerReady?.(),!e.agentWorker)throw Error(`Worker is not initialized.`);let t=o.skill.execution.tools.map(e=>{let t=e.input&&typeof e.input==`object`?{...e.input}:{};return o.arguments&&Object.keys(t).length===0&&(t.rawInput=o.arguments),{...e,input:t}});e.agentWorker.postMessage({type:`execute-skill-tools`,payload:{groupId:n.groupId,skillName:o.skill.name,tools:t}})}else if(n.channel===`peerjs`&&xe(n.groupId),s&&(n.groupId.startsWith(`peer:`)||n.groupId.startsWith(`room:`))&&e.router?.send(n.groupId,n.content,f).catch(e=>{console.error(`Failed to route browser message to peer:`,e)}),a){if(await e.ensureWorkerReady?.(),!e.agentWorker)throw Error(`Worker is not initialized.`);e.agentWorker.postMessage({type:`execute-direct-tool`,payload:{groupId:n.groupId,name:a.toolName,input:a.input}})}else X(e,t)}async function X(e,t){if(e.processing||e.messageQueue.length===0)return;let n=e.messageQueue[0]?.groupId,i=e.providerConfig,a=e.provider;if(n)try{let e=(await te(t)).find(e=>e.groupId===n);if(e?.pinnedProvider){let t=r(e.pinnedProvider);t&&(i=t,a=e.pinnedProvider)}}catch{}let o=i?.requiresApiKey!==!1,s=!0;if(o&&(s=a===e.provider?!!await le(e):!!await e.getApiKeyForSpecificProvider(t,a)),o&&!s){let t=`API key not configured. Go to Settings to add your API key.`;e.events.emit(`provider-help`,{providerId:a,reason:t,helpType:_e(a,t,o)});let n=e.messageQueue.shift();e.events.emit(`error`,{groupId:n.groupId,error:t});return}e.processing=!0;let c=e.messageQueue.shift();try{let{invokeAgent:n}=await import(`./invoke-agent-CN7mSV0Z.js`);await n(e,t,c.groupId,c.content,c.freshContext,c.subagent)}catch(e){console.error(`Failed to invoke agent:`,e)}finally{e.processing=!1,e.messageQueue.length>0&&X(e,t)}}var at=class{listeners;constructor(){this.listeners=/* @__PURE__ */ new Map}emit(e,t){this.listeners.get(e)?.forEach(e=>e(t))}off(e,t){this.listeners.get(e)?.delete(t)}on(e,t){this.listeners.has(e)||this.listeners.set(e,/* @__PURE__ */ new Set),this.listeners.get(e)?.add(t)}};function Z(e,t){return{jsonrpc:`2.0`,method:e,params:t}}var ot=class{static isRoomMethod(e){return e===V.JOIN||e===V.ROSTER||e===V.LEAVE||e===V.MESSAGE||e===V.INVITE||e===V.RELAY||e===V.A2UI||e===V.A2UI_ACTION}roomsSignal=new ee.State([]);_opts;_rooms=/* @__PURE__ */ new Map;_seen=/* @__PURE__ */ new Map;_surfaceOwners=/* @__PURE__ */ new Map;constructor(e){this._opts=e}broadcast(e,t,n){let r=this._rooms.get(e);if(!r)return null;let i=this._opts.getLocalMember(),a=A(),o={roomId:e,messageId:a,senderPeerId:i.peerId,senderAlias:i.alias,text:t,attachments:n?.map(e=>({fileName:e.fileName,mimeType:e.mimeType,path:e.path,size:e.size}))};return this._markSeen(e,a),this._deliverToMembers(r,Z(V.MESSAGE,o)),a}broadcastA2UI(e,t){let n=this._rooms.get(e);if(!n)return null;let r=this._myPeerId;this._surfaceOwners.set(t.surfaceId,r);let i=A(),a={roomId:e,broadcastId:i,ownerPeerId:r,senderPeerId:r,envelope:t};return this._markSeen(e,i),this._deliverToMembers(n,Z(V.A2UI,a)),i}broadcastA2UIAction(e,t){let n=this._rooms.get(e);if(!n)return null;let r=this._opts.getLocalMember(),i=this._surfaceOwners.get(t.surfaceId)??``,a=A(),o={roomId:e,broadcastId:a,ownerPeerId:i,senderPeerId:r.peerId,senderAlias:r.alias,action:t};return this._markSeen(e,a),this._deliverToMembers(n,Z(V.A2UI_ACTION,o)),a}createRoom(e){let t=this._opts.getLocalMember(),n={roomId:A(),name:e,hostPeerId:t.peerId,members:[t],createdAt:Date.now()};return this._save(n),n}get(e){return this._rooms.get(e)??null}getSurfaceOwner(e){return this._surfaceOwners.get(e)}handleNotification(e,t,n){switch(t){case V.JOIN:this._onJoin(e,n);break;case V.ROSTER:this._onRoster(n);break;case V.LEAVE:this._onLeave(e,n);break;case V.MESSAGE:this._onMessage(n);break;case V.INVITE:this._opts.onInvite?.(n);break;case V.RELAY:this._onRelay(n);break;case V.A2UI:this._onA2UI(n);break;case V.A2UI_ACTION:this._onA2UIAction(n)}}invite(e,t){let n=this._rooms.get(e);if(!n)return!1;let r=this._opts.getLocalMember(),i={roomId:e,roomName:n.name,hostPeerId:n.hostPeerId,fromPeerId:r.peerId,fromAlias:r.alias},a=this._opts.transport;return a.connectToPeer(t),a.sendToPeer(t,Z(V.INVITE,i))}isHost(e){let t=this._rooms.get(e);return!!t&&t.hostPeerId===this._myPeerId}joinRoom(e,t,n){let r=this._opts.getLocalMember(),i=this._rooms.get(e)??{roomId:e,name:n,hostPeerId:t,members:[{peerId:t,alias:t,kind:`agent`},r],createdAt:Date.now()};this._save(i);let a=this._opts.transport;a.connectToPeer(t);let o={roomId:e,member:r};return a.sendToPeer(t,Z(V.JOIN,o)),i}leaveRoom(e){let t=this._rooms.get(e);if(!t)return;let n=this._myPeerId;if(t.hostPeerId===n){let r={roomId:e,peerId:n,disbanded:!0};this._deliverToMembers(t,Z(V.LEAVE,r))}else{let r={roomId:e,peerId:n};this._opts.transport.sendToPeer(t.hostPeerId,Z(V.LEAVE,r))}this._rooms.delete(e),this._seen.delete(e),this._opts.removeRoom?.(e),this._publish()}list(){return Array.from(this._rooms.values())}loadRooms(e){this._rooms.clear();for(let t of e)this._rooms.set(t.roomId,t);this._publish()}_broadcastRoster(e){let t={roomId:e.roomId,name:e.name,hostPeerId:e.hostPeerId,members:e.members};this._deliverToMembers(e,Z(V.ROSTER,t))}_deliverToMembers(e,t){let n=this._myPeerId;for(let r of e.members)r.peerId!==n&&this._deliverToPeer(e,r.peerId,t)}_deliverToPeer(e,t,n){let r=this._opts.transport;if(r.isConnected(t)){r.sendToPeer(t,n);return}let i=this._myPeerId;if(e.hostPeerId!==i&&e.hostPeerId!==t&&r.isConnected(e.hostPeerId)){let i={roomId:e.roomId,targetPeerId:t,inner:n};r.sendToPeer(e.hostPeerId,Z(V.RELAY,i)),r.connectToPeer(t)}else r.connectToPeer(t),r.sendToPeer(t,n)}_hasSeen(e,t){return this._seen.get(e)?.has(t)??!1}_markSeen(e,t){let n=this._seen.get(e);if(n||(n=/* @__PURE__ */ new Set,this._seen.set(e,n)),n.add(t),n.size>500){let e=n.values().next().value;e!==void 0&&n.delete(e)}}get _myPeerId(){return this._opts.transport.myPeerId}_onA2UI(e){if(!e||typeof e.roomId!=`string`||typeof e.broadcastId!=`string`||!e.envelope||!this._rooms.get(e.roomId)||this._hasSeen(e.roomId,e.broadcastId))return;this._markSeen(e.roomId,e.broadcastId);let t=e.envelope.surfaceId;this._surfaceOwners.get(t)!==this._myPeerId&&this._surfaceOwners.set(t,e.ownerPeerId);let n={id:e.broadcastId,groupId:B(e.roomId),sender:e.senderPeerId,content:``,timestamp:Date.now(),channel:`room`,a2uiEnvelopes:[e.envelope]};this._opts.onMessage(n)}_onA2UIAction(e){if(!e||typeof e.roomId!=`string`||typeof e.broadcastId!=`string`||!e.action||!this._rooms.get(e.roomId)||this._hasSeen(e.roomId,e.broadcastId)||(this._markSeen(e.roomId,e.broadcastId),this._surfaceOwners.get(e.action.surfaceId)!==this._myPeerId))return;let t={id:e.broadcastId,groupId:B(e.roomId),sender:e.senderAlias||e.senderPeerId,content:J(e.action,e.senderAlias),timestamp:Date.now(),channel:`room`,a2uiAction:e.action};this._opts.onMessage(t)}_onJoin(e,t){if(!t||typeof t.roomId!=`string`)return;let n=this._rooms.get(t.roomId);if(!n||n.hostPeerId!==this._myPeerId)return;let r=t.member??{peerId:e,alias:e,kind:`human`};r.peerId=e;let i=n.members.findIndex(t=>t.peerId===e);i>=0?n.members[i]=r:n.members.push(r),this._save(n),this._broadcastRoster(n)}_onLeave(e,t){if(!t||typeof t.roomId!=`string`)return;let n=this._rooms.get(t.roomId);n&&(t.disbanded?(this._rooms.delete(t.roomId),this._seen.delete(t.roomId),this._opts.removeRoom?.(t.roomId),this._publish()):n.hostPeerId===this._myPeerId&&(n.members=n.members.filter(n=>n.peerId!==(t.peerId||e)),this._save(n),this._broadcastRoster(n)))}_onMessage(e){if(!e||typeof e.roomId!=`string`||typeof e.messageId!=`string`||!this._rooms.get(e.roomId)||this._hasSeen(e.roomId,e.messageId))return;this._markSeen(e.roomId,e.messageId);let t={id:e.messageId,groupId:B(e.roomId),sender:e.senderAlias||e.senderPeerId,content:e.text??``,timestamp:Date.now(),channel:`room`,attachments:e.attachments?.map(e=>({fileName:e.fileName,mimeType:e.mimeType,path:e.path,size:e.size}))};this._opts.onMessage(t)}_onRelay(e){e&&typeof e.targetPeerId==`string`&&e.inner&&this.isHost(e.roomId)&&this._opts.transport.sendToPeer(e.targetPeerId,e.inner)}_onRoster(e){if(!e||typeof e.roomId!=`string`)return;let t=this._rooms.get(e.roomId),n={roomId:e.roomId,name:e.name??t?.name??e.roomId,hostPeerId:e.hostPeerId,members:Array.isArray(e.members)?e.members:[],createdAt:t?.createdAt??Date.now()};this._save(n)}_publish(){this.roomsSignal.set(this.list())}_save(e){this._rooms.set(e.roomId,e),this._opts.persistRoom?.(e),this._publish()}};function st(e){return e&&S(e)?Promise.resolve().then(()=>(e.db.prepare(`SELECT * FROM tasks WHERE enabled = 1`).all()??[]).map(e=>({...e,enabled:!0,tools:e.tools?JSON.parse(e.tools):void 0}))):new Promise(async(t,n)=>{try{let r=e??await b();if(!r)return n(/* @__PURE__ */ Error(`failed to get transaction, cannot get enabled tasks.`));let i=r.transaction(`tasks`,`readonly`);if(!i)return n(/* @__PURE__ */ Error(`failed to get transaction`));let a=i.objectStore(`tasks`).index(`by-enabled`).getAll(1);a.onsuccess=()=>{t(a.result.map(e=>({...e,enabled:!0})))},a.onerror=()=>n(a.error)}catch(e){n(e)}})}function ct(e,t){if(typeof e!=`string`||!e.trim())return!1;let n=e.trim().split(/\s+/);if(n.length!==5)return!1;let[r,i,a,o,s]=n;return Q(r,t.getMinutes())&&Q(i,t.getHours())&&Q(a,t.getDate())&&Q(o,t.getMonth()+1)&&Q(s,t.getDay())}function Q(e,t){return e===`*`||e.split(`,`).some(e=>{if(e.includes(`/`)){let[n,r]=e.split(`/`),i=parseInt(r,10);if(isNaN(i)||i<=0)return!1;if(n===`*`)return t%i===0;if(n.includes(`-`)){let[e,r]=n.split(`-`).map(Number);return t>=e&&t<=r&&(t-e)%i===0}let a=parseInt(n,10);return t>=a&&(t-a)%i===0}if(e.includes(`-`)){let[n,r]=e.split(`-`).map(Number);return t>=n&&t<=r}return parseInt(e,10)===t})}var lt=class{interval=null;onTaskChange;runner;shouldDefer;constructor(e,t,n){this.runner=e,this.onTaskChange=t,this.shouldDefer=n}ranThisMinute(e,t){if(!e.lastRun)return!1;let n=new Date(e.lastRun);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()&&n.getHours()===t.getHours()&&n.getMinutes()===t.getMinutes()}start(){this.interval||(this.interval=setInterval(()=>this.tick(),y),this.tick())}stop(){this.interval&&=(clearInterval(this.interval),null)}async tick(){try{let e=await st(),t=/* @__PURE__ */ new Date;for(let n of e){let e=n.schedule||``;if(e!==``&&ct(e,t)&&!this.ranThisMinute(n,t)){if(this.shouldDefer&&await this.shouldDefer(n))continue;await ie(n.id,t.getTime()),this.onTaskChange?.(),this.runner(n).catch(e=>{console.error(`Task ${n.id} failed:`,e)})}}}catch(e){console.error(`Scheduler tick error:`,e)}}};async function ut(e,t){e.channelEnabledByType.telegram=await R(`telegram`,t),e.channelEnabledByType.imessage=await R(`imessage`,t);let n=await e.loadSecretConfig(t,h.TELEGRAM_BOT_TOKEN),r=E(await C(t,h.TELEGRAM_CHAT_IDS)),i=await C(t,h.TELEGRAM_USE_PROXY)===`true`;e.telegramBotToken=n,e.telegramChatIds=r,e.telegramUseProxy=i,e.telegram.configure(n,r,i);let a=async(e,n)=>{try{let r=await ge(t,e,n),i=new Uint8Array(r.byteLength);i.set(r);let a=n.split(`/`).pop()||n,o=Ee(a);return new Blob([i],{type:o})}catch(e){return console.warn(`Orchestrator: channel fileReader failed for ${n}:`,e),null}};e.telegram.fileReader=a,e.imessage.fileReader=a;let o=(await C(t,h.IMESSAGE_SERVER_URL)||``).trim().replace(/\/+$/,``),s=await e.loadSecretConfig(t,h.IMESSAGE_API_KEY),c=E(await C(t,h.IMESSAGE_CHAT_IDS));e.imessageServerUrl=o,e.imessageApiKey=s,e.imessageChatIds=c,e.imessage.configure(o,s,c),e.channelEnabledByType.peerjs=await R(`peerjs`,t);let l=(await C(t,h.PEERJS_MY_PEER_ID)||``).trim(),u=E(await C(t,h.PEERJS_TRUSTED_PEER_IDS)),d=(await C(t,h.PEERJS_SERVER_HOST)||``).trim(),f=await C(t,h.PEERJS_SERVER_PORT),p=f&&parseInt(f,10)||0,m=(await C(t,h.PEERJS_SERVER_PATH)||``).trim(),g=await C(t,h.PEERJS_SERVER_SECURE)!==`false`,_={},v=await C(t,h.PEERJS_PEER_ALIASES);if(v)try{_=JSON.parse(v)}catch(e){console.warn(`Failed to parse peerjs_peer_aliases`,e)}e.peerjsMyPeerId=l,e.peerjsMyAlias=(await C(t,h.PEERJS_MY_ALIAS)||``).trim(),e.peerjsTrustedPeerIds=u,e.peerjsPeerAliases=_,e.peerjsServerHost=d,e.peerjsServerPort=p,e.peerjsServerPath=m,e.peerjsServerSecure=g;let y=d?{host:d,port:p||void 0,path:m||void 0,secure:g}:{};e.peerjs.configure(l,u,y)}const $={allowedTools:[`clear_chat`,`show_toast`],enabledChannelTypes:[`telegram`],requireMention:!0};function dt(e){if(!e)return{allowedTools:[...$.allowedTools],enabledChannelTypes:[...$.enabledChannelTypes],requireMention:$.requireMention};try{let t=JSON.parse(e),n=Array.isArray(t.enabledChannelTypes)?t.enabledChannelTypes.filter(e=>typeof e==`string`&&e.trim().length>0):$.enabledChannelTypes;return{allowedTools:Array.isArray(t.allowedTools)?t.allowedTools.filter(e=>typeof e==`string`&&e.trim().length>0):$.allowedTools,enabledChannelTypes:n,requireMention:typeof t.requireMention==`boolean`?t.requireMention:$.requireMention}}catch{return{allowedTools:[...$.allowedTools],enabledChannelTypes:[...$.enabledChannelTypes],requireMention:$.requireMention}}}function ft(e,t){typeof navigator<`u`&&navigator.serviceWorker&&((async()=>{try{let e=await M(t);await ye(e)}catch{}})(),navigator.serviceWorker.addEventListener(`message`,n=>{if(n.data?.type===`request-proxy-config`){ne(e);return}if(n.data?.type!==`scheduled-task-trigger`)return;let{taskId:r,groupId:i,prompt:a,taskType:o,tools:s,subscriberId:c}=n.data;i&&(async()=>{if(c){let e=await M(t);if(e&&c!==e){console.warn(`Ignoring push-triggered task ${r}: subscriberId mismatch (${c} !== ${e})`);return}}e.schedulerTriggeredGroups.add(i);try{let t=O.tasks.find(e=>e.id===r);if(t){O.runTask(t);return}if(o===`tools`&&Array.isArray(s)&&s.length>0){O.runTask({id:r||`push-task-${Date.now()}`,groupId:i,createdAt:Date.now(),enabled:!0,prompt:a||``,type:`tools`,tools:s,lastRun:null});return}a&&be(e,a,i)}finally{e.schedulerTriggeredGroups.delete(i)}})().catch(e=>console.error(`Push-triggered task ${r} failed:`,e))}))}function pt(e){return new ot({transport:{get myPeerId(){return e.peerjs.myPeerId||e.peerjsMyPeerId},sendToPeer:(t,n)=>e.peerjs.sendRoomNotification(t,n),isConnected:t=>e.peerjs.isPeerConnected(t),connectToPeer:t=>e.peerjs.connectPeer(t)},getLocalMember:()=>({peerId:e.peerjs.myPeerId||e.peerjsMyPeerId,alias:e.peerjsMyAlias||e.peerjs.myPeerId||e.peerjsMyPeerId||e.assistantName,kind:`agent`,agentName:e.assistantName}),onMessage:t=>e.roomChannel.deliverInbound(t),onInvite:t=>ve(e,t),persistRoom:t=>{e.db&&we(e.db,t).catch(e=>console.error(`Failed to persist room:`,e))},removeRoom:t=>{e.db&&Ce(e.db,t).catch(e=>console.error(`Failed to delete room:`,e))}})}async function mt(e,t){e.initializeChannelRegistry(),e.channelRegistry.onMessage(n=>{Y(e,t,n).catch(e=>{console.error(`Failed to enqueue inbound message:`,e)})}),e.channelRegistry.onTyping((t,n)=>{e.events.emit(`typing`,{groupId:t,typing:n}),t.startsWith(`peer:`)&&O.setRemoteAgentTyping(t,n)}),e.peerjs.onTaskComplete(t=>{e.peerCompletedContexts.add(t)}),await ut(e,t),Se(e);try{let n=await Te(t);e.roomManager.loadRooms(n)}catch(e){console.error(`Failed to load rooms:`,e)}}async function ht(e,t){e.assistantName=await C(t,h.ASSISTANT_NAME)||`ShadowClaw`,e.triggerPattern=o(e.assistantName)}async function gt(e,t){let n=await C(t,h.VM_BOOT_MODE);e.vmBootMode=n===`disabled`||n===`auto`||n===`9p`||n===`ext2`?n:`disabled`,e.streamingEnabled=await C(t,h.STREAMING_ENABLED)!==`false`,e.webMcpToolsEnabled=await C(t,h.WEBMCP_TOOLS_ENABLED)!==`false`,e.vmBashFullInternetAccess=await C(t,h.VM_BASH_FULL_INTERNET_ACCESS)===`true`;let r=await C(t,h.WEBMCP_MODE);(r===`native`||r===`polyfill`)&&ke(r),e.contextCompressionEnabled=await C(t,h.CONTEXT_COMPRESSION_ENABLED)===`true`;let i=await C(t,h.REASONING_EFFORT);e.reasoningEffort=i?i.trim().toLowerCase():`none`,e.directToolCommandPolicy=dt(await C(t,h.DIRECT_TOOL_COMMAND_POLICY)),e.useProxy=await C(t,h.USE_PROXY)===`true`,e.proxyUrl=await C(t,h.PROXY_URL)||`/proxy`,e.gitProxyUrl=await C(t,h.GIT_PROXY_URL)||`/git-proxy`,e.taskServerEnabled=await C(t,h.TASK_SERVER_ENABLED)===`true`,e.taskServerUrl=await C(t,h.TASK_SERVER_URL)||(await import(`./config-C16fFWtP.js`).then(e=>e.k)).DEFAULT_TASK_SERVER_URL}async function _t(e,t){let n=await C(t,h.LLAMAFILE_MODE);n===`cli`||n===`server`?e.llamafileMode=n:await k(t,h.LLAMAFILE_MODE,e.llamafileMode);let r=await C(t,h.LLAMAFILE_HOST);r&&(e.llamafileHost=r);let i=await C(t,h.LLAMAFILE_PORT);if(i){let t=parseInt(i,10);Number.isFinite(t)&&t>=1&&t<=65535&&(e.llamafilePort=t)}await C(t,h.LLAMAFILE_OFFLINE)===`false`&&(e.llamafileOffline=!1),me(e);let a=await C(t,h.MESH_LLM_HOST);a&&(e.meshLlmHost=a),fe(e)}async function vt(e,t){let[n,i,a,o,c,l,d,f,p]=await Promise.all([C(t,h.PROVIDER),C(t,h.BEDROCK_REGION_FALLBACK),C(t,h.BEDROCK_PROFILE_FALLBACK),C(t,h.BEDROCK_AUTH_MODE),C(t,h.MODEL),C(t,h.MAX_TOKENS),C(t,h.MAX_ITERATIONS),C(t,h.RATE_LIMIT_CALLS_PER_MINUTE),C(t,h.RATE_LIMIT_AUTO_ADAPT)]),m=n||e.provider,g=m?r(m):void 0;g&&(e.provider=m,e.providerConfig=g),await e.loadApiKeyForProvider(t,e.provider),e.bedrockRegionFallback=(i||``).trim(),e.bedrockProfileFallback=(a||``).trim(),e.bedrockAuthMode=(o||`provider_chain`).trim();let _=typeof document<`u`&&!!document.getElementById(`shadow-claw-static-routing`),v=e.providerConfig?.format===`transformers_js`,y=!!e.providerConfig?.modelsUrl,b=()=>{if(_||v||!y)return;let t=()=>{ue(e).then(t=>u.fetchModelInfo(e.providerConfig,t||void 0,de(e,e.provider)))};typeof globalThis.requestIdleCallback==`function`?globalThis.requestIdleCallback(t,{timeout:5e3}):setTimeout(t,2e3)};!_&&!v&&y&&(typeof window<`u`&&typeof document<`u`?document.readyState===`complete`?b():window.addEventListener(`load`,b,{once:!0}):b()),e.model=c||e.providerConfig.defaultModel;let x=e.model;e.provider===`prompt_api`&&!P()&&(e.model===`browser-built-in`||!e.model)&&(x=await C(t,h.PROMPT_API_FALLBACK_MODEL)||`onnx-community/Qwen3-0.6B-ONNX`,he(x).catch(()=>{}));let S=s(x);if(e.maxTokens=l===`8192`||e.provider===`prompt_api`&&!P()&&l===`4096`?S:Math.max(1,parseInt(l||String(S),10)),d&&(e.maxIterations=parseInt(d,10)||50),f){let t=parseInt(f,10);e.rateLimitCallsPerMinute=Number.isFinite(t)?Math.max(0,t):0}e.rateLimitAutoAdapt=p!==`false`}async function yt(t,n){t.agentWorker=e(new URL(`./agent.worker.js`,import.meta.url).href),t.agentWorker.onmessage=e=>Pe(t,n,e.data),t.agentWorker.onerror=e=>{console.error(`Agent worker error:`,e)};let r=await C(n,h.STORAGE_HANDLE);r&&t.agentWorker.postMessage({payload:{storageHandle:r},type:`set-storage`}),ne(t),t.scheduler=new lt(async e=>{await Me(t,e)},()=>{t.events.emit(`task-change`,{type:`executed`})},e=>je(e,t)),t.scheduler.start(),ft(t,n)}var bt=class{agentWorker=null;assistantName=_;bedrockAuthMode=`provider_chain`;bedrockProfileFallback=``;bedrockRegionFallback=``;browserChat=new Ue;channelEnabledByType={browser:!0,peerjs:!1,telegram:!1,imessage:!1};channelRegistry=new G;channelsInitialized=!1;contextCompressionEnabled=!1;db=null;directToolCommandPolicy={...$};ensureControlPlaneConnected=ze;events=new at;gitProxyUrl=`/git-proxy`;imessage=new We;imessageApiKey=``;imessageChatIds=[];imessageServerUrl=``;inFlightEffectiveProviderByGroup=/* @__PURE__ */ new Map;inFlightProviderRequestIds=/* @__PURE__ */ new Map;inFlightTriggerByGroup=/* @__PURE__ */ new Map;llamafileHost=`127.0.0.1`;llamafileMode=`cli`;llamafileOffline=!0;llamafilePort=8080;maxIterations=50;maxTokens=g;meshLlmHost=``;messageQueue=[];model=a().defaultModel;peerCompletedContexts=/* @__PURE__ */ new Set;peerjs=new Oe;peerjsMyAlias=``;peerjsMyPeerId=``;peerjsPeerAliases={};peerjsServerHost=``;peerjsServerPath=``;peerjsServerPort=0;peerjsServerSecure=!0;peerjsTrustedPeerIds=[];pendingScheduledTasks=/* @__PURE__ */ new Set;processing=!1;promptControllers=/* @__PURE__ */ new Map;provider=p;providerConfig=a();proxyUrl=`/proxy`;pushSubscriptionWarned=!1;rateLimitAutoAdapt=!0;rateLimitCallsPerMinute=0;reasoningEffort=`none`;roomChannel=new Ye;roomManager;router=null;scheduler=null;schedulerTriggeredGroups=/* @__PURE__ */ new Set;state=`idle`;streamingEnabled=!0;taskServerEnabled=!1;taskServerUrl=`/schedule`;telegram=new Xe;telegramBotToken=``;telegramChatIds=[];telegramUseProxy=!1;transformersProgressPollers=/* @__PURE__ */ new Map;triggerPattern=o(_);useProxy=!1;vmBashFullInternetAccess=!1;vmBootMode=`disabled`;vmStatus={ready:!1,booting:!1,bootAttempted:!1,error:null};webMcpEffectCleanup=null;webMcpRegistrationLock=Promise.resolve();webMcpToolsEnabled=!0;#e=null;#t=null;constructor(){this.roomManager=pt(this),this.initializeChannelRegistry()}clearProviderRequest(e){this.inFlightProviderRequestIds.delete(e)}createProviderRequestId(e){if(this.provider!==`llamafile`)return this.inFlightProviderRequestIds.delete(e),``;let t=`${e}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2,10)}`;return this.inFlightProviderRequestIds.set(e,t),t}async ensureWorkerReady(){this.db&&!this.channelsInitialized&&(this.channelsInitialized=!0,await mt(this,this.db),this.browserChat.onDisplay(()=>{})),!this.agentWorker&&this.db&&await yt(this,this.db),this.db&&(j.load(this.db),H(this,this.db))}initializeChannelRegistry(){this.channelRegistry=new G,this.channelRegistry.register(`br:`,this.browserChat,{badge:`Browser`,autoTrigger:!0}),this.channelRegistry.register(`tg:`,this.telegram,{badge:`Telegram`,autoTrigger:!1}),this.channelRegistry.register(`im:`,this.imessage,{badge:`iMessage`,autoTrigger:!0}),this.channelRegistry.register(`peer:`,this.peerjs,{badge:`PeerJS`,autoTrigger:!1}),this.channelRegistry.register(`room:`,this.roomChannel,{badge:`Room`,autoTrigger:!1}),this.roomChannel.setManager(this.roomManager),this.roomChannel.setPeerJs(this.peerjs),this.peerjs.setRoomNotificationHandler((e,t,n)=>this.roomManager.handleNotification(e,t,n)),this.router=new nt(this.channelRegistry)}setState(e,t){this.state=e,this.events.emit(`state-change`,{state:e,groupId:t})}shutdown(){this.channelRegistry.stopAll(),this.scheduler?.stop();for(let e of this.transformersProgressPollers.keys())F(this,e);this.agentWorker?.terminate(),typeof this.webMcpEffectCleanup==`function`&&this.webMcpEffectCleanup(),Ae()}async ensureAllConnections(e={}){let t=e.force??!1;try{await this.ensureControlPlaneConnected({orchestrator:this,db:this.db||void 0,force:t})}catch(e){console.warn(`Error ensuring Control Plane connection:`,e)}try{Se(this,t)}catch(e){console.warn(`Error ensuring channel connections:`,e)}this.taskServerEnabled&&this.db&&(O.replayTaskSyncOutbox(this.db),O.loadTasks(this.db)),this.scheduler&&(this.scheduler.start(),this.scheduler.tick())}stopCurrentRequest(e=m){if(this.state!==`thinking`&&this.state!==`responding`)return;F(this,e);let t=this.inFlightProviderRequestIds.get(e)||``;this.clearProviderRequest(e),this.agentWorker?.postMessage({type:`cancel`,payload:{groupId:e}}),this.provider===`llamafile`&&t&&pe(t);let n=this.promptControllers.get(e);n&&(n.abort(),this.promptControllers.delete(e)),this.inFlightTriggerByGroup.delete(e),this.inFlightEffectiveProviderByGroup.delete(e),this.events.emit(`typing`,{groupId:e,typing:!1}),this.router?.setTyping(e,!1),this.setState(`idle`,e)}async getApiKey(){if(!this.#t)return null;let e=Date.now();if(this.#e&&this.#e.expiresAt>e)return this.#e.value;try{let t=await I(this.#t);return t===null?null:(this.#e={expiresAt:e+3e4,value:t},t)}catch(e){return console.error(`[Orchestrator] Failed to decrypt API key:`,e),null}}async getApiKeyForSpecificProvider(e,t){let n=await C(e,i(t));if(!n&&t===`openrouter`){let t=await C(e,h.API_KEY);t&&(n=t)}if(!n)return``;try{return await I(n)||``}catch(e){return console.error(`[Orchestrator] Failed to decrypt API key:`,e),``}}async handleCompactDone(e,t,n){await D(e,t);let r={channel:this.channelRegistry.getChannelType(t)??`browser`,content:`📝 **Context Compacted**\n\n${n}`,groupId:t,id:A(),isFromMe:!0,isTrigger:!1,sender:this.assistantName,timestamp:Date.now()};await w(e,r),this.events.emit(`context-compacted`,{groupId:t,summary:n}),this.events.emit(`typing`,{groupId:t,typing:!1}),this.setState(`idle`,t)}async init(){let e=await He();this.db=e,await T(),await Promise.all([ht(this,e),vt(this,e),_t(this,e),gt(this,e)]),await T();let t=typeof document<`u`&&!!document.getElementById(`shadow-claw-static-routing`),n=re(),r=n?.sidebar?.chatHidden,i=n?.sidebar?.tasksHidden,[a,o]=await Promise.all([C(e,h.SIDEBAR_CHAT_HIDDEN),C(e,h.SIDEBAR_TASKS_HIDDEN)]),s=a==null?!!r:N(a),c=o==null?!!i:N(o),l=s&&c;t?l||setTimeout(()=>{this.ensureWorkerReady()},15e3):l||await yt(this,e),l||(this.channelsInitialized=!0,mt(this,e).then(()=>{this.browserChat.onDisplay(()=>{})})),this.events.emit(`ready`,void 0);let u=typeof globalThis<`u`?globalThis.window:void 0;return t?l||setTimeout(()=>{j.load(e),H(this,e)},15e3):u&&typeof u.requestIdleCallback==`function`?l||u.requestIdleCallback(()=>{j.load(e),H(this,e)}):l||(await j.load(e),H(this,e)),e}async loadApiKeyForProvider(e,t){let n=await C(e,i(t));if(!n&&t===`openrouter`){let r=await C(e,h.API_KEY);r&&(n=r,await k(e,i(t),r))}this.#t=n||``,this.#e=null}async loadSecretConfig(e,t){let n=await C(e,t);if(!n)return``;try{return await I(n)||``}catch{let r=await L(n);return r&&await k(e,t,r),n}}async newSession(e,t=m){await D(e,t),this.events.emit(`session-reset`,{groupId:t})}async refreshContextUsage(e,t=m){let n=``;try{n=await ae(e,t,`MEMORY.md`)}catch{}let i=j.enabledTools,a=O.getPeerState(t)||void 0,o=Re(this.assistantName,n,i,j.systemPromptOverride,a,void 0,{groupId:t}),c=(await te(e)).find(e=>e.groupId===t),l=c?.pinnedModel??(c?.pinnedProvider?r(c.pinnedProvider)?.defaultModel??this.model:this.model),u=l;(c?.pinnedProvider??this.provider)===`prompt_api`&&(l===`browser-built-in`||!l)&&!P()&&(u=await C(this.db,h.PROMPT_API_FALLBACK_MODEL)||`onnx-community/Qwen3-0.6B-ONNX`);let d=typeof c?.pinnedMaxTokens==`number`&&Number.isFinite(c.pinnedMaxTokens)&&c.pinnedMaxTokens>0?Math.floor(c.pinnedMaxTokens):this.maxTokens,f=Math.max(1,Math.min(d,s(u))),p=Ne(u),g=U(o)+(i?.reduce((e,t)=>e+U(JSON.stringify(t)),0)??0),_=await Ie(t,200),v=Le(_,{contextLimit:p,systemPromptTokens:g,maxOutputTokens:f,skimTop:this.contextCompressionEnabled}),y=v.estimatedTokens+g;if(O.tokenUsage){let e=O.tokenUsage,t=(e.inputTokens||0)+(e.cacheReadTokens||0)+(e.outputTokens||0);y=Math.max(y,t)}this.events.emit(`context-usage`,{estimatedTokens:y,contextLimit:p,usagePercent:Math.min(100,Math.max(v.usagePercent,y/p*100)),truncatedCount:v.truncatedCount})}async restartCurrentRequest(e=m){if(this.state!==`thinking`&&this.state!==`responding`||!this.db)return!1;let t=this.inFlightTriggerByGroup.get(e);if(!t)return!1;this.stopCurrentRequest(e);let{invokeAgent:n}=await import(`./invoke-agent-CN7mSV0Z.js`);return await n(this,this.db,e,t),!0}async routeRoomA2UIAction(e,t){let n=z(e),r=this.peerjs.myPeerId||this.peerjsMyPeerId,i=this.roomManager.getSurfaceOwner(t.surfaceId);if(!i||i===r){if(!this.db)return;await Y(this,this.db,{id:A(),groupId:e,sender:this.peerjsMyAlias||r||`you`,content:J(t),timestamp:Date.now(),channel:`room`,a2uiAction:t})}else this.roomManager.broadcastA2UIAction(n,t)}async saveSecretConfig(e,t,n){if(!n){await k(e,t,``);return}let r=await L(n);if(!r)throw Error(`Failed to encrypt secret config for ${t}`);await k(e,t,r)}async setApiKey(e,t){this.#t=await L(t),this.#e=null;let n=await L(t);if(!n)throw Error(`key failed to encrypt. config cannot set.`);await k(e,i(this.provider),n)}submitMessage(e,t=m){this.browserChat.submit(e,t)}};export{bt as Orchestrator};
3
+ `)}\n</messages>`}static formatOutbound(e){return e.replace(/<internal>[\s\S]*?<\/internal>/g,``).trim()}registry;constructor(e){this.registry=e}findChannel(e){return this.registry.find(e)}setTyping(e,t){this.findChannel(e)?.setTyping(e,t)}async send(e,t,n){let r=this.findChannel(e);r?await r.send(e,t,n):console.warn(`No channel for groupId: ${e}`)}};function rt(e,t,n){if(!e.enabledChannelTypes.includes(n.channel))return null;let r=n.content.trim(),i=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=r;if(e.requireMention){let e=RegExp(`^@${i}\\b\\s*(?:-|:)?\\s*`,`i`);if(!e.test(a))return null;a=a.replace(e,``).trim()}let o=a.match(/^\/([a-zA-Z0-9_]+)(?:\s+([\s\S]+))?$/);if(!o)return null;let s=o[1];if(!e.allowedTools.includes(s))return null;let c=(o[2]||``).trim();if(!c)return{toolName:s,input:{}};let l=c.startsWith(`'`)&&c.endsWith(`'`)||c.startsWith(`"`)&&c.endsWith(`"`)?c.slice(1,-1).trim():c;try{let e=JSON.parse(l);return e&&typeof e==`object`?{toolName:s,input:e}:null}catch{return null}}function it(e,t){let n=e.trim().match(/^\/([a-z0-9](?:[a-z0-9]|-(?!-))*[a-z0-9]|[a-z0-9])(?:\s+([\s\S]+))?$/u);if(!n)return null;let r=t.find(e=>e.name===n[1]&&e.userInvocable!==!1);return r?{skill:r,arguments:(n[2]||``).trim()}:null}async function Y(e,t,n){if(n.a2uiEnvelopes&&n.a2uiEnvelopes.length>0)for(let t of n.a2uiEnvelopes)e.events.emit(`a2ui-surface`,{groupId:n.groupId,envelope:t});n.a2uiAction&&e.events.emit(`a2ui-action`,{groupId:n.groupId,action:n.a2uiAction});let r=!!n.content,i=(n.attachments?.length??0)>0;if(!r&&!i&&(n.a2uiEnvelopes?.length??0)>0)return;let a=rt(e.directToolCommandPolicy,e.assistantName,n),o=a?null:it(n.content,(await Fe(t,n.groupId)).skills),s=n.channel===`browser`,c=e.channelRegistry.shouldAutoTrigger(n.groupId),l=!1;(n.channel===`browser`||n.groupId.startsWith(`room:`))&&(l=e.triggerPattern.test(n.content.trim())),o&&(l=!0),s&&n.groupId.startsWith(`peer:`)&&e.peerCompletedContexts.delete(n.groupId);let u=!!a;if(!l&&e.peerjsMyPeerId){if(n.content.includes(`@${e.peerjsMyPeerId}`))l=!0;else if(e.peerjsMyAlias&&n.content.includes(`@${e.peerjsMyAlias}`))l=!0;else for(let[t,r]of Object.entries(e.peerjsPeerAliases))if(r===e.peerjsMyPeerId&&n.content.includes(`@${t}`)){l=!0;break}}n.content.trim().startsWith(`[SCHEDULED TASK]`)&&(l=!0),n.content.trim().startsWith(`[A2UI ACTION]`)&&(l=!0);let d=!1;d=u||l?!0:s?!(n.groupId.startsWith(`peer:`)||n.groupId.startsWith(`room:`)):c,d&&!s&&!o&&n.groupId.startsWith(`peer:`)&&e.peerCompletedContexts.has(n.groupId)&&(d=!1);let f=await De(t,n.groupId,n.attachments||[]),p={...n,attachments:f,isFromMe:!1,isTrigger:d};if(d&&!u&&!o?.skill.execution&&e.messageQueue.push(o?{...n,content:`[SKILL COMMAND] Activate the "${o.skill.name}" skill and follow its instructions.\n${o.arguments}`}:n),await w(t,p),e.events.emit(`message`,p),o?.skill.execution){if(await e.ensureWorkerReady?.(),!e.agentWorker)throw Error(`Worker is not initialized.`);let t=o.skill.execution.tools.map(e=>{let t=e.input&&typeof e.input==`object`?{...e.input}:{};return o.arguments&&Object.keys(t).length===0&&(t.rawInput=o.arguments),{...e,input:t}});e.agentWorker.postMessage({type:`execute-skill-tools`,payload:{groupId:n.groupId,skillName:o.skill.name,tools:t}})}else if(n.channel===`peerjs`&&xe(n.groupId),s&&(n.groupId.startsWith(`peer:`)||n.groupId.startsWith(`room:`))&&e.router?.send(n.groupId,n.content,f).catch(e=>{console.error(`Failed to route browser message to peer:`,e)}),a){if(await e.ensureWorkerReady?.(),!e.agentWorker)throw Error(`Worker is not initialized.`);e.agentWorker.postMessage({type:`execute-direct-tool`,payload:{groupId:n.groupId,name:a.toolName,input:a.input}})}else X(e,t)}async function X(e,t){if(e.processing||e.messageQueue.length===0)return;let n=e.messageQueue[0]?.groupId,i=e.providerConfig,a=e.provider;if(n)try{let e=(await te(t)).find(e=>e.groupId===n);if(e?.pinnedProvider){let t=r(e.pinnedProvider);t&&(i=t,a=e.pinnedProvider)}}catch{}let o=i?.requiresApiKey!==!1,s=!0;if(o&&(s=a===e.provider?!!await le(e):!!await e.getApiKeyForSpecificProvider(t,a)),o&&!s){let t=`API key not configured. Go to Settings to add your API key.`;e.events.emit(`provider-help`,{providerId:a,reason:t,helpType:_e(a,t,o)});let n=e.messageQueue.shift();e.events.emit(`error`,{groupId:n.groupId,error:t});return}e.processing=!0;let c=e.messageQueue.shift();try{let{invokeAgent:n}=await import(`./invoke-agent-C_geruwq.js`);await n(e,t,c.groupId,c.content,c.freshContext,c.subagent)}catch(e){console.error(`Failed to invoke agent:`,e)}finally{e.processing=!1,e.messageQueue.length>0&&X(e,t)}}var at=class{listeners;constructor(){this.listeners=/* @__PURE__ */ new Map}emit(e,t){this.listeners.get(e)?.forEach(e=>e(t))}off(e,t){this.listeners.get(e)?.delete(t)}on(e,t){this.listeners.has(e)||this.listeners.set(e,/* @__PURE__ */ new Set),this.listeners.get(e)?.add(t)}};function Z(e,t){return{jsonrpc:`2.0`,method:e,params:t}}var ot=class{static isRoomMethod(e){return e===V.JOIN||e===V.ROSTER||e===V.LEAVE||e===V.MESSAGE||e===V.INVITE||e===V.RELAY||e===V.A2UI||e===V.A2UI_ACTION}roomsSignal=new ee.State([]);_opts;_rooms=/* @__PURE__ */ new Map;_seen=/* @__PURE__ */ new Map;_surfaceOwners=/* @__PURE__ */ new Map;constructor(e){this._opts=e}broadcast(e,t,n){let r=this._rooms.get(e);if(!r)return null;let i=this._opts.getLocalMember(),a=A(),o={roomId:e,messageId:a,senderPeerId:i.peerId,senderAlias:i.alias,text:t,attachments:n?.map(e=>({fileName:e.fileName,mimeType:e.mimeType,path:e.path,size:e.size}))};return this._markSeen(e,a),this._deliverToMembers(r,Z(V.MESSAGE,o)),a}broadcastA2UI(e,t){let n=this._rooms.get(e);if(!n)return null;let r=this._myPeerId;this._surfaceOwners.set(t.surfaceId,r);let i=A(),a={roomId:e,broadcastId:i,ownerPeerId:r,senderPeerId:r,envelope:t};return this._markSeen(e,i),this._deliverToMembers(n,Z(V.A2UI,a)),i}broadcastA2UIAction(e,t){let n=this._rooms.get(e);if(!n)return null;let r=this._opts.getLocalMember(),i=this._surfaceOwners.get(t.surfaceId)??``,a=A(),o={roomId:e,broadcastId:a,ownerPeerId:i,senderPeerId:r.peerId,senderAlias:r.alias,action:t};return this._markSeen(e,a),this._deliverToMembers(n,Z(V.A2UI_ACTION,o)),a}createRoom(e){let t=this._opts.getLocalMember(),n={roomId:A(),name:e,hostPeerId:t.peerId,members:[t],createdAt:Date.now()};return this._save(n),n}get(e){return this._rooms.get(e)??null}getSurfaceOwner(e){return this._surfaceOwners.get(e)}handleNotification(e,t,n){switch(t){case V.JOIN:this._onJoin(e,n);break;case V.ROSTER:this._onRoster(n);break;case V.LEAVE:this._onLeave(e,n);break;case V.MESSAGE:this._onMessage(n);break;case V.INVITE:this._opts.onInvite?.(n);break;case V.RELAY:this._onRelay(n);break;case V.A2UI:this._onA2UI(n);break;case V.A2UI_ACTION:this._onA2UIAction(n)}}invite(e,t){let n=this._rooms.get(e);if(!n)return!1;let r=this._opts.getLocalMember(),i={roomId:e,roomName:n.name,hostPeerId:n.hostPeerId,fromPeerId:r.peerId,fromAlias:r.alias},a=this._opts.transport;return a.connectToPeer(t),a.sendToPeer(t,Z(V.INVITE,i))}isHost(e){let t=this._rooms.get(e);return!!t&&t.hostPeerId===this._myPeerId}joinRoom(e,t,n){let r=this._opts.getLocalMember(),i=this._rooms.get(e)??{roomId:e,name:n,hostPeerId:t,members:[{peerId:t,alias:t,kind:`agent`},r],createdAt:Date.now()};this._save(i);let a=this._opts.transport;a.connectToPeer(t);let o={roomId:e,member:r};return a.sendToPeer(t,Z(V.JOIN,o)),i}leaveRoom(e){let t=this._rooms.get(e);if(!t)return;let n=this._myPeerId;if(t.hostPeerId===n){let r={roomId:e,peerId:n,disbanded:!0};this._deliverToMembers(t,Z(V.LEAVE,r))}else{let r={roomId:e,peerId:n};this._opts.transport.sendToPeer(t.hostPeerId,Z(V.LEAVE,r))}this._rooms.delete(e),this._seen.delete(e),this._opts.removeRoom?.(e),this._publish()}list(){return Array.from(this._rooms.values())}loadRooms(e){this._rooms.clear();for(let t of e)this._rooms.set(t.roomId,t);this._publish()}_broadcastRoster(e){let t={roomId:e.roomId,name:e.name,hostPeerId:e.hostPeerId,members:e.members};this._deliverToMembers(e,Z(V.ROSTER,t))}_deliverToMembers(e,t){let n=this._myPeerId;for(let r of e.members)r.peerId!==n&&this._deliverToPeer(e,r.peerId,t)}_deliverToPeer(e,t,n){let r=this._opts.transport;if(r.isConnected(t)){r.sendToPeer(t,n);return}let i=this._myPeerId;if(e.hostPeerId!==i&&e.hostPeerId!==t&&r.isConnected(e.hostPeerId)){let i={roomId:e.roomId,targetPeerId:t,inner:n};r.sendToPeer(e.hostPeerId,Z(V.RELAY,i)),r.connectToPeer(t)}else r.connectToPeer(t),r.sendToPeer(t,n)}_hasSeen(e,t){return this._seen.get(e)?.has(t)??!1}_markSeen(e,t){let n=this._seen.get(e);if(n||(n=/* @__PURE__ */ new Set,this._seen.set(e,n)),n.add(t),n.size>500){let e=n.values().next().value;e!==void 0&&n.delete(e)}}get _myPeerId(){return this._opts.transport.myPeerId}_onA2UI(e){if(!e||typeof e.roomId!=`string`||typeof e.broadcastId!=`string`||!e.envelope||!this._rooms.get(e.roomId)||this._hasSeen(e.roomId,e.broadcastId))return;this._markSeen(e.roomId,e.broadcastId);let t=e.envelope.surfaceId;this._surfaceOwners.get(t)!==this._myPeerId&&this._surfaceOwners.set(t,e.ownerPeerId);let n={id:e.broadcastId,groupId:B(e.roomId),sender:e.senderPeerId,content:``,timestamp:Date.now(),channel:`room`,a2uiEnvelopes:[e.envelope]};this._opts.onMessage(n)}_onA2UIAction(e){if(!e||typeof e.roomId!=`string`||typeof e.broadcastId!=`string`||!e.action||!this._rooms.get(e.roomId)||this._hasSeen(e.roomId,e.broadcastId)||(this._markSeen(e.roomId,e.broadcastId),this._surfaceOwners.get(e.action.surfaceId)!==this._myPeerId))return;let t={id:e.broadcastId,groupId:B(e.roomId),sender:e.senderAlias||e.senderPeerId,content:J(e.action,e.senderAlias),timestamp:Date.now(),channel:`room`,a2uiAction:e.action};this._opts.onMessage(t)}_onJoin(e,t){if(!t||typeof t.roomId!=`string`)return;let n=this._rooms.get(t.roomId);if(!n||n.hostPeerId!==this._myPeerId)return;let r=t.member??{peerId:e,alias:e,kind:`human`};r.peerId=e;let i=n.members.findIndex(t=>t.peerId===e);i>=0?n.members[i]=r:n.members.push(r),this._save(n),this._broadcastRoster(n)}_onLeave(e,t){if(!t||typeof t.roomId!=`string`)return;let n=this._rooms.get(t.roomId);n&&(t.disbanded?(this._rooms.delete(t.roomId),this._seen.delete(t.roomId),this._opts.removeRoom?.(t.roomId),this._publish()):n.hostPeerId===this._myPeerId&&(n.members=n.members.filter(n=>n.peerId!==(t.peerId||e)),this._save(n),this._broadcastRoster(n)))}_onMessage(e){if(!e||typeof e.roomId!=`string`||typeof e.messageId!=`string`||!this._rooms.get(e.roomId)||this._hasSeen(e.roomId,e.messageId))return;this._markSeen(e.roomId,e.messageId);let t={id:e.messageId,groupId:B(e.roomId),sender:e.senderAlias||e.senderPeerId,content:e.text??``,timestamp:Date.now(),channel:`room`,attachments:e.attachments?.map(e=>({fileName:e.fileName,mimeType:e.mimeType,path:e.path,size:e.size}))};this._opts.onMessage(t)}_onRelay(e){e&&typeof e.targetPeerId==`string`&&e.inner&&this.isHost(e.roomId)&&this._opts.transport.sendToPeer(e.targetPeerId,e.inner)}_onRoster(e){if(!e||typeof e.roomId!=`string`)return;let t=this._rooms.get(e.roomId),n={roomId:e.roomId,name:e.name??t?.name??e.roomId,hostPeerId:e.hostPeerId,members:Array.isArray(e.members)?e.members:[],createdAt:t?.createdAt??Date.now()};this._save(n)}_publish(){this.roomsSignal.set(this.list())}_save(e){this._rooms.set(e.roomId,e),this._opts.persistRoom?.(e),this._publish()}};function st(e){return e&&S(e)?Promise.resolve().then(()=>(e.db.prepare(`SELECT * FROM tasks WHERE enabled = 1`).all()??[]).map(e=>({...e,enabled:!0,tools:e.tools?JSON.parse(e.tools):void 0}))):new Promise(async(t,n)=>{try{let r=e??await b();if(!r)return n(/* @__PURE__ */ Error(`failed to get transaction, cannot get enabled tasks.`));let i=r.transaction(`tasks`,`readonly`);if(!i)return n(/* @__PURE__ */ Error(`failed to get transaction`));let a=i.objectStore(`tasks`).index(`by-enabled`).getAll(1);a.onsuccess=()=>{t(a.result.map(e=>({...e,enabled:!0})))},a.onerror=()=>n(a.error)}catch(e){n(e)}})}function ct(e,t){if(typeof e!=`string`||!e.trim())return!1;let n=e.trim().split(/\s+/);if(n.length!==5)return!1;let[r,i,a,o,s]=n;return Q(r,t.getMinutes())&&Q(i,t.getHours())&&Q(a,t.getDate())&&Q(o,t.getMonth()+1)&&Q(s,t.getDay())}function Q(e,t){return e===`*`||e.split(`,`).some(e=>{if(e.includes(`/`)){let[n,r]=e.split(`/`),i=parseInt(r,10);if(isNaN(i)||i<=0)return!1;if(n===`*`)return t%i===0;if(n.includes(`-`)){let[e,r]=n.split(`-`).map(Number);return t>=e&&t<=r&&(t-e)%i===0}let a=parseInt(n,10);return t>=a&&(t-a)%i===0}if(e.includes(`-`)){let[n,r]=e.split(`-`).map(Number);return t>=n&&t<=r}return parseInt(e,10)===t})}var lt=class{interval=null;onTaskChange;runner;shouldDefer;constructor(e,t,n){this.runner=e,this.onTaskChange=t,this.shouldDefer=n}ranThisMinute(e,t){if(!e.lastRun)return!1;let n=new Date(e.lastRun);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()&&n.getHours()===t.getHours()&&n.getMinutes()===t.getMinutes()}start(){this.interval||(this.interval=setInterval(()=>this.tick(),y),this.tick())}stop(){this.interval&&=(clearInterval(this.interval),null)}async tick(){try{let e=await st(),t=/* @__PURE__ */ new Date;for(let n of e){let e=n.schedule||``;if(e!==``&&ct(e,t)&&!this.ranThisMinute(n,t)){if(this.shouldDefer&&await this.shouldDefer(n))continue;await ie(n.id,t.getTime()),this.onTaskChange?.(),this.runner(n).catch(e=>{console.error(`Task ${n.id} failed:`,e)})}}}catch(e){console.error(`Scheduler tick error:`,e)}}};async function ut(e,t){e.channelEnabledByType.telegram=await R(`telegram`,t),e.channelEnabledByType.imessage=await R(`imessage`,t);let n=await e.loadSecretConfig(t,h.TELEGRAM_BOT_TOKEN),r=E(await C(t,h.TELEGRAM_CHAT_IDS)),i=await C(t,h.TELEGRAM_USE_PROXY)===`true`;e.telegramBotToken=n,e.telegramChatIds=r,e.telegramUseProxy=i,e.telegram.configure(n,r,i);let a=async(e,n)=>{try{let r=await ge(t,e,n),i=new Uint8Array(r.byteLength);i.set(r);let a=n.split(`/`).pop()||n,o=Ee(a);return new Blob([i],{type:o})}catch(e){return console.warn(`Orchestrator: channel fileReader failed for ${n}:`,e),null}};e.telegram.fileReader=a,e.imessage.fileReader=a;let o=(await C(t,h.IMESSAGE_SERVER_URL)||``).trim().replace(/\/+$/,``),s=await e.loadSecretConfig(t,h.IMESSAGE_API_KEY),c=E(await C(t,h.IMESSAGE_CHAT_IDS));e.imessageServerUrl=o,e.imessageApiKey=s,e.imessageChatIds=c,e.imessage.configure(o,s,c),e.channelEnabledByType.peerjs=await R(`peerjs`,t);let l=(await C(t,h.PEERJS_MY_PEER_ID)||``).trim(),u=E(await C(t,h.PEERJS_TRUSTED_PEER_IDS)),d=(await C(t,h.PEERJS_SERVER_HOST)||``).trim(),f=await C(t,h.PEERJS_SERVER_PORT),p=f&&parseInt(f,10)||0,m=(await C(t,h.PEERJS_SERVER_PATH)||``).trim(),g=await C(t,h.PEERJS_SERVER_SECURE)!==`false`,_={},v=await C(t,h.PEERJS_PEER_ALIASES);if(v)try{_=JSON.parse(v)}catch(e){console.warn(`Failed to parse peerjs_peer_aliases`,e)}e.peerjsMyPeerId=l,e.peerjsMyAlias=(await C(t,h.PEERJS_MY_ALIAS)||``).trim(),e.peerjsTrustedPeerIds=u,e.peerjsPeerAliases=_,e.peerjsServerHost=d,e.peerjsServerPort=p,e.peerjsServerPath=m,e.peerjsServerSecure=g;let y=d?{host:d,port:p||void 0,path:m||void 0,secure:g}:{};e.peerjs.configure(l,u,y)}const $={allowedTools:[`clear_chat`,`show_toast`],enabledChannelTypes:[`telegram`],requireMention:!0};function dt(e){if(!e)return{allowedTools:[...$.allowedTools],enabledChannelTypes:[...$.enabledChannelTypes],requireMention:$.requireMention};try{let t=JSON.parse(e),n=Array.isArray(t.enabledChannelTypes)?t.enabledChannelTypes.filter(e=>typeof e==`string`&&e.trim().length>0):$.enabledChannelTypes;return{allowedTools:Array.isArray(t.allowedTools)?t.allowedTools.filter(e=>typeof e==`string`&&e.trim().length>0):$.allowedTools,enabledChannelTypes:n,requireMention:typeof t.requireMention==`boolean`?t.requireMention:$.requireMention}}catch{return{allowedTools:[...$.allowedTools],enabledChannelTypes:[...$.enabledChannelTypes],requireMention:$.requireMention}}}function ft(e,t){typeof navigator<`u`&&navigator.serviceWorker&&((async()=>{try{let e=await M(t);await ye(e)}catch{}})(),navigator.serviceWorker.addEventListener(`message`,n=>{if(n.data?.type===`request-proxy-config`){ne(e);return}if(n.data?.type!==`scheduled-task-trigger`)return;let{taskId:r,groupId:i,prompt:a,taskType:o,tools:s,subscriberId:c}=n.data;i&&(async()=>{if(c){let e=await M(t);if(e&&c!==e){console.warn(`Ignoring push-triggered task ${r}: subscriberId mismatch (${c} !== ${e})`);return}}e.schedulerTriggeredGroups.add(i);try{let t=O.tasks.find(e=>e.id===r);if(t){O.runTask(t);return}if(o===`tools`&&Array.isArray(s)&&s.length>0){O.runTask({id:r||`push-task-${Date.now()}`,groupId:i,createdAt:Date.now(),enabled:!0,prompt:a||``,type:`tools`,tools:s,lastRun:null});return}a&&be(e,a,i)}finally{e.schedulerTriggeredGroups.delete(i)}})().catch(e=>console.error(`Push-triggered task ${r} failed:`,e))}))}function pt(e){return new ot({transport:{get myPeerId(){return e.peerjs.myPeerId||e.peerjsMyPeerId},sendToPeer:(t,n)=>e.peerjs.sendRoomNotification(t,n),isConnected:t=>e.peerjs.isPeerConnected(t),connectToPeer:t=>e.peerjs.connectPeer(t)},getLocalMember:()=>({peerId:e.peerjs.myPeerId||e.peerjsMyPeerId,alias:e.peerjsMyAlias||e.peerjs.myPeerId||e.peerjsMyPeerId||e.assistantName,kind:`agent`,agentName:e.assistantName}),onMessage:t=>e.roomChannel.deliverInbound(t),onInvite:t=>ve(e,t),persistRoom:t=>{e.db&&we(e.db,t).catch(e=>console.error(`Failed to persist room:`,e))},removeRoom:t=>{e.db&&Ce(e.db,t).catch(e=>console.error(`Failed to delete room:`,e))}})}async function mt(e,t){e.initializeChannelRegistry(),e.channelRegistry.onMessage(n=>{Y(e,t,n).catch(e=>{console.error(`Failed to enqueue inbound message:`,e)})}),e.channelRegistry.onTyping((t,n)=>{e.events.emit(`typing`,{groupId:t,typing:n}),t.startsWith(`peer:`)&&O.setRemoteAgentTyping(t,n)}),e.peerjs.onTaskComplete(t=>{e.peerCompletedContexts.add(t)}),await ut(e,t),Se(e);try{let n=await Te(t);e.roomManager.loadRooms(n)}catch(e){console.error(`Failed to load rooms:`,e)}}async function ht(e,t){e.assistantName=await C(t,h.ASSISTANT_NAME)||`ShadowClaw`,e.triggerPattern=o(e.assistantName)}async function gt(e,t){let n=await C(t,h.VM_BOOT_MODE);e.vmBootMode=n===`disabled`||n===`auto`||n===`9p`||n===`ext2`?n:`disabled`,e.streamingEnabled=await C(t,h.STREAMING_ENABLED)!==`false`,e.webMcpToolsEnabled=await C(t,h.WEBMCP_TOOLS_ENABLED)!==`false`,e.vmBashFullInternetAccess=await C(t,h.VM_BASH_FULL_INTERNET_ACCESS)===`true`;let r=await C(t,h.WEBMCP_MODE);(r===`native`||r===`polyfill`)&&ke(r),e.contextCompressionEnabled=await C(t,h.CONTEXT_COMPRESSION_ENABLED)===`true`;let i=await C(t,h.REASONING_EFFORT);e.reasoningEffort=i?i.trim().toLowerCase():`none`,e.directToolCommandPolicy=dt(await C(t,h.DIRECT_TOOL_COMMAND_POLICY)),e.useProxy=await C(t,h.USE_PROXY)===`true`,e.proxyUrl=await C(t,h.PROXY_URL)||`/proxy`,e.gitProxyUrl=await C(t,h.GIT_PROXY_URL)||`/git-proxy`,e.taskServerEnabled=await C(t,h.TASK_SERVER_ENABLED)===`true`,e.taskServerUrl=await C(t,h.TASK_SERVER_URL)||(await import(`./config-C16fFWtP.js`).then(e=>e.k)).DEFAULT_TASK_SERVER_URL}async function _t(e,t){let n=await C(t,h.LLAMAFILE_MODE);n===`cli`||n===`server`?e.llamafileMode=n:await k(t,h.LLAMAFILE_MODE,e.llamafileMode);let r=await C(t,h.LLAMAFILE_HOST);r&&(e.llamafileHost=r);let i=await C(t,h.LLAMAFILE_PORT);if(i){let t=parseInt(i,10);Number.isFinite(t)&&t>=1&&t<=65535&&(e.llamafilePort=t)}await C(t,h.LLAMAFILE_OFFLINE)===`false`&&(e.llamafileOffline=!1),me(e);let a=await C(t,h.MESH_LLM_HOST);a&&(e.meshLlmHost=a),fe(e)}async function vt(e,t){let[n,i,a,o,c,l,d,f,p]=await Promise.all([C(t,h.PROVIDER),C(t,h.BEDROCK_REGION_FALLBACK),C(t,h.BEDROCK_PROFILE_FALLBACK),C(t,h.BEDROCK_AUTH_MODE),C(t,h.MODEL),C(t,h.MAX_TOKENS),C(t,h.MAX_ITERATIONS),C(t,h.RATE_LIMIT_CALLS_PER_MINUTE),C(t,h.RATE_LIMIT_AUTO_ADAPT)]),m=n||e.provider,g=m?r(m):void 0;g&&(e.provider=m,e.providerConfig=g),await e.loadApiKeyForProvider(t,e.provider),e.bedrockRegionFallback=(i||``).trim(),e.bedrockProfileFallback=(a||``).trim(),e.bedrockAuthMode=(o||`provider_chain`).trim();let _=typeof document<`u`&&!!document.getElementById(`shadow-claw-static-routing`),v=e.providerConfig?.format===`transformers_js`,y=!!e.providerConfig?.modelsUrl,b=()=>{if(_||v||!y)return;let t=()=>{ue(e).then(t=>u.fetchModelInfo(e.providerConfig,t||void 0,de(e,e.provider)))};typeof globalThis.requestIdleCallback==`function`?globalThis.requestIdleCallback(t,{timeout:5e3}):setTimeout(t,2e3)};!_&&!v&&y&&(typeof window<`u`&&typeof document<`u`?document.readyState===`complete`?b():window.addEventListener(`load`,b,{once:!0}):b()),e.model=c||e.providerConfig.defaultModel;let x=e.model;e.provider===`prompt_api`&&!P()&&(e.model===`browser-built-in`||!e.model)&&(x=await C(t,h.PROMPT_API_FALLBACK_MODEL)||`onnx-community/Qwen3-0.6B-ONNX`,he(x).catch(()=>{}));let S=s(x);if(e.maxTokens=l===`8192`||e.provider===`prompt_api`&&!P()&&l===`4096`?S:Math.max(1,parseInt(l||String(S),10)),d&&(e.maxIterations=parseInt(d,10)||50),f){let t=parseInt(f,10);e.rateLimitCallsPerMinute=Number.isFinite(t)?Math.max(0,t):0}e.rateLimitAutoAdapt=p!==`false`}async function yt(t,n){t.agentWorker=e(new URL(`./agent.worker.js`,import.meta.url).href),t.agentWorker.onmessage=e=>Pe(t,n,e.data),t.agentWorker.onerror=e=>{console.error(`Agent worker error:`,e)};let r=await C(n,h.STORAGE_HANDLE);r&&t.agentWorker.postMessage({payload:{storageHandle:r},type:`set-storage`}),ne(t),t.scheduler=new lt(async e=>{await Me(t,e)},()=>{t.events.emit(`task-change`,{type:`executed`})},e=>je(e,t)),t.scheduler.start(),ft(t,n)}var bt=class{agentWorker=null;assistantName=_;bedrockAuthMode=`provider_chain`;bedrockProfileFallback=``;bedrockRegionFallback=``;browserChat=new Ue;channelEnabledByType={browser:!0,peerjs:!1,telegram:!1,imessage:!1};channelRegistry=new G;channelsInitialized=!1;contextCompressionEnabled=!1;db=null;directToolCommandPolicy={...$};ensureControlPlaneConnected=ze;events=new at;gitProxyUrl=`/git-proxy`;imessage=new We;imessageApiKey=``;imessageChatIds=[];imessageServerUrl=``;inFlightEffectiveProviderByGroup=/* @__PURE__ */ new Map;inFlightProviderRequestIds=/* @__PURE__ */ new Map;inFlightTriggerByGroup=/* @__PURE__ */ new Map;llamafileHost=`127.0.0.1`;llamafileMode=`cli`;llamafileOffline=!0;llamafilePort=8080;maxIterations=50;maxTokens=g;meshLlmHost=``;messageQueue=[];model=a().defaultModel;peerCompletedContexts=/* @__PURE__ */ new Set;peerjs=new Oe;peerjsMyAlias=``;peerjsMyPeerId=``;peerjsPeerAliases={};peerjsServerHost=``;peerjsServerPath=``;peerjsServerPort=0;peerjsServerSecure=!0;peerjsTrustedPeerIds=[];pendingScheduledTasks=/* @__PURE__ */ new Set;processing=!1;promptControllers=/* @__PURE__ */ new Map;provider=p;providerConfig=a();proxyUrl=`/proxy`;pushSubscriptionWarned=!1;rateLimitAutoAdapt=!0;rateLimitCallsPerMinute=0;reasoningEffort=`none`;roomChannel=new Ye;roomManager;router=null;scheduler=null;schedulerTriggeredGroups=/* @__PURE__ */ new Set;state=`idle`;streamingEnabled=!0;taskServerEnabled=!1;taskServerUrl=`/schedule`;telegram=new Xe;telegramBotToken=``;telegramChatIds=[];telegramUseProxy=!1;transformersProgressPollers=/* @__PURE__ */ new Map;triggerPattern=o(_);useProxy=!1;vmBashFullInternetAccess=!1;vmBootMode=`disabled`;vmStatus={ready:!1,booting:!1,bootAttempted:!1,error:null};webMcpEffectCleanup=null;webMcpRegistrationLock=Promise.resolve();webMcpToolsEnabled=!0;#e=null;#t=null;constructor(){this.roomManager=pt(this),this.initializeChannelRegistry()}clearProviderRequest(e){this.inFlightProviderRequestIds.delete(e)}createProviderRequestId(e){if(this.provider!==`llamafile`)return this.inFlightProviderRequestIds.delete(e),``;let t=`${e}:${Date.now().toString(36)}:${Math.random().toString(36).slice(2,10)}`;return this.inFlightProviderRequestIds.set(e,t),t}async ensureWorkerReady(){this.db&&!this.channelsInitialized&&(this.channelsInitialized=!0,await mt(this,this.db),this.browserChat.onDisplay(()=>{})),!this.agentWorker&&this.db&&await yt(this,this.db),this.db&&(j.load(this.db),H(this,this.db))}initializeChannelRegistry(){this.channelRegistry=new G,this.channelRegistry.register(`br:`,this.browserChat,{badge:`Browser`,autoTrigger:!0}),this.channelRegistry.register(`tg:`,this.telegram,{badge:`Telegram`,autoTrigger:!1}),this.channelRegistry.register(`im:`,this.imessage,{badge:`iMessage`,autoTrigger:!0}),this.channelRegistry.register(`peer:`,this.peerjs,{badge:`PeerJS`,autoTrigger:!1}),this.channelRegistry.register(`room:`,this.roomChannel,{badge:`Room`,autoTrigger:!1}),this.roomChannel.setManager(this.roomManager),this.roomChannel.setPeerJs(this.peerjs),this.peerjs.setRoomNotificationHandler((e,t,n)=>this.roomManager.handleNotification(e,t,n)),this.router=new nt(this.channelRegistry)}setState(e,t){this.state=e,this.events.emit(`state-change`,{state:e,groupId:t})}shutdown(){this.channelRegistry.stopAll(),this.scheduler?.stop();for(let e of this.transformersProgressPollers.keys())F(this,e);this.agentWorker?.terminate(),typeof this.webMcpEffectCleanup==`function`&&this.webMcpEffectCleanup(),Ae()}async ensureAllConnections(e={}){let t=e.force??!1;try{await this.ensureControlPlaneConnected({orchestrator:this,db:this.db||void 0,force:t})}catch(e){console.warn(`Error ensuring Control Plane connection:`,e)}try{Se(this,t)}catch(e){console.warn(`Error ensuring channel connections:`,e)}this.taskServerEnabled&&this.db&&(O.replayTaskSyncOutbox(this.db),O.loadTasks(this.db)),this.scheduler&&(this.scheduler.start(),this.scheduler.tick())}stopCurrentRequest(e=m){if(this.state!==`thinking`&&this.state!==`responding`)return;F(this,e);let t=this.inFlightProviderRequestIds.get(e)||``;this.clearProviderRequest(e),this.agentWorker?.postMessage({type:`cancel`,payload:{groupId:e}}),this.provider===`llamafile`&&t&&pe(t);let n=this.promptControllers.get(e);n&&(n.abort(),this.promptControllers.delete(e)),this.inFlightTriggerByGroup.delete(e),this.inFlightEffectiveProviderByGroup.delete(e),this.events.emit(`typing`,{groupId:e,typing:!1}),this.router?.setTyping(e,!1),this.setState(`idle`,e)}async getApiKey(){if(!this.#t)return null;let e=Date.now();if(this.#e&&this.#e.expiresAt>e)return this.#e.value;try{let t=await I(this.#t);return t===null?null:(this.#e={expiresAt:e+3e4,value:t},t)}catch(e){return console.error(`[Orchestrator] Failed to decrypt API key:`,e),null}}async getApiKeyForSpecificProvider(e,t){let n=await C(e,i(t));if(!n&&t===`openrouter`){let t=await C(e,h.API_KEY);t&&(n=t)}if(!n)return``;try{return await I(n)||``}catch(e){return console.error(`[Orchestrator] Failed to decrypt API key:`,e),``}}async handleCompactDone(e,t,n){await D(e,t);let r={channel:this.channelRegistry.getChannelType(t)??`browser`,content:`📝 **Context Compacted**\n\n${n}`,groupId:t,id:A(),isFromMe:!0,isTrigger:!1,sender:this.assistantName,timestamp:Date.now()};await w(e,r),this.events.emit(`context-compacted`,{groupId:t,summary:n}),this.events.emit(`typing`,{groupId:t,typing:!1}),this.setState(`idle`,t)}async init(){let e=await He();this.db=e,await T(),await Promise.all([ht(this,e),vt(this,e),_t(this,e),gt(this,e)]),await T();let t=typeof document<`u`&&!!document.getElementById(`shadow-claw-static-routing`),n=re(),r=n?.sidebar?.chatHidden,i=n?.sidebar?.tasksHidden,[a,o]=await Promise.all([C(e,h.SIDEBAR_CHAT_HIDDEN),C(e,h.SIDEBAR_TASKS_HIDDEN)]),s=a==null?!!r:N(a),c=o==null?!!i:N(o),l=s&&c;t?l||setTimeout(()=>{this.ensureWorkerReady()},15e3):l||await yt(this,e),l||(this.channelsInitialized=!0,mt(this,e).then(()=>{this.browserChat.onDisplay(()=>{})})),this.events.emit(`ready`,void 0);let u=typeof globalThis<`u`?globalThis.window:void 0;return t?l||setTimeout(()=>{j.load(e),H(this,e)},15e3):u&&typeof u.requestIdleCallback==`function`?l||u.requestIdleCallback(()=>{j.load(e),H(this,e)}):l||(await j.load(e),H(this,e)),e}async loadApiKeyForProvider(e,t){let n=await C(e,i(t));if(!n&&t===`openrouter`){let r=await C(e,h.API_KEY);r&&(n=r,await k(e,i(t),r))}this.#t=n||``,this.#e=null}async loadSecretConfig(e,t){let n=await C(e,t);if(!n)return``;try{return await I(n)||``}catch{let r=await L(n);return r&&await k(e,t,r),n}}async newSession(e,t=m){await D(e,t),this.events.emit(`session-reset`,{groupId:t})}async refreshContextUsage(e,t=m){let n=``;try{n=await ae(e,t,`MEMORY.md`)}catch{}let i=j.enabledTools,a=O.getPeerState(t)||void 0,o=Re(this.assistantName,n,i,j.systemPromptOverride,a,void 0,{groupId:t}),c=(await te(e)).find(e=>e.groupId===t),l=c?.pinnedModel??(c?.pinnedProvider?r(c.pinnedProvider)?.defaultModel??this.model:this.model),u=l;(c?.pinnedProvider??this.provider)===`prompt_api`&&(l===`browser-built-in`||!l)&&!P()&&(u=await C(this.db,h.PROMPT_API_FALLBACK_MODEL)||`onnx-community/Qwen3-0.6B-ONNX`);let d=typeof c?.pinnedMaxTokens==`number`&&Number.isFinite(c.pinnedMaxTokens)&&c.pinnedMaxTokens>0?Math.floor(c.pinnedMaxTokens):this.maxTokens,f=Math.max(1,Math.min(d,s(u))),p=Ne(u),g=U(o)+(i?.reduce((e,t)=>e+U(JSON.stringify(t)),0)??0),_=await Ie(t,200),v=Le(_,{contextLimit:p,systemPromptTokens:g,maxOutputTokens:f,skimTop:this.contextCompressionEnabled}),y=v.estimatedTokens+g;if(O.tokenUsage){let e=O.tokenUsage,t=(e.inputTokens||0)+(e.cacheReadTokens||0)+(e.outputTokens||0);y=Math.max(y,t)}this.events.emit(`context-usage`,{estimatedTokens:y,contextLimit:p,usagePercent:Math.min(100,Math.max(v.usagePercent,y/p*100)),truncatedCount:v.truncatedCount})}async restartCurrentRequest(e=m){if(this.state!==`thinking`&&this.state!==`responding`||!this.db)return!1;let t=this.inFlightTriggerByGroup.get(e);if(!t)return!1;this.stopCurrentRequest(e);let{invokeAgent:n}=await import(`./invoke-agent-C_geruwq.js`);return await n(this,this.db,e,t),!0}async routeRoomA2UIAction(e,t){let n=z(e),r=this.peerjs.myPeerId||this.peerjsMyPeerId,i=this.roomManager.getSurfaceOwner(t.surfaceId);if(!i||i===r){if(!this.db)return;await Y(this,this.db,{id:A(),groupId:e,sender:this.peerjsMyAlias||r||`you`,content:J(t),timestamp:Date.now(),channel:`room`,a2uiAction:t})}else this.roomManager.broadcastA2UIAction(n,t)}async saveSecretConfig(e,t,n){if(!n){await k(e,t,``);return}let r=await L(n);if(!r)throw Error(`Failed to encrypt secret config for ${t}`);await k(e,t,r)}async setApiKey(e,t){this.#t=await L(t),this.#e=null;let n=await L(t);if(!n)throw Error(`key failed to encrypt. config cannot set.`);await k(e,i(this.provider),n)}submitMessage(e,t=m){this.browserChat.submit(e,t)}};export{bt as Orchestrator};
@@ -60,4 +60,4 @@ slug: "shadow-claw-pages"
60
60
  <li><a href="https://deepwiki.com/xt-ml/shadow-claw">Deep Wiki</a></li>
61
61
  </ul>
62
62
  </article>`;function et(){let e=u(`/static-main/index.html`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}async function tt(e){let t=await m(e,l.MAIN_GROUP_INDEX_SUPPRESSED);return t===!0||t===`true`}async function nt(e,t){await g(e,l.MAIN_GROUP_INDEX_SUPPRESSED,t)}async function I(e,t=c,n){try{if(await y(e,t,`index.html`)){if(t===`br:main`)try{let r=await b(e,t,`index.html`);typeof r==`string`&&(r.includes(`<shadow-claw`)||r.includes(`data-shadow-claw-dsd`))&&await D(e,t,`index.html`,n??F)}catch{}return!0}if(t===`br:main`&&await tt(e))return!1;let r=n;if(r===void 0&&typeof fetch==`function`)try{let e=await fetch(et());if(e.ok){let t=await e.text();!t.includes(`<shadow-claw`)&&!t.includes(`data-shadow-claw-dsd`)&&(r=t)}}catch{}return r??=F,await D(e,t,`index.html`,r),!0}catch(e){return console.warn(`Failed to ensure main workspace Memory:`,e),!1}}const L='---\ntitle: "Agent Memory"\ncreated: "1970-01-01T00:00:00Z"\nupdated: "1970-01-01T00:00:00Z"\nslug: "agent-memory"\n---\n\n## Memory\n\n### Workspace Layout & Skills Conventions\n\n- **Skills**: `.agents/skills/<skill-name>/SKILL.md` (canonical flat layout; legacy `.agents/skills/main/` supported for backward-compatible reads)\n- **Declarative Tools**: `.agents/tools/<tool-name>.json` (canonical flat layout; legacy `.agents/tools/main/` supported for backward-compatible reads)\n- **Skill Format**: Markdown file with YAML frontmatter AND a Markdown body (frontmatter is metadata only; always include a `# <Skill Title>` heading and human-readable description in the Markdown body so it renders in document previews):\n\n ```yaml\n ---\n name: <skill-name>\n description: <clear summary for model and slash command>\n user-invocable: true\n metadata:\n allowed-tools: <tool1> <tool2>\n execution:\n type: tools\n tools:\n - name: <tool1>\n input: { ... }\n - name: <tool2>\n input: { "$pipe": "prev" }\n ---\n # <Skill Title>\n\n <Overview and description of what the skill does, parameters, and usage instructions.>\n ```\n\n- **Declarative Tool Format**: JSON with `"name"`, `"description"`, `"executor": "javascript"`, `"inputSchema"`, and `"code"`.\n- **Open Agent Skills & Discovery**: Install community skills from [skills.sh](https://skills.sh) via `npx shadow-claw skills add <owner/repo>` (or `npx skills add`), search via `npx shadow-claw skills find <term>`, and publish RFC v0.2.0 discovery indexes via `npx shadow-claw skills:index` (`.well-known/agent-skills/index.json`).\n- **Authoring**: Use `create_directory` before writing new directories, then `write_file`.',rt=`MEMORY.md`;function it(){let e=u(`/static-main/MEMORY.md`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}async function R(e){let t=await m(e,l.MAIN_GROUP_README_SUPPRESSED);return t===!0||t===`true`}async function z(e,t){await g(e,l.MAIN_GROUP_README_SUPPRESSED,t)}async function B(e,t=c,n){try{if(await y(e,t,`MEMORY.md`)){if(t===`br:main`)try{let r=await b(e,t,rt);typeof r==`string`&&(r.includes(`<shadow-claw`)||r.includes(`data-shadow-claw-dsd`))&&await D(e,t,rt,n??L)}catch{}return!0}if(t===`br:main`&&await R(e))return!1;let r=n;if(r===void 0&&typeof fetch==`function`)try{let e=await fetch(it());if(e.ok){let t=await e.text();!t.includes(`<shadow-claw`)&&!t.includes(`data-shadow-claw-dsd`)&&(r=t)}}catch{}return r??=L,await D(e,t,rt,r),!0}catch(e){return console.warn(`Failed to ensure main workspace Memory:`,e),!1}}async function at(e,t,n=`.`){for(let r=0;r<2;r++)try{let r=await T(e,t);if(n&&n!==`.`){let e=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean);for(let t of e){let e=await r.getDirectoryHandle(t);if(typeof r.isSameEntry==`function`&&await r.isSameEntry(e))throw Error(`Directory navigation stuck at "${r.name}" for segment "${t}" — the stored directory handle may be stale.`);r=e}}let i=[];for await(let[e,t]of r.entries())i.push(t.kind===`directory`?`${e}/`:e);return i.sort()}catch(e){if(r===0&&te(e)){w();continue}throw e}return[]}function ot(e){if(!e||typeof e!=`object`)return!1;let t=globalThis.FileSystemDirectoryHandle;return t!==void 0&&e instanceof t||typeof e.getDirectoryHandle==`function`&&typeof e.getFileHandle==`function`&&typeof e.requestPermission==`function`}async function st(e){let t=await m(e,l.STORAGE_HANDLE);return!ot(t)||await t.requestPermission({mode:`readwrite`})===`granted`}function V(e){let t=s();return t?`shadowclaw:${t}:${e}`:e}function ct(e){if(typeof localStorage>`u`)return null;let t=V(e);try{let n=localStorage.getItem(t);if(n!==null)return n;if(t===e)return null;let r=localStorage.getItem(e);if(r!==null)return localStorage.setItem(t,r),r}catch(e){console.warn(`Unable to read from localStorage:`,e)}return null}function H(e,t){if(typeof localStorage>`u`)return;let n=V(e);try{localStorage.setItem(n,t)}catch(e){console.warn(`Unable to write to localStorage:`,e)}}function lt(e){if(typeof localStorage>`u`)return;let t=V(e);try{localStorage.removeItem(t)}catch(e){console.warn(`Unable to remove from localStorage:`,e)}}async function U(e,t){let n=await T(e,t);for await(let[e]of n.entries())await n.removeEntry(e,{recursive:!0})}async function W(e,t,n){let r=await T(e,t),{dirs:i,filename:a}=ne(n.replace(/\/$/,``)),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a,{recursive:!0})}function G(e,t){return`${e}:${t}`}async function ut(e){let t=await m(e,l.SUPPRESSED_PAGES_LIST);if(!t||typeof t!=`string`)return[];try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return[]}async function dt(e,t,n){let r=await ut(e),i=G(t,n);return r.some(e=>G(e.groupId,e.path)===i)}async function ft(e,t,n){let r=await ut(e),i=G(t,n);if(!r.some(e=>G(e.groupId,e.path)===i)){let i=[...r,{groupId:t,path:n}];await g(e,l.SUPPRESSED_PAGES_LIST,JSON.stringify(i))}}async function pt(e,t,n){let r=await ut(e),i=G(t,n),a=r.filter(e=>G(e.groupId,e.path)!==i);a.length!==r.length&&await g(e,l.SUPPRESSED_PAGES_LIST,JSON.stringify(a))}function K(e){return Array.from(new Set(e.map(e=>e.trim()).filter(Boolean)))}function mt(e){let t=e.trim().replace(/\\/g,`/`);return t===`/`||/^\/+$/.test(t)?`/`:t.replace(/^\/+/,``).replace(/\/+$/,``)}const ht=/\.(md|markdown|html|xhtml|txt)$/i;function q(e){return e===`/`?`/`:e.replace(ht,``)}function gt(e){let t=e.trim().replace(/\\/g,`/`);return t===`/`||/^\/+$/.test(t)?`/`:t.replace(/^\/+/,``).replace(/\/+$/,``)}function _t(e){return e?e.replace(/^br:/i,``).replace(/^br-/i,``).trim():`main`}function J(e,t){let n=gt(t);if(!n)return;e.add(n);let r=q(n);r&&r!==n&&e.add(r)}function vt(e,t,n){let r=/* @__PURE__ */ new Set;if(!e)return r;let i=_t(t);if(e===`/`){if(r.add(`/`),J(r,`index.html`),n){let e=mt(n);e&&e!==`/`&&J(r,`${e}/index.html`)}return J(r,`pages/index.html`),J(r,`pages/${i}/index.html`),J(r,`${i}/index.html`),r}if(J(r,e),n){let t=mt(n);t&&t!==`/`&&J(r,`${t}/${e}`)}if(e.startsWith(`pages/`)){let t=e.slice(6);J(r,t),t.startsWith(`${i}/`)?J(r,t.slice(`${i}/`.length)):J(r,t.replace(/^[^/]+\//,``))}else J(r,`pages/${e}`),J(r,`pages/${i}/${e}`),J(r,`${i}/${e}`);for(let e of Array.from(r)){let t=q(e);if(e===`index.html`||t===`index`){r.add(`/`);break}}return r}function yt(e,t){let n=t.toLowerCase(),r=q(t).toLowerCase(),i=n===r?[n]:[n,r];for(let t of e){let e=t.toLowerCase(),n=q(e);for(let t of i)if(t&&(e===t||n===t||t!==`/`&&(e.startsWith(`${t}/`)||n.startsWith(`${t}/`)||e.endsWith(`/${t}`)||n.endsWith(`/${t}`)||e.includes(`/${t}/`)||n.includes(`/${t}/`))))return!0}return!1}function bt(e,t){for(let n of t){let t=mt(n);if(t&&yt(e,t))return!0}return!1}function xt(e,t,n,r){if(!e||typeof e!=`string`)return!1;let i=gt(e);if(!i)return!1;let a=[],o=[],s,c;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t,n=e.allowList??e.allowlist??[],r=e.denyList??e.denylist??[];a=K(Array.from(n||[])),o=K(Array.from(r||[])),s=e.groupId,c=e.basePathPrefix}else a=K(Array.from(t||[])),o=K(Array.from(n||[])),s=r?.groupId,c=r?.basePathPrefix;let l=vt(i,s,c);return o.length>0&&bt(l,o)?!1:a.length>0?bt(l,a):!0}function St(e=c){return e===`br:main`?l.STATIC_MAIN_SITE_SEEDED:`${l.STATIC_MAIN_SITE_SEEDED}:${e}`}async function Ct(e,t=c){let n=St(t),r=await m(e,n);return r===!0||r===`true`}async function wt(e,t=c,n=!0){let r=St(t);await g(e,r,n)}function Tt(){let e=u(`/static-main-manifest.json`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}function Et(e){let t=e.replace(/^\/+/,``),n=`static-main`;if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);typeof t?.pages?.baseUrl==`string`&&(n=t.pages.baseUrl.replace(/^\/+/,``).replace(/\/+$/,``))}}catch{}let r=u(n?`/${n}/${t}`:`/${t}`);if(typeof window<`u`&&window.location?.origin)try{return new URL(r,window.location.origin).toString()}catch{return r}return r}async function Dt(){if(typeof fetch!=`function`)return null;try{let e=Tt(),t=await fetch(e);if(t.ok){if((t.headers?.get?.(`content-type`)||``).includes(`text/html`))return null;let e=await t.json();if(e&&Array.isArray(e.pages))return e}}catch{}return null}async function Ot(e){if(typeof fetch!=`function`)return null;try{let t=Et(e),n=await fetch(t);if(n.ok){let t=n.headers?.get?.(`content-type`)||``;if((e.endsWith(`.md`)||e.endsWith(`.markdown`)||e.endsWith(`.json`))&&t.includes(`text/html`))return null;let r=await n.text();return r.includes(`<shadow-claw`)||r.includes(`data-shadow-claw-dsd`)?null:r}}catch{}return null}function kt(e){if(typeof document>`u`)return null;let t=t=>{if(!t||!(t instanceof HTMLElement))return!1;if(!e)return!0;let n=t.getAttribute(`data-initial-path`)?.trim();return!n||n===e},n=document.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(n))return n;let r=document.querySelector(`shadow-claw`)?.shadowRoot,i=(r?.querySelector(`shadow-claw-pages`)?.shadowRoot)?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`)||r?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(i))return i;let a=document.querySelectorAll(`template`);for(let n of Array.from(a)){let r=n.content?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(r))return r;let i=n.content?.querySelectorAll(`template`);if(i)for(let n of Array.from(i)){let r=n.content?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(r))return r}}return null}function Y(e=`index.html`){let t=kt(e);if(!t)return null;let n=t.getAttribute(`data-initial-path`)?.trim();if(n&&n!==e)return null;let r=t.querySelector(`[data-markdown-frontmatter]`),i=null;if(r){let e=r.getAttribute(`data-frontmatter`);if(e)try{i=JSON.parse(e)}catch{}}let a=t.cloneNode(!0),o=a.querySelector(`[data-markdown-frontmatter]`);o&&o.remove();let s=a.innerHTML.trim();if(!s&&!i)return null;if(i&&Object.keys(i).length>0){let e=[`---`];for(let[t,n]of Object.entries(i))typeof n==`string`?e.push(`${t}: ${JSON.stringify(n)}`):typeof n==`number`||typeof n==`boolean`?e.push(`${t}: ${n}`):e.push(`${t}: ${JSON.stringify(n)}`);return e.push(`---`,``),`${e.join(`
63
- `)}\n${s}`}return s}async function At(e={}){let t=()=>{let e=null;if(typeof document<`u`){let t=document.getElementById(`shadow-claw-static-manifest`);if(t&&t.textContent)try{let n=JSON.parse(t.textContent);n&&Array.isArray(n.pages)&&(e={...n,pages:[...n.pages]})}catch(e){console.warn(`Failed to parse embedded static main manifest:`,e)}let n=document.querySelectorAll(`script[type="text/markdown"][data-shadow-claw-page]`);if(n.length>0){e||={pages:[]};for(let t of Array.from(n)){let n=t.getAttribute(`data-shadow-claw-page`)?.trim();if(n){let r=t.textContent||``;r=ie(r),!r.trim()&&/^memory\.(md|markdown)$/iu.test(n)&&(r=L),!r.trim()&&(n===`index.html`||/^index\.(html?|xhtml)$/iu.test(n))&&(r=Y(n)??F);let i=e.pages.findIndex(e=>e.displayPath===n);i>=0?e.pages[i].content=r:e.pages.push({displayPath:n,content:r})}}}let r=document.getElementById(`shadow-claw-site-config`);if(r?.textContent)try{let t=JSON.parse(r.textContent);if(Array.isArray(t?.pages?.files)){e||={pages:[]};for(let n of t.pages.files)if(typeof n==`string`&&n.trim()){let t=n.trim(),r=``;/^memory\.(md|markdown)$/iu.test(t)?r=L:(t===`index.html`||/^index\.(html?|xhtml)$/iu.test(t))&&(r=Y(t)??F),e.pages.some(e=>e.displayPath===t)||e.pages.push({displayPath:t,content:r})}}}catch{}let i=kt();if(i){e||={pages:[]};let t=i.getAttribute(`data-initial-path`)?.trim()||`index.html`;if(!e.pages.some(e=>e.displayPath===t)){let n=Y(t)??F;e.pages.push({displayPath:t,content:n})}e.pages.some(e=>/^memory\.(md|markdown)$/iu.test(e.displayPath))||e.pages.push({displayPath:`MEMORY.md`,content:L})}}return e};if(e.preferEmbedded!==!1){let e=t();if(e&&e.pages.length>0)return e}if(e.fetchFallback!==!1){let e=await Dt();if(e&&e.pages.length>0)return e}if(e.preferEmbedded===!1){let e=t();if(e&&e.pages.length>0)return e}return{pages:[{displayPath:`index.html`,content:F},{displayPath:`MEMORY.md`,content:L}]}}async function jt(e){if(typeof document<`u`){let t=document.getElementById(`shadow-claw-static-manifest`);if(t&&t.textContent)try{let n=JSON.parse(t.textContent);if(n&&Array.isArray(n.pages)){let t=n.pages.find(t=>t.displayPath===e);if(t&&typeof t.content==`string`&&t.content.trim())return t.content}}catch{}let n=document.querySelectorAll(`script[type="text/markdown"][data-shadow-claw-page]`);for(let t of Array.from(n))if(t.getAttribute(`data-shadow-claw-page`)?.trim()===e){let e=t.textContent||``;if(e.trim())return e}let r=Y(e);if(typeof r==`string`&&r.trim())return r;if(/^memory\.(md|markdown)$/iu.test(e))return L;if(e===`index.html`||/^index\.(html?|xhtml)$/iu.test(e))return F}let t=await Ot(e);if(typeof t==`string`)return t;let n=await Dt();if(n&&Array.isArray(n.pages)){let t=n.pages.find(t=>t.displayPath===e);if(t&&typeof t.content==`string`)return t.content}return null}async function Mt(e,t,n=[]){for(let[r,i]of Object.entries(t))if(r===`purgePreRenderedStaticPages`&&i===!0){if(n.length>0){let t=n[0],r=n.slice(1).join(`/`);try{r?await W(e,t,r):await U(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await Mt(e,i,[...n,r])}function Nt(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t?.pages?.sortOrder===`desc`)return`desc`;if(t?.pages?.sortOrder===`asc`)return`asc`}}catch{}return`desc`}function Pt(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent)?.pages?.defaultPinnedPage;if(typeof t==`string`&&t.trim().length>0)return t.trim()}}catch{}return null}function Ft(){let e=`ShadowClaw`,t,n;if(typeof document<`u`){try{let r=document.getElementById(`shadow-claw-site-config`);if(r?.textContent){let i=JSON.parse(r.textContent);i?.site?.title&&(e=String(i.site.title).trim()),(i?.site?.titleSeparator??i?.site?.sep)&&(t=String(i.site.titleSeparator??i.site.sep)),i?.site?.titleTemplate&&(n=String(i.site.titleTemplate))}}catch{}if(e===`ShadowClaw`&&document.title){let t=document.title.split(/\s*[-|—•·]\s*/),n=t[t.length-1]?.trim();n&&(e=n)}}return{siteTitle:e,separator:t,titleTemplate:n}}function It(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);return{allowList:K(t?.pages?.allowList??t?.pages?.allowlist??t?.allowList??t?.allowlist??[]),denyList:K(t?.pages?.denyList??t?.pages?.denylist??t?.denyList??t?.denylist??[])}}}catch{}return{allowList:[],denyList:[]}}function Lt(e,t){let n=t??Nt();return[...e].sort((e,t)=>{let r=e.path,i=t.path,a=r.split(`/`).pop()||``,o=i.split(`/`).pop()||``,s=/^index\.(html?|xhtml)$/iu.test(a),c=/^index\.(html?|xhtml)$/iu.test(o);if(s&&!c)return-1;if(!s&&c)return 1;let l=/^memory\.(md|markdown)$/iu.test(a),u=/^memory\.(md|markdown)$/iu.test(o);return l&&!u?1:!l&&u?-1:n===`asc`?r.localeCompare(i,void 0,{numeric:!0,sensitivity:`base`}):i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})})}async function Rt(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(ct(n)===i)return!0}catch{}try{if(await m(e,r)===i){try{H(n,i)}catch{}return!0}await g(e,r,i);try{H(n,i)}catch{}}catch{try{H(n,i)}catch{}}return!1}async function zt(e,t=c,n=[],r={}){await I(e,t);let i=await At(r),a=!1;i.preRenderedStaticPages&&(await Rt(e,i.purgeId)||(a=!0,await Mt(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await Rt(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await W(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}try{await W(e,t,`.agents/tools/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}}for(let n of i.pages)if(n.content?.includes(`slug: "shadow-claw--purge-pages"`)){!a&&!await Rt(e,i.purgeId)&&(a=!0,await U(e,t));break}let s=t===`br:main`&&await R(e),l=new Set(i.pages.map(e=>G(t,e.displayPath))),u=a?n.filter(e=>e.groupId!==t||l.has(G(e.groupId,e.path))):[...n],{allowList:d,denyList:f}=It(),p=0;for(let n of i.pages)if(p++,p%5==0&&await new Promise(e=>setTimeout(e,0)),!n.content?.includes(`slug: "shadow-claw--purge-pages"`)&&xt(n.displayPath,{allowList:d,denyList:f,groupId:t})){if(/^memory\.(md|markdown)$/iu.test(n.displayPath)){if(s)continue;let r=typeof n.content==`string`&&n.content.trim().length>0&&n.content!==L?n.content:void 0;if(r===void 0?await B(e,t):await B(e,t,r)){let e=G(t,n.displayPath);u.some(t=>G(t.groupId,t.path)===e)||u.push({groupId:t,path:n.displayPath})}}else if(!await dt(e,t,n.displayPath))try{if(!await y(e,t,n.displayPath)){let r=n.content;(typeof r!=`string`||!r.trim())&&(r=n.displayPath===`index.html`?Y(`index.html`)??F:await Ot(n.displayPath)??``),await D(e,t,n.displayPath,r)}let r=G(t,n.displayPath);u.some(e=>G(e.groupId,e.path)===r)||u.push({groupId:t,path:n.displayPath})}catch(e){console.warn(`Failed to seed static page file ${n.displayPath}:`,e)}}if(t===`br:main`){for(let n of i.skills||[]){let r=`.agents/skills/main/${n.displayPath}`;try{await y(e,t,r)||await D(e,t,r,n.content)}catch(e){console.warn(`Failed to seed skill file ${r}:`,e)}}for(let n of i.tools||[]){let r=`.agents/tools/main/${n.displayPath}`;try{(o||!await y(e,t,r))&&await D(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let m=typeof document<`u`&&(document.getElementById(`shadow-claw-static-manifest`)!==null||document.querySelector(`script[type="text/markdown"][data-shadow-claw-page]`)!==null||kt()!==null);r.preferEmbedded!==!1&&m||await wt(e,t,!0);let h=u.filter(e=>xt(e.path,{allowList:d,denyList:f,groupId:e.groupId}));return Object.defineProperty(h,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(h,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),Lt(h)}var Bt=class{_events;_handlers=[];_runs=/* @__PURE__ */ new Map;constructor(e){this._events=e}start(){this._listen(`streaming-start`,this._onStreamingStart),this._listen(`streaming-chunk`,this._onStreamingChunk),this._listen(`streaming-end`,this._onStreamingEnd),this._listen(`streaming-done`,this._onStreamingDone),this._listen(`streaming-error`,this._onStreamingError),this._listen(`tool-activity`,this._onToolActivity)}stop(){for(let{event:e,handler:t}of this._handlers)this._events.off(e,t);this._handlers=[],this._runs.clear()}_emit(e,t){window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{groupId:e,event:t}}))}_listen(e,t){this._events.on(e,t),this._handlers.push({event:e,handler:t})}_onStreamingChunk=({groupId:e,text:t})=>{let n=this._runs.get(e);n&&n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_CONTENT`,messageId:n.messageId,delta:t,timestamp:Date.now()})};_onStreamingDone=({groupId:e})=>{let t=this._runs.get(e);t&&(t.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_FINISHED`,threadId:t.threadId,runId:t.runId,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingEnd=({groupId:e})=>{let t=this._runs.get(e);t&&t.messageId&&(this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),t.messageId=null)};_onStreamingError=({groupId:e,error:t})=>{let n=this._runs.get(e);n&&(n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:n.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_ERROR`,message:t||`Unknown streaming error`,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingStart=({groupId:e})=>{let t=_(),n=e,r=_();this._runs.set(e,{runId:t,threadId:n,messageId:r,activeToolCallIds:/* @__PURE__ */ new Set}),this._emit(e,{type:`RUN_STARTED`,threadId:n,runId:t,timestamp:Date.now()}),this._emit(e,{type:`TEXT_MESSAGE_START`,messageId:r,role:`assistant`,timestamp:Date.now()})};_onToolActivity=({groupId:e,tool:t,status:n})=>{let r=this._runs.get(e);if(r){if(n===`running`){let n=_();r.activeToolCallIds.add(n),this._emit(e,{type:`TOOL_CALL_START`,toolCallId:n,toolCallName:t,timestamp:Date.now()}),r._lastToolCallId=n}else if(n===`done`||n===`error`){let t=r._lastToolCallId;t&&(r.activeToolCallIds.delete(t),this._emit(e,{type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()}))}}}};function Vt(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)Ht(n,e);return n}function Ht(e,t){let{op:n,path:r,value:i}=t;if(!r||!r.startsWith(`/`))return;let a=r.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),o=a.pop();if(o===void 0)return;let s=e;for(let e of a){if(typeof s!=`object`||!s)return;s=s[e]}typeof s==`object`&&s&&(Array.isArray(s)?Ut(s,o,n,i):Wt(s,o,n,i))}function Ut(e,t,n,r){if(n===`add`){if(t===`-`)e.push(r);else{let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<=e.length&&e.splice(n,0,r)}}else if(n===`replace`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&(e[n]=r)}else if(n===`remove`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&e.splice(n,1)}}function Wt(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}function Gt(e){if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t))return K(t.map(e=>String(e)))}catch{}return K(e.split(`,`))}let X=/* @__PURE__ */ new Map;function Z(e){if(typeof document>`u`)return null;let t=`shadow-claw-site-config`;if(e){let n=e.getAttribute(`config`)?.trim();n&&(t=n.replace(/^#/,``))}let n=document.getElementById(t);if(!n?.textContent)return X.delete(t),null;let r=X.get(t);if(r&&r.rawText===n.textContent)return r.config;try{let e=JSON.parse(n.textContent);if(!e||typeof e!=`object`)return X.delete(t),null;let r={...e};return X.set(t,{rawText:n.textContent,config:r}),r}catch(e){return console.warn(`[ShadowClaw] Failed to parse site configuration from #${t}:`,e),null}}var Kt=/* @__PURE__ */ e({OrchestratorStore:()=>Qt,accumulateTokenUsage:()=>Zt,orchestratorStore:()=>$t});function qt(e){if(e){if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:void 0}catch{return}}}function Jt(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return typeof e==`number`&&e===1}function Yt(e){return!!e}async function Q(e,t,n,r){if(!Yt(r))return!0;if(!e.schedule)return await $(e.id,t,n,r)!==`failed`;try{let r=t.replace(/\/$/,``);return(await fetch(`${r}/tasks`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,subscriberId:n})})).ok}catch{return!1}}async function $(e,t,n,r){if(!Yt(r))return`missing`;try{let r=t.replace(/\/$/,``),i=`subscriberId=${encodeURIComponent(n)}`,a=await fetch(`${r}/tasks/${encodeURIComponent(e)}?${i}`,{method:`DELETE`});return a.ok?`deleted`:a.status===404||a.status===405?`missing`:`failed`}catch{return`failed`}}async function Xt(e,t,n,r){if(!Yt(r))return null;try{let r=t.replace(/\/$/,``),i=await fetch(`${r}/tasks?groupId=${encodeURIComponent(e)}&subscriberId=${encodeURIComponent(n)}`,{method:`GET`});if(!i.ok||typeof i.json!=`function`)return null;let a=await i.json();return Array.isArray(a)?a.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.schedule==`string`&&typeof e.prompt==`string`).map(t=>({id:t.id,groupId:t.group_id||t.groupId||e,schedule:t.schedule,type:t.type,prompt:t.prompt,tools:qt(t.tools),channel:typeof t.channel==`string`?t.channel:void 0,enabled:t.enabled===!0||t.enabled===1,lastRun:typeof t.lastRun==`number`?t.lastRun:typeof t.last_run==`number`?t.last_run:null,createdAt:typeof t.createdAt==`number`?t.createdAt:typeof t.created_at==`number`?t.created_at:Date.now(),name:typeof t.name==`string`?t.name:void 0,order:typeof t.order==`number`?t.order:typeof t.task_order==`number`?t.task_order:void 0})):null}catch{return null}}function Zt(e,t){let n=(e?.inputTokens??0)+(t.inputTokens??0),r=(e?.outputTokens??0)+(t.outputTokens??0),i=(e?.cacheReadTokens??0)+(t.cacheReadTokens??0),a=(e?.cacheCreationTokens??0)+(t.cacheCreationTokens??0);return{groupId:t.groupId||e?.groupId||``,inputTokens:n,outputTokens:r,cacheReadTokens:i,cacheCreationTokens:a,totalTokens:n+r+i+a,contextLimit:t.contextLimit||e?.contextLimit||0}}var Qt=class e{static DEFAULT_PAGE_PATH=`MEMORY.md`;orchestrator;_activeGroupId;_activePage;_activePinnedPage;_defaultPinnedPage;_activityLog;_activityLogSessionStartedAtByGroup;_aguiAdapter;_aguiEvent;_contextUsage;_currentPath;_db;_error;_files;_gitProxyUrl;_groups;_hadPersistedActivePage;_initResolve;_isTyping;_lastOrchestratorDisplayState=`idle`;_messages;_modelDownloadProgress;_onlineReplayHandler;_pages;_pagesAllowList;_pagesDenyList;_peerStateByGroup;_proxyUrl;_ready;_remoteAgentStatusByGroup;_remoteAgentTypingByGroup;_replayingTaskSyncOutbox;_subscriberId;_sidebarDefaultPage;_state;_storageStatus;_streamingText;_tasks;_taskSyncOutbox;_tokenUsage;_tokenUsageAccumulator=null;_toolActivity;_unreadGroupIds;_useProxy;_vmBashFullInternetAccess;_whenInitialized;_whenReady;_readyResolve;constructor(){this._messages=new h.State([]),this._isTyping=new h.State(!1),this._storageStatus=new h.State(null),this._toolActivity=new h.State(null),this._modelDownloadProgress=new h.State(null),this._activityLog=new h.State([]),this._state=new h.State(`idle`),this._tokenUsage=new h.State(null),this._error=new h.State(null),this._activeGroupId=new h.State(c),this._ready=new h.State(!1),this._tasks=new h.State([]),this._files=new h.State([]),this._currentPath=new h.State(`.`),this._groups=new h.State([]),this._unreadGroupIds=new h.State(/* @__PURE__ */ new Set),this._streamingText=new h.State(null),this._aguiEvent=new h.State(null),this._contextUsage=new h.State(null),this._useProxy=new h.State(!1),this._proxyUrl=new h.State(`/proxy`),this._gitProxyUrl=new h.State(`/git-proxy`),this._vmBashFullInternetAccess=new h.State(!1),this._activePage=new h.State(`pages`);let e=Z()?.sidebar?.defaultPage,t=e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`;this._sidebarDefaultPage=new h.State(t),this._pages=new h.State([]),this._pagesAllowList=new h.State([]),this._pagesDenyList=new h.State([]),this._activePinnedPage=new h.State(null),this._defaultPinnedPage=new h.State(null),this._remoteAgentStatusByGroup=new h.State(/* @__PURE__ */ new Map),this._remoteAgentTypingByGroup=new h.State(/* @__PURE__ */ new Map),this._peerStateByGroup=new h.State(/* @__PURE__ */ new Map),this._hadPersistedActivePage=!1,this._initResolve=null,this._whenInitialized=new Promise(e=>{this._initResolve=e}),this._readyResolve=null,this._whenReady=new Promise(e=>{this._readyResolve=e}),this.orchestrator=null,this._db=null,this._activityLogSessionStartedAtByGroup=/* @__PURE__ */ new Map,this._taskSyncOutbox=[],this._replayingTaskSyncOutbox=!1,this._subscriberId=null,this._onlineReplayHandler=null,this._aguiAdapter=null}get activeGroupId(){return this._activeGroupId.get()}get activePage(){return this._activePage.get()}get activePinnedPage(){return this._activePinnedPage.get()}get defaultPinnedPage(){return this._defaultPinnedPage.get()}get pagesAllowList(){return this._pagesAllowList.get()}get pagesDenyList(){return this._pagesDenyList.get()}isPageAllowed(e,t){return xt(e,{allowList:this._pagesAllowList.get(),denyList:this._pagesDenyList.get(),groupId:t??this._activeGroupId.get()})}get effectiveDefaultPage(){let e=this._defaultPinnedPage.get();return e&&this.isPageAllowed(e.path,e.groupId)?e:this._pages.get()[0]||null}get activityLog(){return this._activityLog.get()}get taskServerEnabled(){return this.orchestrator?.taskServerEnabled??!1}get aguiEvent(){return this._aguiEvent.get()}clearError(){this._error.set(null),this._state.get()===`error`&&this._state.set(`idle`)}get contextUsage(){return this._contextUsage.get()}get tokenUsageAccumulator(){return this._tokenUsageAccumulator}get currentPath(){return this._currentPath.get()}get error(){return this._error.get()}get files(){return this._files.get()}getPeerState(e){return this._peerStateByGroup.get().get(e)||null}getRemoteAgentStatus(e){return this._remoteAgentStatusByGroup.get().get(e)||`idle`}getState(){return{messages:this.messages,isTyping:this.isTyping,toolActivity:this.toolActivity,activityLog:this.activityLog,state:this.state,tokenUsage:this.tokenUsage,modelDownloadProgress:this.modelDownloadProgress,error:this.error,activeGroupId:this.activeGroupId,pages:this.pages,ready:this.ready,files:this.files,currentPath:this.currentPath,streamingText:this.streamingText,contextUsage:this.contextUsage}}getTasksForBackup(){return this._tasks.get()}get gitProxyUrl(){return this._gitProxyUrl.get()}get groups(){return this._groups.get()}get hadPersistedActivePage(){return this._hadPersistedActivePage}isRemoteAgentTyping(e){return this._remoteAgentTypingByGroup.get().get(e)||!1}get isTyping(){return this._isTyping.get()}get messages(){return this._messages.get()}get modelDownloadProgress(){return this._modelDownloadProgress.get()}get pages(){return this._pages.get()}get proxyUrl(){return this._proxyUrl.get()}get ready(){return this._ready.get()}sendMessage(e,t=[],n){n===void 0?this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t):this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t,n)}async sendFileToPeer(e,t=this._activeGroupId.get(),n){let r=t.startsWith(`peer:`),i=t.startsWith(`room:`);if(!r&&!i){let e=`Can only send files to peers in a peer or room conversation.`;throw O(e,4500),Error(e)}let a=this.orchestrator?.router;if(!a){let e=`Network router is not initialized.`;throw O(e,4500),Error(e)}let o=n?.fileName||e.split(`/`).pop()||e,s=n?.mimeType||`application/octet-stream`,c=n?.size||0;a.setTyping(t,!0);try{let n={path:e,fileName:o,mimeType:s,size:c};if(await a.send(t,``,[n]),this._db){let e={id:_(),groupId:t,sender:`You`,content:``,timestamp:Date.now(),channel:i?`room`:`peerjs`,attachments:[n],isFromMe:!1,isTrigger:!1};await N(this._db,e),this.orchestrator?.events.emit(`message`,e)}ae(`Sent ${o} to ${i?`room peers`:`peer`}`,2500)}catch(e){let t=e instanceof Error?e.message:String(e);throw console.error(`sendFileToPeer error:`,e),O(`Failed to send file: ${t}`,6e3),e}finally{a.setTyping(t,!1)}}setActiveGroup(e,t,n=this._activePage.get()===`chat`){if(this._activeGroupId.set(t),this._messages.set([]),this._activityLog.set([]),this._error.set(null),this._isTyping.set(!1),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._currentPath.set(`.`),n){let e=new Set(this._unreadGroupIds.get());e.delete(t)&&this._unreadGroupIds.set(e)}this.loadHistory(),this.loadTasks(e),this.loadFiles(e)}setReady(e=!0){this._ready.set(e),e&&this._readyResolve&&this._readyResolve()}setRemoteAgentStatus(e,t){let n=this._remoteAgentStatusByGroup.get(),r=new Map(n);r.set(e,t),this._remoteAgentStatusByGroup.set(r)}setRemoteAgentTyping(e,t){let n=this._remoteAgentTypingByGroup.get(),r=new Map(n);t?r.set(e,!0):r.delete(e),this._remoteAgentTypingByGroup.set(r)}get sidebarDefaultPage(){return this._sidebarDefaultPage.get()}get state(){return this._state.get()}stopCurrentRequest(){this.orchestrator?.stopCurrentRequest?.(this._activeGroupId.get())}get storageStatus(){return this._storageStatus.get()}get streamingText(){return this._streamingText.get()}syncHostWorkspaceToVM(){fe(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){pe(this.orchestrator,this._activeGroupId.get())}get tasks(){return this._tasks.get()}get tokenUsage(){return this._tokenUsage.get()}get toolActivity(){return this._toolActivity.get()}get unreadGroupIds(){return this._unreadGroupIds.get()}get useProxy(){return this._useProxy.get()}get vmBashFullInternetAccess(){return this._vmBashFullInternetAccess.get()}get whenInitialized(){return this._whenInitialized}async resetSiteConfigSeed(e){await g(e,l.SITE_CONFIG_SEEDED,!1)}get whenReady(){return this._whenReady}async addPage(e,t,n=this._activeGroupId.get()){let r=n===`br:main`?this.normalizePagePath(t):t.trim();if(!r||!this.isPageAllowed(r,n))return;let i=this._pages.get();i.some(e=>e.path===r&&e.groupId===n)||(this.setPages([...i,{groupId:n,path:r}]),await pt(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await z(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await v(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r)await $(t.id,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)===`failed`?(console.warn(`Failed to delete task "${t.id}" from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t.id,queuedAt:Date.now()})):await Le(e,t.id);await this.loadTasks(e)}async cloneConversation(e,t){let n=await Ke(e,t);if(!n)return null;await Pe(e,t,n.groupId),await Fe(e,t,n.groupId);try{let r=await b(e,t,`MEMORY.md`);r&&await D(e,n.groupId,`MEMORY.md`,r)}catch{}try{await Qe(e,t,n.groupId,`attachments`)}catch{}return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async compactContext(e){if(!this.orchestrator)return;let{compactContext:t}=await import(`./compact-context-fOTqwKF6.js`);return t(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await Ve(e,t);return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await We(e,t),await Ne(e,t),await this.loadGroups(e),this._activeGroupId.get()===t)){let t=this._groups.get()[0]?.groupId||`br:main`;this.setActiveGroup(e,t)}}async deleteMessage(e,t){await Ie(e,t),await this.loadHistory(),this.orchestrator?.refreshContextUsage&&await this.orchestrator.refreshContextUsage(e,this._activeGroupId.get())}async deleteTask(e,t){let n=await this.getSubscriberId(e);if(await $(t,this.getTaskServerBaseUrl(),n,this.orchestrator?.taskServerEnabled??!1)===`failed`)throw console.warn(`Failed to delete task from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t,queuedAt:Date.now()}),Error(`Failed to delete scheduled task on server; task kept locally.`);await Le(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await M(e);if(!r.find(e=>e.groupId===n)){let i=[...r],a=``;if(this.orchestrator?.peerjsPeerAliases){for(let[e,n]of Object.entries(this.orchestrator.peerjsPeerAliases))if(n===t){a=e;break}}i.push({groupId:n,name:`Peer: ${a||t.substring(0,8)}`,createdAt:Date.now()}),await j(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await st(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,i){this._db=e,this.orchestrator=i,this._taskSyncOutbox=this.parseTaskSyncOutbox(await m(e,l.TASK_SYNC_OUTBOX)),await this.replayTaskSyncOutbox(e),typeof window<`u`&&!this._onlineReplayHandler&&(this._onlineReplayHandler=()=>{this._db&&this.replayTaskSyncOutbox(this._db)},window.addEventListener(`online`,this._onlineReplayHandler)),i.events.on(`a2ui-surface`,async({groupId:t,envelope:n})=>{t&&this.ensureGroupExists(e,t);let r=this._messages.get(),i=r.findIndex(e=>e.a2uiEnvelopes?.some(e=>e.surfaceId===n.surfaceId));if(i!==-1){let t=r[i],a=[...t.a2uiEnvelopes||[],n],o={...t,a2uiEnvelopes:a},s=[...r];s[i]=o,this._messages.set(s),await N(e,o)}else{let i=!t.startsWith(`peer:`),a={id:_(),groupId:t,sender:i?`agent`:t.replace(/^peer:/,``),content:``,timestamp:Date.now(),channel:t.startsWith(`peer:`)?`peerjs`:`browser`,isFromMe:i,isTrigger:!1,a2uiEnvelopes:[n]};t===this._activeGroupId.get()&&this._messages.set([...r,a]),await N(e,a)}}),i.events.on(`message`,t=>{if(t.groupId&&this.ensureGroupExists(e,t.groupId,t.timestamp),t.groupId&&t.groupId!==this._activeGroupId.get()){let e=new Set(this._unreadGroupIds.get());e.add(t.groupId),this._unreadGroupIds.set(e)}else t.isFromMe&&this._streamingText.get()!==null&&this._streamingText.set(null),this._messages.set([...this._messages.get(),t])}),i.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),i.events.on(`tool-activity`,({groupId:e,tool:t,status:n})=>{e&&e!==this._activeGroupId.get()||this._toolActivity.set(n===`running`?{tool:t,status:n}:null)}),i.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),i.events.on(`thinking-log`,e=>{e.groupId&&e.groupId!==this._activeGroupId.get()||(e.level===`info`&&e.label===`Starting`?this._activityLog.set([e]):this._activityLog.set([...this._activityLog.get(),e]),this.forwardActivityLogEntryToServer(e))}),i.events.on(`state-change`,e=>{let t=typeof e==`string`?e:e.state,n=typeof e==`string`?void 0:e.groupId;if(n&&n!==this._activeGroupId.get())return;let r=this._lastOrchestratorDisplayState;this._lastOrchestratorDisplayState=t,this._state.set(t),t===`idle`&&(this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null)),t===`thinking`&&r!==`thinking`&&r!==`responding`&&(this._tokenUsageAccumulator=null)}),i.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),i.events.on(`session-reset`,()=>{this._messages.set([]),this._activityLog.set([]),this._tokenUsageAccumulator=null,this._tokenUsage.set(null),this._contextUsage.set(null),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._isTyping.set(!1),this._state.set(`idle`)}),i.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),i.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=Zt(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),i.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),i.events.on(`ready`,()=>{this._ready.set(!0)}),i.events.on(`task-change`,()=>{this.loadTasks(e)}),i.events.on(`file-change`,()=>{this.loadFiles(e)}),i.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),i.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),i.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),i.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),i.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new Bt(i.events),this._aguiAdapter.start(),typeof window<`u`&&window.addEventListener(`shadow-claw-agui-event`,(e=>{e.detail.groupId===this._activeGroupId.get()&&this._aguiEvent.set(e.detail);let t=e.detail.event;if(t){if(t.type===`STATE_SNAPSHOT`){let n=new Map(this._peerStateByGroup.get());n.set(e.detail.groupId,t.snapshot||{}),this._peerStateByGroup.set(n)}else if(t.type===`STATE_DELTA`){let n=new Map(this._peerStateByGroup.get()),r=Vt(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await r(e),t(),n(),await k();let s=await m(e,l.PAGES_ALLOW_LIST),u=await m(e,l.PAGES_DENY_LIST);s&&this._pagesAllowList.set(Gt(String(s))),u&&this._pagesDenyList.set(Gt(String(u))),await k();let d=typeof document<`u`&&document.getElementById(`shadow-claw-static-routing`)!==null,f=await m(e,l.PAGES_LIST),p=f==null?[]:this.parsePagesList(f),h=await zt(e,c,p);h.length>0?(this.setPages(h),await this.persistPages(e)):await this.ensureDefaultPage(e),await k(),await this.applySiteConfigDefaults(e),await k(),await this.loadGroups(e);let g=await m(e,l.LAST_ACTIVE_GROUP);g&&g!==this._activeGroupId.get()&&this._activeGroupId.set(g),await k();let v=await m(e,l.LAST_ACTIVE_PAGE);v&&(this._activePage.set(v),this._hadPersistedActivePage=!0);let y=await m(e,l.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(y));let b=Pt(),x=null;if(b&&(x=o(b)),!x){let t=await m(e,l.DEFAULT_PINNED_PAGE);t&&(x=o(t))}x&&this.isPageAllowed(x.path,x.groupId)&&this._defaultPinnedPage.set(x),await k();let S=typeof window<`u`&&window.history?window.history.state:null,C=!!(S?.inFeedScroll||S?.scrollSpy||S?.suppressRouter)||typeof window<`u`&&window.location&&(()=>{let e=window.location.pathname||`/`,t=a();t!==`/`&&e.startsWith(t)&&(e=`/`+e.slice(t.length));let n=e.split(`/`).filter(Boolean);return n.length===0||n.length===1&&n[0]===`index.html`})(),w=!1;if(C&&x&&this.isPageAllowed(x.path,x.groupId)&&(this._activePinnedPage.set(x),w=!0),!w){let t=await m(e,l.LAST_SELECTED_PINNED_PAGE);if(t)try{let e=JSON.parse(t);e&&typeof e.path==`string`&&typeof e.groupId==`string`&&this.isPageAllowed(e.path,e.groupId)&&(this._activePinnedPage.set(e),w=!0)}catch{}}!w&&C&&this.effectiveDefaultPage&&this.isPageAllowed(this.effectiveDefaultPage.path,this.effectiveDefaultPage.groupId)&&(this._activePinnedPage.set(this.effectiveDefaultPage),w=!0),this.orchestrator&&(this._useProxy.set(this.orchestrator.useProxy),this._proxyUrl.set(this.orchestrator.proxyUrl),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess));let[ee,te,T]=await Promise.all([m(e,l.SIDEBAR_CHAT_HIDDEN),m(e,l.SIDEBAR_TASKS_HIDDEN),m(e,l.SIDEBAR_FILES_HIDDEN)]),E=Z(),ne=E?.sidebar?.chatHidden,re=E?.sidebar?.tasksHidden,D=E?.sidebar?.filesHidden,ie=ee==null?!!ne:oe(ee),ae=te==null?!!re:oe(te),O=T==null?!!D:oe(T),se=()=>{let t=[];(!ie||this.activePage===`chat`)&&t.push(this.loadHistory()),(!ae||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),Promise.all(t).catch(e=>{console.warn(`Secondary background store loads failed:`,e)})};if(d)typeof window.requestIdleCallback==`function`?window.requestIdleCallback(se,{timeout:2e3}):setTimeout(se,100);else{let t=[];(!ie||this.activePage===`chat`)&&t.push(this.loadHistory()),(!ae||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),await Promise.all(t)}await k(),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await C(e));let r=await at(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await M(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await Re(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await v(e),r=n.filter(e=>e.groupId===t);r.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(r);let i=await this.getSubscriberId(e),a=await Xt(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1);if(!a)return;let o=new Set(n.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));if(s.length===0)return;for(let t of s)await P(e,t);let c=[...r,...s];c.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(c)}async navigateBackFolder(e){let t=this._currentPath.get();if(t===`.`)return;let n=t.split(`/`).filter(Boolean);n.pop();let r=n.length===0?`.`:n.join(`/`);await this.setCurrentPath(e,r)}async navigateIntoFolder(e,t){let n=this._currentPath.get(),r=n===`.`?t.replace(/\/$/,``):`${n}/${t.replace(/\/$/,``)}`;try{await this.setCurrentPath(e,r)}catch(t){console.error(`Failed to navigate into folder in store:`,t),O(`Folder not found: ${r}`,4500),await this.loadFiles(e)}}async newSession(e){await this.orchestrator?.newSession?.(e,this._activeGroupId.get()),await this.loadHistory()}async removePage(t,n,r=this._activeGroupId.get()){let i=this.normalizePagePath(n);if(!i)return;let a=this._pages.get();if(!a.some(e=>e.path===i&&e.groupId===r))return;let o=a.filter(e=>e.path!==i||e.groupId!==r);await ft(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await z(t,!0);let l=s||await R(t);if(o.length===0&&!l){if(await B(t,`br:main`))o.push({groupId:c,path:e.DEFAULT_PAGE_PATH});else return}this.setPages(o);let u=this._defaultPinnedPage.get();u&&u.path===i&&u.groupId===r&&await this.setDefaultPinnedPage(t,null),await this.persistPages(t)}async removeAllPages(e){let t=[...this._pages.get()];for(let n of t)await ft(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await z(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await He(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await Ge(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await Ze(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await Q(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync reordered task "${t.id}" to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}async replayTaskSyncOutbox(e){if(!(this._replayingTaskSyncOutbox||this._taskSyncOutbox.length===0)){this._replayingTaskSyncOutbox=!0;try{let t=await this.getSubscriberId(e),n=[];for(let e of this._taskSyncOutbox){let r=this.getTaskServerBaseUrl();(e.type===`upsert`?await Q(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await $(e.id,r,t,this.orchestrator?.taskServerEnabled??!1))||n.push(e)}this._taskSyncOutbox=this.compactTaskSyncOutbox(n),await this.persistTaskSyncOutbox(e)}finally{this._replayingTaskSyncOutbox=!1}}}async resetToRootFolder(e){await this.setCurrentPath(e,`.`)}async restartCurrentRequest(){return this.orchestrator?.restartCurrentRequest?this.orchestrator.restartCurrentRequest(this._activeGroupId.get()):!1}async restoreTasksFromBackup(e,t){await this.clearAllTasks(e);let n=this._activeGroupId.get();for(let r of t){let t={...r,groupId:n,id:crypto.randomUUID?crypto.randomUUID():`task-${Date.now()}-${Math.random()}`};await this.upsertTask(e,t,{reloadTasks:!1})}await this.loadTasks(e)}async runTask(e,t=!1){let n=this._db;if(t&&n&&(await Xe(e.id,Date.now()),await this.loadTasks(n)),e.type===`tools`&&Array.isArray(e.tools)&&e.tools.length>0){if(this.orchestrator?.agentWorker){let n=e.subagent?`subagent:${_()}`:e.groupId;this.orchestrator.agentWorker.postMessage({type:`execute-task-tools`,payload:{groupId:n,tools:e.tools,isManual:t}})}else console.error(`Agent worker not available to execute tool task.`)}else{if(!e.groupId){console.error(`Task ${e.id} has no groupId - refusing to execute in active conversation to prevent context pollution.`);return}this.orchestrator?.browserChat?.submit(e.prompt,e.groupId,[],void 0,e.freshContext,e.subagent)}}async setActivePage(e,t){this._activePage.set(t),await g(e,l.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await g(e,l.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){t&&!this.isPageAllowed(t.path,t.groupId)&&(t=this.effectiveDefaultPage),this._activePinnedPage.set(t),t?await g(e,l.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await g(e,l.LAST_SELECTED_PINNED_PAGE,null)}async setDefaultPinnedPage(e,t){if(t&&!this.isPageAllowed(t.path,t.groupId))return;let n=this._defaultPinnedPage.get(),r=n&&t&&n.path===t.path&&n.groupId===t.groupId?null:t;this._defaultPinnedPage.set(r),r?await g(e,l.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await g(e,l.DEFAULT_PINNED_PAGE,null)}async reorderPages(e,t){this.setPages(t),await this.persistPages(e)}async setCurrentPath(e,t){let n=t.replace(/^\/+|\/+$/g,``)||`.`,r=this._activeGroupId.get();this._storageStatus.set(await C(e));let i=await at(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await be(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await Ce(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await Ae(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await je(this.orchestrator,e,t),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess))}async switchConversation(e,t,n){this.setActiveGroup(e,t,n??this._activePage.get()===`chat`),await g(e,l.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await P(e,r),await this.loadTasks(e),await Q(r,this.getTaskServerBaseUrl(),await this.getSubscriberId(e),this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to update task on server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:r.id,task:r,queuedAt:Date.now()}))}async updateConversationPinnedProvider(e,t,n,r,i){await qe(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await Ye(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await Je(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await Ue(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await P(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await Q(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync task to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}compactTaskSyncOutbox(e){let t=/* @__PURE__ */ new Map;return e.forEach((e,n)=>{t.set(e.id,n)}),e.filter((e,n)=>t.get(e.id)===n)}deriveGroupName(e){return e.startsWith(`tg:`)?`Telegram ${e.slice(3)}`:e.startsWith(`im:`)?`iMessage ${e.slice(3)}`:e.startsWith(`br:`)?e===`br:main`?`Main`:`Browser Conversation`:`Conversation`}getActivityLogSessionStartedAt(e){let t=this._activityLogSessionStartedAtByGroup.get(e);if(t)return t;let n=(/* @__PURE__ */ new Date()).toISOString();return this._activityLogSessionStartedAtByGroup.set(e,n),n}getTaskServerBaseUrl(){return this.orchestrator?.taskServerUrl??`/schedule`}async getSubscriberId(e){if(this._subscriberId)return this._subscriberId;let t=await S(e);return this._subscriberId=t,t}normalizePagePath(t){let n=t.trim().replace(/^\/+/,``).replace(/\/+/g,`/`);return n===`main/memory.md`?e.DEFAULT_PAGE_PATH:n}normalizeSidebarDefaultPage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`}parsePagesList(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{groupId:c,path:this.normalizePagePath(e)};if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.path!=`string`)return null;let n=typeof t.groupId==`string`&&t.groupId.trim().length>0?t.groupId:c,r=n===`br:main`?this.normalizePagePath(t.path):t.path.trim();return r?{groupId:n,path:r}:null}).filter(e=>!!e).filter((e,t,n)=>{let r=`${e.groupId}\u0000${e.path}`;return t===n.findIndex(e=>`${e.groupId}\u0000${e.path}`===r)}):[]}catch{return[]}}parseTaskSyncOutbox(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>!!e&&typeof e==`object`).filter(e=>e.type===`upsert`||e.type===`delete`).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({...e,queuedAt:typeof e.queuedAt==`number`?e.queuedAt:Date.now()}));return this.compactTaskSyncOutbox(n)}catch{return[]}}resolveSidebarDefaultPageForActivePage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:this._sidebarDefaultPage.get()}setPages(e){let t=e.filter(e=>this.isPageAllowed(e.path,e.groupId)),n=t.filter(e=>e.path.toLowerCase()===`memory.md`),r=t.filter(e=>e.path.toLowerCase()!==`memory.md`);this._pages.set([...r,...n])}async ensureDefaultPage(t){if(await R(t))return;let n=await B(t,c);await I(t,c),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:c,path:e.DEFAULT_PAGE_PATH}]),await this.persistPages(t))}async ensureGroupExists(e,t,n){let r=this._groups.get();if(r.some(e=>e.groupId===t))return;let i=[...r,{groupId:t,name:this.deriveGroupName(t),createdAt:n||Date.now()}];this._groups.set(i);try{await j(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!Jt(await m(this._db,l.ACTIVITY_LOG_DISK_LOGGING_ENABLED)))return;let t=typeof e.groupId==`string`&&e.groupId?e.groupId:this._activeGroupId.get();if(!t)return;let n=typeof e.message==`string`?e.message.trim():``;if(!n)return;e.level===`info`&&e.label===`Starting`&&this._activityLogSessionStartedAtByGroup.set(t,(/* @__PURE__ */ new Date()).toISOString());let r=this.getActivityLogSessionStartedAt(t);try{await fetch(`/activity-log`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({groupId:t,level:e.level,label:e.label,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString(),sessionStartedAt:r})})}catch(e){console.warn(`Failed to persist activity log entry to server:`,e)}}scheduleBackgroundStaticMainSiteSeeding(e){if(typeof window>`u`)return;let t=async()=>{try{if(await Ct(e,`br:main`))return;let t=await m(e,l.PAGES_LIST),n=t==null?[]:this.parsePagesList(t),r=await zt(e,c,n,{preferEmbedded:!1});r&&r.length>0&&(this.setPages(r),await this.persistPages(e))}catch(e){console.warn(`Background static main site seeding failed:`,e)}};typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:3e3}):setTimeout(()=>void t(),100)}async persistPages(e){await g(e,l.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await g(e,l.TASK_SYNC_OUTBOX,JSON.stringify(this._taskSyncOutbox))}async queueTaskSyncOutboxOperation(e,t){this._taskSyncOutbox=this.compactTaskSyncOutbox([...this._taskSyncOutbox,t]),await this.persistTaskSyncOutbox(e)}async applySiteConfigDefaults(e){if(typeof document<`u`)try{let r=Z();if(!r||typeof r!=`object`)return;i(r),t(),n();let a=r.customElements;if((await M(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await Ue(e,c,void 0),(r.settings?.internetAccess??r.settings?.vm_bash_full_internet_access??r.settings?.fullInternetAccess??r.internetAccess)===!0&&await m(e,l.VM_BASH_FULL_INTERNET_ACCESS)!==`true`&&(await g(e,l.VM_BASH_FULL_INTERNET_ACCESS,`true`),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=!0),this._vmBashFullInternetAccess.set(!0)),r.pages&&typeof r.pages==`object`){let{defaultPinnedPage:t}=r.pages;if(t&&typeof t==`string`){let n=o(t);n&&this.isPageAllowed(n.path,n.groupId)&&(this._defaultPinnedPage.set(n),await g(e,l.DEFAULT_PINNED_PAGE,JSON.stringify(n)))}}let s=r.allowedCustomElements||(typeof a==`object`&&!Array.isArray(a)?a.allowedElements:void 0);s!==void 0&&(await m(e,l.ALLOWED_CUSTOM_ELEMENTS)??await g(e,l.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(s)));let u=r.allowedCustomElementDomains||(typeof a==`object`&&!Array.isArray(a)?a.allowedDomains:void 0);if(u!==void 0&&(await m(e,l.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS)??await g(e,l.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(u))),r.sidebar&&typeof r.sidebar==`object`){let{pagesHidden:t,chatHidden:n,tasksHidden:i,filesHidden:a,defaultPage:o}=r.sidebar;if(t!==void 0&&(await m(e,l.SIDEBAR_PAGES_HIDDEN)??await g(e,l.SIDEBAR_PAGES_HIDDEN,String(!!t))),n!==void 0&&(await m(e,l.SIDEBAR_CHAT_HIDDEN)??await g(e,l.SIDEBAR_CHAT_HIDDEN,String(!!n))),i!==void 0&&(await m(e,l.SIDEBAR_TASKS_HIDDEN)??await g(e,l.SIDEBAR_TASKS_HIDDEN,String(!!i))),a!==void 0&&(await m(e,l.SIDEBAR_FILES_HIDDEN)??await g(e,l.SIDEBAR_FILES_HIDDEN,String(!!a))),o&&typeof o==`string`){let t=this.normalizeSidebarDefaultPage(o);this._sidebarDefaultPage.set(t),await m(e,l.SIDEBAR_DEFAULT_PAGE)||await g(e,l.SIDEBAR_DEFAULT_PAGE,o)}}if(r.settings&&typeof r.settings==`object`){let{assistantName:t,defaultProvider:n,provider:i,defaultModel:a,model:o}=r.settings;t&&typeof t==`string`&&(await m(e,l.ASSISTANT_NAME)||await g(e,l.ASSISTANT_NAME,t));let s=n??i;if(typeof s==`string`&&s.trim().length>0&&!await m(e,l.PROVIDER)){let t=s.trim();await g(e,l.PROVIDER,t),this.orchestrator&&(this.orchestrator.provider=t)}let c=a??o;if(typeof c==`string`&&c.trim().length>0&&!await m(e,l.MODEL)){let t=c.trim();await g(e,l.MODEL,t),this.orchestrator&&(this.orchestrator.model=t)}let u=r.settings.internetAccess??r.settings.vm_bash_full_internet_access??r.settings.fullInternetAccess??r.internetAccess;typeof u==`boolean`&&(await m(e,l.VM_BASH_FULL_INTERNET_ACCESS)??(await g(e,l.VM_BASH_FULL_INTERNET_ACCESS,String(u)),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=u),this._vmBashFullInternetAccess.set(u)))}let d=(r.settings&&typeof r.settings==`object`?r.settings.defaultToolsProfile:void 0)??r.defaultToolsProfile;if(typeof d==`string`&&d.trim().length>0&&!await m(e,l.ACTIVE_TOOL_PROFILE)){let t=d.trim();if(t.toLowerCase()===`none`)await x.deactivateProfile(e);else{let n=x.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await x.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(r.pages&&typeof r.pages==`object`){let{defaultPinnedPage:t}=r.pages;t&&typeof t==`string`&&(await m(e,l.DEFAULT_PINNED_PAGE)||await g(e,l.DEFAULT_PINNED_PAGE,t))}let f=r.pages?.allowList??r.pages?.allowlist??r.allowList??r.allowlist,p=r.pages?.denyList??r.pages?.denylist??r.denyList??r.denylist;if(Array.isArray(f)&&await m(e,l.PAGES_ALLOW_LIST)==null){let t=K(f.map(String));this._pagesAllowList.set(t),await g(e,l.PAGES_ALLOW_LIST,JSON.stringify(t))}if(Array.isArray(p)&&await m(e,l.PAGES_DENY_LIST)==null){let t=K(p.map(String));this._pagesDenyList.set(t),await g(e,l.PAGES_DENY_LIST,JSON.stringify(t))}await g(e,l.SITE_CONFIG_SEEDED,`true`);let h=this._pages.get(),_=h.filter(e=>this.isPageAllowed(e.path,e.groupId));_.length!==h.length&&(this.setPages(_),await this.persistPages(e));let v=this._activePinnedPage.get();v&&!this.isPageAllowed(v.path,v.groupId)&&await this.setActivePinnedPage(e,this.effectiveDefaultPage);let y=this._defaultPinnedPage.get();if(y&&!this.isPageAllowed(y.path,y.groupId)&&await this.setDefaultPinnedPage(e,null),Array.isArray(r.enabledTools)){let t=r.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await x.setAllEnabled(e,t),await x.setAllDeclarativeEnabled(e,t)}await g(e,l.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const $t=new Qt;export{ye as A,Ae as B,N as C,Re as D,M as E,Te as F,le as G,ve as H,Ee as I,he as J,de as K,De as L,Se as M,Ce as N,Le as O,we as P,k as Q,Oe as R,P as S,A as T,me as U,Me as V,ue as W,se as X,_e as Y,ce as Z,B as _,Pt as a,nt as b,K as c,U as d,ct as f,at as g,H as h,Gt as i,xe as j,Ne as k,ft as l,lt as m,Kt as n,Ft as o,V as p,ge as q,Z as r,jt as s,$t as t,W as u,z as v,Ve as w,Xe as x,I as y,ke as z};
63
+ `)}\n${s}`}return s}async function At(e={}){let t=()=>{let e=null;if(typeof document<`u`){let t=document.getElementById(`shadow-claw-static-manifest`);if(t&&t.textContent)try{let n=JSON.parse(t.textContent);n&&Array.isArray(n.pages)&&(e={...n,pages:[...n.pages]})}catch(e){console.warn(`Failed to parse embedded static main manifest:`,e)}let n=document.querySelectorAll(`script[type="text/markdown"][data-shadow-claw-page]`);if(n.length>0){e||={pages:[]};for(let t of Array.from(n)){let n=t.getAttribute(`data-shadow-claw-page`)?.trim();if(n){let r=t.textContent||``;r=ie(r),!r.trim()&&/^memory\.(md|markdown)$/iu.test(n)&&(r=L),!r.trim()&&(n===`index.html`||/^index\.(html?|xhtml)$/iu.test(n))&&(r=Y(n)??F);let i=e.pages.findIndex(e=>e.displayPath===n);i>=0?e.pages[i].content=r:e.pages.push({displayPath:n,content:r})}}}let r=document.getElementById(`shadow-claw-site-config`);if(r?.textContent)try{let t=JSON.parse(r.textContent);if(Array.isArray(t?.pages?.files)){e||={pages:[]};for(let n of t.pages.files)if(typeof n==`string`&&n.trim()){let t=n.trim(),r=``;/^memory\.(md|markdown)$/iu.test(t)?r=L:(t===`index.html`||/^index\.(html?|xhtml)$/iu.test(t))&&(r=Y(t)??F),e.pages.some(e=>e.displayPath===t)||e.pages.push({displayPath:t,content:r})}}}catch{}let i=kt();if(i){e||={pages:[]};let t=i.getAttribute(`data-initial-path`)?.trim()||`index.html`;if(!e.pages.some(e=>e.displayPath===t)){let n=Y(t)??F;e.pages.push({displayPath:t,content:n})}e.pages.some(e=>/^memory\.(md|markdown)$/iu.test(e.displayPath))||e.pages.push({displayPath:`MEMORY.md`,content:L})}}return e};if(e.preferEmbedded!==!1){let e=t();if(e&&e.pages.length>0)return e}if(e.fetchFallback!==!1){let e=await Dt();if(e&&e.pages.length>0)return e}if(e.preferEmbedded===!1){let e=t();if(e&&e.pages.length>0)return e}return{pages:[{displayPath:`index.html`,content:F},{displayPath:`MEMORY.md`,content:L}]}}async function jt(e){if(typeof document<`u`){let t=document.getElementById(`shadow-claw-static-manifest`);if(t&&t.textContent)try{let n=JSON.parse(t.textContent);if(n&&Array.isArray(n.pages)){let t=n.pages.find(t=>t.displayPath===e);if(t&&typeof t.content==`string`&&t.content.trim())return t.content}}catch{}let n=document.querySelectorAll(`script[type="text/markdown"][data-shadow-claw-page]`);for(let t of Array.from(n))if(t.getAttribute(`data-shadow-claw-page`)?.trim()===e){let e=t.textContent||``;if(e.trim())return e}let r=Y(e);if(typeof r==`string`&&r.trim())return r;if(/^memory\.(md|markdown)$/iu.test(e))return L;if(e===`index.html`||/^index\.(html?|xhtml)$/iu.test(e))return F}let t=await Ot(e);if(typeof t==`string`)return t;let n=await Dt();if(n&&Array.isArray(n.pages)){let t=n.pages.find(t=>t.displayPath===e);if(t&&typeof t.content==`string`)return t.content}return null}async function Mt(e,t,n=[]){for(let[r,i]of Object.entries(t))if(r===`purgePreRenderedStaticPages`&&i===!0){if(n.length>0){let t=n[0],r=n.slice(1).join(`/`);try{r?await W(e,t,r):await U(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await Mt(e,i,[...n,r])}function Nt(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t?.pages?.sortOrder===`desc`)return`desc`;if(t?.pages?.sortOrder===`asc`)return`asc`}}catch{}return`desc`}function Pt(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent)?.pages?.defaultPinnedPage;if(typeof t==`string`&&t.trim().length>0)return t.trim()}}catch{}return null}function Ft(){let e=`ShadowClaw`,t,n;if(typeof document<`u`){try{let r=document.getElementById(`shadow-claw-site-config`);if(r?.textContent){let i=JSON.parse(r.textContent);i?.site?.title&&(e=String(i.site.title).trim()),(i?.site?.titleSeparator??i?.site?.sep)&&(t=String(i.site.titleSeparator??i.site.sep)),i?.site?.titleTemplate&&(n=String(i.site.titleTemplate))}}catch{}if(e===`ShadowClaw`&&document.title){let t=document.title.split(/\s*[-|—•·]\s*/),n=t[t.length-1]?.trim();n&&(e=n)}}return{siteTitle:e,separator:t,titleTemplate:n}}function It(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);return{allowList:K(t?.pages?.allowList??t?.pages?.allowlist??t?.allowList??t?.allowlist??[]),denyList:K(t?.pages?.denyList??t?.pages?.denylist??t?.denyList??t?.denylist??[])}}}catch{}return{allowList:[],denyList:[]}}function Lt(e,t){let n=t??Nt();return[...e].sort((e,t)=>{let r=e.path,i=t.path,a=r.split(`/`).pop()||``,o=i.split(`/`).pop()||``,s=/^index\.(html?|xhtml)$/iu.test(a),c=/^index\.(html?|xhtml)$/iu.test(o);if(s&&!c)return-1;if(!s&&c)return 1;let l=/^memory\.(md|markdown)$/iu.test(a),u=/^memory\.(md|markdown)$/iu.test(o);return l&&!u?1:!l&&u?-1:n===`asc`?r.localeCompare(i,void 0,{numeric:!0,sensitivity:`base`}):i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})})}async function Rt(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(ct(n)===i)return!0}catch{}try{if(await m(e,r)===i){try{H(n,i)}catch{}return!0}await g(e,r,i);try{H(n,i)}catch{}}catch{try{H(n,i)}catch{}}return!1}async function zt(e,t=c,n=[],r={}){await I(e,t);let i=await At(r),a=!1;i.preRenderedStaticPages&&(await Rt(e,i.purgeId)||(a=!0,await Mt(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await Rt(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await W(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}try{await W(e,t,`.agents/tools/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}}for(let n of i.pages)if(n.content?.includes(`slug: "shadow-claw--purge-pages"`)){!a&&!await Rt(e,i.purgeId)&&(a=!0,await U(e,t));break}let s=t===`br:main`&&await R(e),l=new Set(i.pages.map(e=>G(t,e.displayPath))),u=a?n.filter(e=>e.groupId!==t||l.has(G(e.groupId,e.path))):[...n],{allowList:d,denyList:f}=It(),p=0;for(let n of i.pages)if(p++,p%5==0&&await new Promise(e=>setTimeout(e,0)),!n.content?.includes(`slug: "shadow-claw--purge-pages"`)&&xt(n.displayPath,{allowList:d,denyList:f,groupId:t})){if(/^memory\.(md|markdown)$/iu.test(n.displayPath)){if(s)continue;let r=typeof n.content==`string`&&n.content.trim().length>0&&n.content!==L?n.content:void 0;if(r===void 0?await B(e,t):await B(e,t,r)){let e=G(t,n.displayPath);u.some(t=>G(t.groupId,t.path)===e)||u.push({groupId:t,path:n.displayPath})}}else if(!await dt(e,t,n.displayPath))try{if(!await y(e,t,n.displayPath)){let r=n.content;(typeof r!=`string`||!r.trim())&&(r=n.displayPath===`index.html`?Y(`index.html`)??F:await Ot(n.displayPath)??``),await D(e,t,n.displayPath,r)}let r=G(t,n.displayPath);u.some(e=>G(e.groupId,e.path)===r)||u.push({groupId:t,path:n.displayPath})}catch(e){console.warn(`Failed to seed static page file ${n.displayPath}:`,e)}}if(t===`br:main`){for(let n of i.skills||[]){let r=`.agents/skills/main/${n.displayPath}`;try{await y(e,t,r)||await D(e,t,r,n.content)}catch(e){console.warn(`Failed to seed skill file ${r}:`,e)}}for(let n of i.tools||[]){let r=`.agents/tools/main/${n.displayPath}`;try{(o||!await y(e,t,r))&&await D(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let m=typeof document<`u`&&(document.getElementById(`shadow-claw-static-manifest`)!==null||document.querySelector(`script[type="text/markdown"][data-shadow-claw-page]`)!==null||kt()!==null);r.preferEmbedded!==!1&&m||await wt(e,t,!0);let h=u.filter(e=>xt(e.path,{allowList:d,denyList:f,groupId:e.groupId}));return Object.defineProperty(h,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(h,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),Lt(h)}var Bt=class{_events;_handlers=[];_runs=/* @__PURE__ */ new Map;constructor(e){this._events=e}start(){this._listen(`streaming-start`,this._onStreamingStart),this._listen(`streaming-chunk`,this._onStreamingChunk),this._listen(`streaming-end`,this._onStreamingEnd),this._listen(`streaming-done`,this._onStreamingDone),this._listen(`streaming-error`,this._onStreamingError),this._listen(`tool-activity`,this._onToolActivity)}stop(){for(let{event:e,handler:t}of this._handlers)this._events.off(e,t);this._handlers=[],this._runs.clear()}_emit(e,t){window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{groupId:e,event:t}}))}_listen(e,t){this._events.on(e,t),this._handlers.push({event:e,handler:t})}_onStreamingChunk=({groupId:e,text:t})=>{let n=this._runs.get(e);n&&n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_CONTENT`,messageId:n.messageId,delta:t,timestamp:Date.now()})};_onStreamingDone=({groupId:e})=>{let t=this._runs.get(e);t&&(t.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_FINISHED`,threadId:t.threadId,runId:t.runId,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingEnd=({groupId:e})=>{let t=this._runs.get(e);t&&t.messageId&&(this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),t.messageId=null)};_onStreamingError=({groupId:e,error:t})=>{let n=this._runs.get(e);n&&(n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:n.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_ERROR`,message:t||`Unknown streaming error`,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingStart=({groupId:e})=>{let t=_(),n=e,r=_();this._runs.set(e,{runId:t,threadId:n,messageId:r,activeToolCallIds:/* @__PURE__ */ new Set}),this._emit(e,{type:`RUN_STARTED`,threadId:n,runId:t,timestamp:Date.now()}),this._emit(e,{type:`TEXT_MESSAGE_START`,messageId:r,role:`assistant`,timestamp:Date.now()})};_onToolActivity=({groupId:e,tool:t,status:n})=>{let r=this._runs.get(e);if(r){if(n===`running`){let n=_();r.activeToolCallIds.add(n),this._emit(e,{type:`TOOL_CALL_START`,toolCallId:n,toolCallName:t,timestamp:Date.now()}),r._lastToolCallId=n}else if(n===`done`||n===`error`){let t=r._lastToolCallId;t&&(r.activeToolCallIds.delete(t),this._emit(e,{type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()}))}}}};function Vt(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)Ht(n,e);return n}function Ht(e,t){let{op:n,path:r,value:i}=t;if(!r||!r.startsWith(`/`))return;let a=r.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),o=a.pop();if(o===void 0)return;let s=e;for(let e of a){if(typeof s!=`object`||!s)return;s=s[e]}typeof s==`object`&&s&&(Array.isArray(s)?Ut(s,o,n,i):Wt(s,o,n,i))}function Ut(e,t,n,r){if(n===`add`){if(t===`-`)e.push(r);else{let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<=e.length&&e.splice(n,0,r)}}else if(n===`replace`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&(e[n]=r)}else if(n===`remove`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&e.splice(n,1)}}function Wt(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}function Gt(e){if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t))return K(t.map(e=>String(e)))}catch{}return K(e.split(`,`))}let X=/* @__PURE__ */ new Map;function Z(e){if(typeof document>`u`)return null;let t=`shadow-claw-site-config`;if(e){let n=e.getAttribute(`config`)?.trim();n&&(t=n.replace(/^#/,``))}let n=document.getElementById(t);if(!n?.textContent)return X.delete(t),null;let r=X.get(t);if(r&&r.rawText===n.textContent)return r.config;try{let e=JSON.parse(n.textContent);if(!e||typeof e!=`object`)return X.delete(t),null;let r={...e};return X.set(t,{rawText:n.textContent,config:r}),r}catch(e){return console.warn(`[ShadowClaw] Failed to parse site configuration from #${t}:`,e),null}}var Kt=/* @__PURE__ */ e({OrchestratorStore:()=>Qt,accumulateTokenUsage:()=>Zt,orchestratorStore:()=>$t});function qt(e){if(e){if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:void 0}catch{return}}}function Jt(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return typeof e==`number`&&e===1}function Yt(e){return!!e}async function Q(e,t,n,r){if(!Yt(r))return!0;if(!e.schedule)return await $(e.id,t,n,r)!==`failed`;try{let r=t.replace(/\/$/,``);return(await fetch(`${r}/tasks`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,subscriberId:n})})).ok}catch{return!1}}async function $(e,t,n,r){if(!Yt(r))return`missing`;try{let r=t.replace(/\/$/,``),i=`subscriberId=${encodeURIComponent(n)}`,a=await fetch(`${r}/tasks/${encodeURIComponent(e)}?${i}`,{method:`DELETE`});return a.ok?`deleted`:a.status===404||a.status===405?`missing`:`failed`}catch{return`failed`}}async function Xt(e,t,n,r){if(!Yt(r))return null;try{let r=t.replace(/\/$/,``),i=await fetch(`${r}/tasks?groupId=${encodeURIComponent(e)}&subscriberId=${encodeURIComponent(n)}`,{method:`GET`});if(!i.ok||typeof i.json!=`function`)return null;let a=await i.json();return Array.isArray(a)?a.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.schedule==`string`&&typeof e.prompt==`string`).map(t=>({id:t.id,groupId:t.group_id||t.groupId||e,schedule:t.schedule,type:t.type,prompt:t.prompt,tools:qt(t.tools),channel:typeof t.channel==`string`?t.channel:void 0,enabled:t.enabled===!0||t.enabled===1,lastRun:typeof t.lastRun==`number`?t.lastRun:typeof t.last_run==`number`?t.last_run:null,createdAt:typeof t.createdAt==`number`?t.createdAt:typeof t.created_at==`number`?t.created_at:Date.now(),name:typeof t.name==`string`?t.name:void 0,order:typeof t.order==`number`?t.order:typeof t.task_order==`number`?t.task_order:void 0})):null}catch{return null}}function Zt(e,t){let n=(e?.inputTokens??0)+(t.inputTokens??0),r=(e?.outputTokens??0)+(t.outputTokens??0),i=(e?.cacheReadTokens??0)+(t.cacheReadTokens??0),a=(e?.cacheCreationTokens??0)+(t.cacheCreationTokens??0);return{groupId:t.groupId||e?.groupId||``,inputTokens:n,outputTokens:r,cacheReadTokens:i,cacheCreationTokens:a,totalTokens:n+r+i+a,contextLimit:t.contextLimit||e?.contextLimit||0}}var Qt=class e{static DEFAULT_PAGE_PATH=`MEMORY.md`;orchestrator;_activeGroupId;_activePage;_activePinnedPage;_defaultPinnedPage;_activityLog;_activityLogSessionStartedAtByGroup;_aguiAdapter;_aguiEvent;_contextUsage;_currentPath;_db;_error;_files;_gitProxyUrl;_groups;_hadPersistedActivePage;_initResolve;_isTyping;_lastOrchestratorDisplayState=`idle`;_messages;_modelDownloadProgress;_onlineReplayHandler;_pages;_pagesAllowList;_pagesDenyList;_peerStateByGroup;_proxyUrl;_ready;_remoteAgentStatusByGroup;_remoteAgentTypingByGroup;_replayingTaskSyncOutbox;_subscriberId;_sidebarDefaultPage;_state;_storageStatus;_streamingText;_tasks;_taskSyncOutbox;_tokenUsage;_tokenUsageAccumulator=null;_toolActivity;_unreadGroupIds;_useProxy;_vmBashFullInternetAccess;_whenInitialized;_whenReady;_readyResolve;constructor(){this._messages=new h.State([]),this._isTyping=new h.State(!1),this._storageStatus=new h.State(null),this._toolActivity=new h.State(null),this._modelDownloadProgress=new h.State(null),this._activityLog=new h.State([]),this._state=new h.State(`idle`),this._tokenUsage=new h.State(null),this._error=new h.State(null),this._activeGroupId=new h.State(c),this._ready=new h.State(!1),this._tasks=new h.State([]),this._files=new h.State([]),this._currentPath=new h.State(`.`),this._groups=new h.State([]),this._unreadGroupIds=new h.State(/* @__PURE__ */ new Set),this._streamingText=new h.State(null),this._aguiEvent=new h.State(null),this._contextUsage=new h.State(null),this._useProxy=new h.State(!1),this._proxyUrl=new h.State(`/proxy`),this._gitProxyUrl=new h.State(`/git-proxy`),this._vmBashFullInternetAccess=new h.State(!1),this._activePage=new h.State(`pages`);let e=Z()?.sidebar?.defaultPage,t=e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`;this._sidebarDefaultPage=new h.State(t),this._pages=new h.State([]),this._pagesAllowList=new h.State([]),this._pagesDenyList=new h.State([]),this._activePinnedPage=new h.State(null),this._defaultPinnedPage=new h.State(null),this._remoteAgentStatusByGroup=new h.State(/* @__PURE__ */ new Map),this._remoteAgentTypingByGroup=new h.State(/* @__PURE__ */ new Map),this._peerStateByGroup=new h.State(/* @__PURE__ */ new Map),this._hadPersistedActivePage=!1,this._initResolve=null,this._whenInitialized=new Promise(e=>{this._initResolve=e}),this._readyResolve=null,this._whenReady=new Promise(e=>{this._readyResolve=e}),this.orchestrator=null,this._db=null,this._activityLogSessionStartedAtByGroup=/* @__PURE__ */ new Map,this._taskSyncOutbox=[],this._replayingTaskSyncOutbox=!1,this._subscriberId=null,this._onlineReplayHandler=null,this._aguiAdapter=null}get activeGroupId(){return this._activeGroupId.get()}get activePage(){return this._activePage.get()}get activePinnedPage(){return this._activePinnedPage.get()}get defaultPinnedPage(){return this._defaultPinnedPage.get()}get pagesAllowList(){return this._pagesAllowList.get()}get pagesDenyList(){return this._pagesDenyList.get()}isPageAllowed(e,t){return xt(e,{allowList:this._pagesAllowList.get(),denyList:this._pagesDenyList.get(),groupId:t??this._activeGroupId.get()})}get effectiveDefaultPage(){let e=this._defaultPinnedPage.get();return e&&this.isPageAllowed(e.path,e.groupId)?e:this._pages.get()[0]||null}get activityLog(){return this._activityLog.get()}get taskServerEnabled(){return this.orchestrator?.taskServerEnabled??!1}get aguiEvent(){return this._aguiEvent.get()}clearError(){this._error.set(null),this._state.get()===`error`&&this._state.set(`idle`)}get contextUsage(){return this._contextUsage.get()}get tokenUsageAccumulator(){return this._tokenUsageAccumulator}get currentPath(){return this._currentPath.get()}get error(){return this._error.get()}get files(){return this._files.get()}getPeerState(e){return this._peerStateByGroup.get().get(e)||null}getRemoteAgentStatus(e){return this._remoteAgentStatusByGroup.get().get(e)||`idle`}getState(){return{messages:this.messages,isTyping:this.isTyping,toolActivity:this.toolActivity,activityLog:this.activityLog,state:this.state,tokenUsage:this.tokenUsage,modelDownloadProgress:this.modelDownloadProgress,error:this.error,activeGroupId:this.activeGroupId,pages:this.pages,ready:this.ready,files:this.files,currentPath:this.currentPath,streamingText:this.streamingText,contextUsage:this.contextUsage}}getTasksForBackup(){return this._tasks.get()}get gitProxyUrl(){return this._gitProxyUrl.get()}get groups(){return this._groups.get()}get hadPersistedActivePage(){return this._hadPersistedActivePage}isRemoteAgentTyping(e){return this._remoteAgentTypingByGroup.get().get(e)||!1}get isTyping(){return this._isTyping.get()}get messages(){return this._messages.get()}get modelDownloadProgress(){return this._modelDownloadProgress.get()}get pages(){return this._pages.get()}get proxyUrl(){return this._proxyUrl.get()}get ready(){return this._ready.get()}sendMessage(e,t=[],n){n===void 0?this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t):this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t,n)}async sendFileToPeer(e,t=this._activeGroupId.get(),n){let r=t.startsWith(`peer:`),i=t.startsWith(`room:`);if(!r&&!i){let e=`Can only send files to peers in a peer or room conversation.`;throw O(e,4500),Error(e)}let a=this.orchestrator?.router;if(!a){let e=`Network router is not initialized.`;throw O(e,4500),Error(e)}let o=n?.fileName||e.split(`/`).pop()||e,s=n?.mimeType||`application/octet-stream`,c=n?.size||0;a.setTyping(t,!0);try{let n={path:e,fileName:o,mimeType:s,size:c};if(await a.send(t,``,[n]),this._db){let e={id:_(),groupId:t,sender:`You`,content:``,timestamp:Date.now(),channel:i?`room`:`peerjs`,attachments:[n],isFromMe:!1,isTrigger:!1};await N(this._db,e),this.orchestrator?.events.emit(`message`,e)}ae(`Sent ${o} to ${i?`room peers`:`peer`}`,2500)}catch(e){let t=e instanceof Error?e.message:String(e);throw console.error(`sendFileToPeer error:`,e),O(`Failed to send file: ${t}`,6e3),e}finally{a.setTyping(t,!1)}}setActiveGroup(e,t,n=this._activePage.get()===`chat`){if(this._activeGroupId.set(t),this._messages.set([]),this._activityLog.set([]),this._error.set(null),this._isTyping.set(!1),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._currentPath.set(`.`),n){let e=new Set(this._unreadGroupIds.get());e.delete(t)&&this._unreadGroupIds.set(e)}this.loadHistory(),this.loadTasks(e),this.loadFiles(e)}setReady(e=!0){this._ready.set(e),e&&this._readyResolve&&this._readyResolve()}setRemoteAgentStatus(e,t){let n=this._remoteAgentStatusByGroup.get(),r=new Map(n);r.set(e,t),this._remoteAgentStatusByGroup.set(r)}setRemoteAgentTyping(e,t){let n=this._remoteAgentTypingByGroup.get(),r=new Map(n);t?r.set(e,!0):r.delete(e),this._remoteAgentTypingByGroup.set(r)}get sidebarDefaultPage(){return this._sidebarDefaultPage.get()}get state(){return this._state.get()}stopCurrentRequest(){this.orchestrator?.stopCurrentRequest?.(this._activeGroupId.get())}get storageStatus(){return this._storageStatus.get()}get streamingText(){return this._streamingText.get()}syncHostWorkspaceToVM(){fe(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){pe(this.orchestrator,this._activeGroupId.get())}get tasks(){return this._tasks.get()}get tokenUsage(){return this._tokenUsage.get()}get toolActivity(){return this._toolActivity.get()}get unreadGroupIds(){return this._unreadGroupIds.get()}get useProxy(){return this._useProxy.get()}get vmBashFullInternetAccess(){return this._vmBashFullInternetAccess.get()}get whenInitialized(){return this._whenInitialized}async resetSiteConfigSeed(e){await g(e,l.SITE_CONFIG_SEEDED,!1)}get whenReady(){return this._whenReady}async addPage(e,t,n=this._activeGroupId.get()){let r=n===`br:main`?this.normalizePagePath(t):t.trim();if(!r||!this.isPageAllowed(r,n))return;let i=this._pages.get();i.some(e=>e.path===r&&e.groupId===n)||(this.setPages([...i,{groupId:n,path:r}]),await pt(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await z(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await v(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r)await $(t.id,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)===`failed`?(console.warn(`Failed to delete task "${t.id}" from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t.id,queuedAt:Date.now()})):await Le(e,t.id);await this.loadTasks(e)}async cloneConversation(e,t){let n=await Ke(e,t);if(!n)return null;await Pe(e,t,n.groupId),await Fe(e,t,n.groupId);try{let r=await b(e,t,`MEMORY.md`);r&&await D(e,n.groupId,`MEMORY.md`,r)}catch{}try{await Qe(e,t,n.groupId,`attachments`)}catch{}return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async compactContext(e){if(!this.orchestrator)return;let{compactContext:t}=await import(`./compact-context-dHitmPsV.js`);return t(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await Ve(e,t);return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await We(e,t),await Ne(e,t),await this.loadGroups(e),this._activeGroupId.get()===t)){let t=this._groups.get()[0]?.groupId||`br:main`;this.setActiveGroup(e,t)}}async deleteMessage(e,t){await Ie(e,t),await this.loadHistory(),this.orchestrator?.refreshContextUsage&&await this.orchestrator.refreshContextUsage(e,this._activeGroupId.get())}async deleteTask(e,t){let n=await this.getSubscriberId(e);if(await $(t,this.getTaskServerBaseUrl(),n,this.orchestrator?.taskServerEnabled??!1)===`failed`)throw console.warn(`Failed to delete task from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t,queuedAt:Date.now()}),Error(`Failed to delete scheduled task on server; task kept locally.`);await Le(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await M(e);if(!r.find(e=>e.groupId===n)){let i=[...r],a=``;if(this.orchestrator?.peerjsPeerAliases){for(let[e,n]of Object.entries(this.orchestrator.peerjsPeerAliases))if(n===t){a=e;break}}i.push({groupId:n,name:`Peer: ${a||t.substring(0,8)}`,createdAt:Date.now()}),await j(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await st(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,i){this._db=e,this.orchestrator=i,this._taskSyncOutbox=this.parseTaskSyncOutbox(await m(e,l.TASK_SYNC_OUTBOX)),await this.replayTaskSyncOutbox(e),typeof window<`u`&&!this._onlineReplayHandler&&(this._onlineReplayHandler=()=>{this._db&&this.replayTaskSyncOutbox(this._db)},window.addEventListener(`online`,this._onlineReplayHandler)),i.events.on(`a2ui-surface`,async({groupId:t,envelope:n})=>{t&&this.ensureGroupExists(e,t);let r=this._messages.get(),i=r.findIndex(e=>e.a2uiEnvelopes?.some(e=>e.surfaceId===n.surfaceId));if(i!==-1){let t=r[i],a=[...t.a2uiEnvelopes||[],n],o={...t,a2uiEnvelopes:a},s=[...r];s[i]=o,this._messages.set(s),await N(e,o)}else{let i=!t.startsWith(`peer:`),a={id:_(),groupId:t,sender:i?`agent`:t.replace(/^peer:/,``),content:``,timestamp:Date.now(),channel:t.startsWith(`peer:`)?`peerjs`:`browser`,isFromMe:i,isTrigger:!1,a2uiEnvelopes:[n]};t===this._activeGroupId.get()&&this._messages.set([...r,a]),await N(e,a)}}),i.events.on(`message`,t=>{if(t.groupId&&this.ensureGroupExists(e,t.groupId,t.timestamp),t.groupId&&t.groupId!==this._activeGroupId.get()){let e=new Set(this._unreadGroupIds.get());e.add(t.groupId),this._unreadGroupIds.set(e)}else t.isFromMe&&this._streamingText.get()!==null&&this._streamingText.set(null),this._messages.set([...this._messages.get(),t])}),i.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),i.events.on(`tool-activity`,({groupId:e,tool:t,status:n})=>{e&&e!==this._activeGroupId.get()||this._toolActivity.set(n===`running`?{tool:t,status:n}:null)}),i.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),i.events.on(`thinking-log`,e=>{e.groupId&&e.groupId!==this._activeGroupId.get()||(e.level===`info`&&e.label===`Starting`?this._activityLog.set([e]):this._activityLog.set([...this._activityLog.get(),e]),this.forwardActivityLogEntryToServer(e))}),i.events.on(`state-change`,e=>{let t=typeof e==`string`?e:e.state,n=typeof e==`string`?void 0:e.groupId;if(n&&n!==this._activeGroupId.get())return;let r=this._lastOrchestratorDisplayState;this._lastOrchestratorDisplayState=t,this._state.set(t),t===`idle`&&(this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null)),t===`thinking`&&r!==`thinking`&&r!==`responding`&&(this._tokenUsageAccumulator=null)}),i.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),i.events.on(`session-reset`,()=>{this._messages.set([]),this._activityLog.set([]),this._tokenUsageAccumulator=null,this._tokenUsage.set(null),this._contextUsage.set(null),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._isTyping.set(!1),this._state.set(`idle`)}),i.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),i.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=Zt(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),i.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),i.events.on(`ready`,()=>{this._ready.set(!0)}),i.events.on(`task-change`,()=>{this.loadTasks(e)}),i.events.on(`file-change`,()=>{this.loadFiles(e)}),i.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),i.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),i.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),i.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),i.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new Bt(i.events),this._aguiAdapter.start(),typeof window<`u`&&window.addEventListener(`shadow-claw-agui-event`,(e=>{e.detail.groupId===this._activeGroupId.get()&&this._aguiEvent.set(e.detail);let t=e.detail.event;if(t){if(t.type===`STATE_SNAPSHOT`){let n=new Map(this._peerStateByGroup.get());n.set(e.detail.groupId,t.snapshot||{}),this._peerStateByGroup.set(n)}else if(t.type===`STATE_DELTA`){let n=new Map(this._peerStateByGroup.get()),r=Vt(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await r(e),t(),n(),await k();let s=await m(e,l.PAGES_ALLOW_LIST),u=await m(e,l.PAGES_DENY_LIST);s&&this._pagesAllowList.set(Gt(String(s))),u&&this._pagesDenyList.set(Gt(String(u))),await k();let d=typeof document<`u`&&document.getElementById(`shadow-claw-static-routing`)!==null,f=await m(e,l.PAGES_LIST),p=f==null?[]:this.parsePagesList(f),h=await zt(e,c,p);h.length>0?(this.setPages(h),await this.persistPages(e)):await this.ensureDefaultPage(e),await k(),await this.applySiteConfigDefaults(e),await k(),await this.loadGroups(e);let g=await m(e,l.LAST_ACTIVE_GROUP);g&&g!==this._activeGroupId.get()&&this._activeGroupId.set(g),await k();let v=await m(e,l.LAST_ACTIVE_PAGE);v&&(this._activePage.set(v),this._hadPersistedActivePage=!0);let y=await m(e,l.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(y));let b=Pt(),x=null;if(b&&(x=o(b)),!x){let t=await m(e,l.DEFAULT_PINNED_PAGE);t&&(x=o(t))}x&&this.isPageAllowed(x.path,x.groupId)&&this._defaultPinnedPage.set(x),await k();let S=typeof window<`u`&&window.history?window.history.state:null,C=!!(S?.inFeedScroll||S?.scrollSpy||S?.suppressRouter)||typeof window<`u`&&window.location&&(()=>{let e=window.location.pathname||`/`,t=a();t!==`/`&&e.startsWith(t)&&(e=`/`+e.slice(t.length));let n=e.split(`/`).filter(Boolean);return n.length===0||n.length===1&&n[0]===`index.html`})(),w=!1;if(C&&x&&this.isPageAllowed(x.path,x.groupId)&&(this._activePinnedPage.set(x),w=!0),!w){let t=await m(e,l.LAST_SELECTED_PINNED_PAGE);if(t)try{let e=JSON.parse(t);e&&typeof e.path==`string`&&typeof e.groupId==`string`&&this.isPageAllowed(e.path,e.groupId)&&(this._activePinnedPage.set(e),w=!0)}catch{}}!w&&C&&this.effectiveDefaultPage&&this.isPageAllowed(this.effectiveDefaultPage.path,this.effectiveDefaultPage.groupId)&&(this._activePinnedPage.set(this.effectiveDefaultPage),w=!0),this.orchestrator&&(this._useProxy.set(this.orchestrator.useProxy),this._proxyUrl.set(this.orchestrator.proxyUrl),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess));let[ee,te,T]=await Promise.all([m(e,l.SIDEBAR_CHAT_HIDDEN),m(e,l.SIDEBAR_TASKS_HIDDEN),m(e,l.SIDEBAR_FILES_HIDDEN)]),E=Z(),ne=E?.sidebar?.chatHidden,re=E?.sidebar?.tasksHidden,D=E?.sidebar?.filesHidden,ie=ee==null?!!ne:oe(ee),ae=te==null?!!re:oe(te),O=T==null?!!D:oe(T),se=()=>{let t=[];(!ie||this.activePage===`chat`)&&t.push(this.loadHistory()),(!ae||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),Promise.all(t).catch(e=>{console.warn(`Secondary background store loads failed:`,e)})};if(d)typeof window.requestIdleCallback==`function`?window.requestIdleCallback(se,{timeout:2e3}):setTimeout(se,100);else{let t=[];(!ie||this.activePage===`chat`)&&t.push(this.loadHistory()),(!ae||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),await Promise.all(t)}await k(),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await C(e));let r=await at(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await M(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await Re(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await v(e),r=n.filter(e=>e.groupId===t);r.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(r);let i=await this.getSubscriberId(e),a=await Xt(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1);if(!a)return;let o=new Set(n.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));if(s.length===0)return;for(let t of s)await P(e,t);let c=[...r,...s];c.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(c)}async navigateBackFolder(e){let t=this._currentPath.get();if(t===`.`)return;let n=t.split(`/`).filter(Boolean);n.pop();let r=n.length===0?`.`:n.join(`/`);await this.setCurrentPath(e,r)}async navigateIntoFolder(e,t){let n=this._currentPath.get(),r=n===`.`?t.replace(/\/$/,``):`${n}/${t.replace(/\/$/,``)}`;try{await this.setCurrentPath(e,r)}catch(t){console.error(`Failed to navigate into folder in store:`,t),O(`Folder not found: ${r}`,4500),await this.loadFiles(e)}}async newSession(e){await this.orchestrator?.newSession?.(e,this._activeGroupId.get()),await this.loadHistory()}async removePage(t,n,r=this._activeGroupId.get()){let i=this.normalizePagePath(n);if(!i)return;let a=this._pages.get();if(!a.some(e=>e.path===i&&e.groupId===r))return;let o=a.filter(e=>e.path!==i||e.groupId!==r);await ft(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await z(t,!0);let l=s||await R(t);if(o.length===0&&!l){if(await B(t,`br:main`))o.push({groupId:c,path:e.DEFAULT_PAGE_PATH});else return}this.setPages(o);let u=this._defaultPinnedPage.get();u&&u.path===i&&u.groupId===r&&await this.setDefaultPinnedPage(t,null),await this.persistPages(t)}async removeAllPages(e){let t=[...this._pages.get()];for(let n of t)await ft(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await z(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await He(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await Ge(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await Ze(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await Q(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync reordered task "${t.id}" to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}async replayTaskSyncOutbox(e){if(!(this._replayingTaskSyncOutbox||this._taskSyncOutbox.length===0)){this._replayingTaskSyncOutbox=!0;try{let t=await this.getSubscriberId(e),n=[];for(let e of this._taskSyncOutbox){let r=this.getTaskServerBaseUrl();(e.type===`upsert`?await Q(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await $(e.id,r,t,this.orchestrator?.taskServerEnabled??!1))||n.push(e)}this._taskSyncOutbox=this.compactTaskSyncOutbox(n),await this.persistTaskSyncOutbox(e)}finally{this._replayingTaskSyncOutbox=!1}}}async resetToRootFolder(e){await this.setCurrentPath(e,`.`)}async restartCurrentRequest(){return this.orchestrator?.restartCurrentRequest?this.orchestrator.restartCurrentRequest(this._activeGroupId.get()):!1}async restoreTasksFromBackup(e,t){await this.clearAllTasks(e);let n=this._activeGroupId.get();for(let r of t){let t={...r,groupId:n,id:crypto.randomUUID?crypto.randomUUID():`task-${Date.now()}-${Math.random()}`};await this.upsertTask(e,t,{reloadTasks:!1})}await this.loadTasks(e)}async runTask(e,t=!1){let n=this._db;if(t&&n&&(await Xe(e.id,Date.now()),await this.loadTasks(n)),e.type===`tools`&&Array.isArray(e.tools)&&e.tools.length>0){if(this.orchestrator?.agentWorker){let n=e.subagent?`subagent:${_()}`:e.groupId;this.orchestrator.agentWorker.postMessage({type:`execute-task-tools`,payload:{groupId:n,tools:e.tools,isManual:t}})}else console.error(`Agent worker not available to execute tool task.`)}else{if(!e.groupId){console.error(`Task ${e.id} has no groupId - refusing to execute in active conversation to prevent context pollution.`);return}this.orchestrator?.browserChat?.submit(e.prompt,e.groupId,[],void 0,e.freshContext,e.subagent)}}async setActivePage(e,t){this._activePage.set(t),await g(e,l.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await g(e,l.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){t&&!this.isPageAllowed(t.path,t.groupId)&&(t=this.effectiveDefaultPage),this._activePinnedPage.set(t),t?await g(e,l.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await g(e,l.LAST_SELECTED_PINNED_PAGE,null)}async setDefaultPinnedPage(e,t){if(t&&!this.isPageAllowed(t.path,t.groupId))return;let n=this._defaultPinnedPage.get(),r=n&&t&&n.path===t.path&&n.groupId===t.groupId?null:t;this._defaultPinnedPage.set(r),r?await g(e,l.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await g(e,l.DEFAULT_PINNED_PAGE,null)}async reorderPages(e,t){this.setPages(t),await this.persistPages(e)}async setCurrentPath(e,t){let n=t.replace(/^\/+|\/+$/g,``)||`.`,r=this._activeGroupId.get();this._storageStatus.set(await C(e));let i=await at(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await be(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await Ce(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await Ae(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await je(this.orchestrator,e,t),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess))}async switchConversation(e,t,n){this.setActiveGroup(e,t,n??this._activePage.get()===`chat`),await g(e,l.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await P(e,r),await this.loadTasks(e),await Q(r,this.getTaskServerBaseUrl(),await this.getSubscriberId(e),this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to update task on server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:r.id,task:r,queuedAt:Date.now()}))}async updateConversationPinnedProvider(e,t,n,r,i){await qe(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await Ye(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await Je(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await Ue(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await P(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await Q(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync task to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}compactTaskSyncOutbox(e){let t=/* @__PURE__ */ new Map;return e.forEach((e,n)=>{t.set(e.id,n)}),e.filter((e,n)=>t.get(e.id)===n)}deriveGroupName(e){return e.startsWith(`tg:`)?`Telegram ${e.slice(3)}`:e.startsWith(`im:`)?`iMessage ${e.slice(3)}`:e.startsWith(`br:`)?e===`br:main`?`Main`:`Browser Conversation`:`Conversation`}getActivityLogSessionStartedAt(e){let t=this._activityLogSessionStartedAtByGroup.get(e);if(t)return t;let n=(/* @__PURE__ */ new Date()).toISOString();return this._activityLogSessionStartedAtByGroup.set(e,n),n}getTaskServerBaseUrl(){return this.orchestrator?.taskServerUrl??`/schedule`}async getSubscriberId(e){if(this._subscriberId)return this._subscriberId;let t=await S(e);return this._subscriberId=t,t}normalizePagePath(t){let n=t.trim().replace(/^\/+/,``).replace(/\/+/g,`/`);return n===`main/memory.md`?e.DEFAULT_PAGE_PATH:n}normalizeSidebarDefaultPage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`}parsePagesList(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{groupId:c,path:this.normalizePagePath(e)};if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.path!=`string`)return null;let n=typeof t.groupId==`string`&&t.groupId.trim().length>0?t.groupId:c,r=n===`br:main`?this.normalizePagePath(t.path):t.path.trim();return r?{groupId:n,path:r}:null}).filter(e=>!!e).filter((e,t,n)=>{let r=`${e.groupId}\u0000${e.path}`;return t===n.findIndex(e=>`${e.groupId}\u0000${e.path}`===r)}):[]}catch{return[]}}parseTaskSyncOutbox(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>!!e&&typeof e==`object`).filter(e=>e.type===`upsert`||e.type===`delete`).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({...e,queuedAt:typeof e.queuedAt==`number`?e.queuedAt:Date.now()}));return this.compactTaskSyncOutbox(n)}catch{return[]}}resolveSidebarDefaultPageForActivePage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:this._sidebarDefaultPage.get()}setPages(e){let t=e.filter(e=>this.isPageAllowed(e.path,e.groupId)),n=t.filter(e=>e.path.toLowerCase()===`memory.md`),r=t.filter(e=>e.path.toLowerCase()!==`memory.md`);this._pages.set([...r,...n])}async ensureDefaultPage(t){if(await R(t))return;let n=await B(t,c);await I(t,c),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:c,path:e.DEFAULT_PAGE_PATH}]),await this.persistPages(t))}async ensureGroupExists(e,t,n){let r=this._groups.get();if(r.some(e=>e.groupId===t))return;let i=[...r,{groupId:t,name:this.deriveGroupName(t),createdAt:n||Date.now()}];this._groups.set(i);try{await j(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!Jt(await m(this._db,l.ACTIVITY_LOG_DISK_LOGGING_ENABLED)))return;let t=typeof e.groupId==`string`&&e.groupId?e.groupId:this._activeGroupId.get();if(!t)return;let n=typeof e.message==`string`?e.message.trim():``;if(!n)return;e.level===`info`&&e.label===`Starting`&&this._activityLogSessionStartedAtByGroup.set(t,(/* @__PURE__ */ new Date()).toISOString());let r=this.getActivityLogSessionStartedAt(t);try{await fetch(`/activity-log`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({groupId:t,level:e.level,label:e.label,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString(),sessionStartedAt:r})})}catch(e){console.warn(`Failed to persist activity log entry to server:`,e)}}scheduleBackgroundStaticMainSiteSeeding(e){if(typeof window>`u`)return;let t=async()=>{try{if(await Ct(e,`br:main`))return;let t=await m(e,l.PAGES_LIST),n=t==null?[]:this.parsePagesList(t),r=await zt(e,c,n,{preferEmbedded:!1});r&&r.length>0&&(this.setPages(r),await this.persistPages(e))}catch(e){console.warn(`Background static main site seeding failed:`,e)}};typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:3e3}):setTimeout(()=>void t(),100)}async persistPages(e){await g(e,l.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await g(e,l.TASK_SYNC_OUTBOX,JSON.stringify(this._taskSyncOutbox))}async queueTaskSyncOutboxOperation(e,t){this._taskSyncOutbox=this.compactTaskSyncOutbox([...this._taskSyncOutbox,t]),await this.persistTaskSyncOutbox(e)}async applySiteConfigDefaults(e){if(typeof document<`u`)try{let r=Z();if(!r||typeof r!=`object`)return;i(r),t(),n();let a=r.customElements;if((await M(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await Ue(e,c,void 0),(r.settings?.internetAccess??r.settings?.vm_bash_full_internet_access??r.settings?.fullInternetAccess??r.internetAccess)===!0&&await m(e,l.VM_BASH_FULL_INTERNET_ACCESS)!==`true`&&(await g(e,l.VM_BASH_FULL_INTERNET_ACCESS,`true`),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=!0),this._vmBashFullInternetAccess.set(!0)),r.pages&&typeof r.pages==`object`){let{defaultPinnedPage:t}=r.pages;if(t&&typeof t==`string`){let n=o(t);n&&this.isPageAllowed(n.path,n.groupId)&&(this._defaultPinnedPage.set(n),await g(e,l.DEFAULT_PINNED_PAGE,JSON.stringify(n)))}}let s=r.allowedCustomElements||(typeof a==`object`&&!Array.isArray(a)?a.allowedElements:void 0);s!==void 0&&(await m(e,l.ALLOWED_CUSTOM_ELEMENTS)??await g(e,l.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(s)));let u=r.allowedCustomElementDomains||(typeof a==`object`&&!Array.isArray(a)?a.allowedDomains:void 0);if(u!==void 0&&(await m(e,l.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS)??await g(e,l.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(u))),r.sidebar&&typeof r.sidebar==`object`){let{pagesHidden:t,chatHidden:n,tasksHidden:i,filesHidden:a,defaultPage:o}=r.sidebar;if(t!==void 0&&(await m(e,l.SIDEBAR_PAGES_HIDDEN)??await g(e,l.SIDEBAR_PAGES_HIDDEN,String(!!t))),n!==void 0&&(await m(e,l.SIDEBAR_CHAT_HIDDEN)??await g(e,l.SIDEBAR_CHAT_HIDDEN,String(!!n))),i!==void 0&&(await m(e,l.SIDEBAR_TASKS_HIDDEN)??await g(e,l.SIDEBAR_TASKS_HIDDEN,String(!!i))),a!==void 0&&(await m(e,l.SIDEBAR_FILES_HIDDEN)??await g(e,l.SIDEBAR_FILES_HIDDEN,String(!!a))),o&&typeof o==`string`){let t=this.normalizeSidebarDefaultPage(o);this._sidebarDefaultPage.set(t),await m(e,l.SIDEBAR_DEFAULT_PAGE)||await g(e,l.SIDEBAR_DEFAULT_PAGE,o)}}if(r.settings&&typeof r.settings==`object`){let{assistantName:t,defaultProvider:n,provider:i,defaultModel:a,model:o}=r.settings;t&&typeof t==`string`&&(await m(e,l.ASSISTANT_NAME)||await g(e,l.ASSISTANT_NAME,t));let s=n??i;if(typeof s==`string`&&s.trim().length>0&&!await m(e,l.PROVIDER)){let t=s.trim();await g(e,l.PROVIDER,t),this.orchestrator&&(this.orchestrator.provider=t)}let c=a??o;if(typeof c==`string`&&c.trim().length>0&&!await m(e,l.MODEL)){let t=c.trim();await g(e,l.MODEL,t),this.orchestrator&&(this.orchestrator.model=t)}let u=r.settings.internetAccess??r.settings.vm_bash_full_internet_access??r.settings.fullInternetAccess??r.internetAccess;typeof u==`boolean`&&(await m(e,l.VM_BASH_FULL_INTERNET_ACCESS)??(await g(e,l.VM_BASH_FULL_INTERNET_ACCESS,String(u)),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=u),this._vmBashFullInternetAccess.set(u)))}let d=(r.settings&&typeof r.settings==`object`?r.settings.defaultToolsProfile:void 0)??r.defaultToolsProfile;if(typeof d==`string`&&d.trim().length>0&&!await m(e,l.ACTIVE_TOOL_PROFILE)){let t=d.trim();if(t.toLowerCase()===`none`)await x.deactivateProfile(e);else{let n=x.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await x.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(r.pages&&typeof r.pages==`object`){let{defaultPinnedPage:t}=r.pages;t&&typeof t==`string`&&(await m(e,l.DEFAULT_PINNED_PAGE)||await g(e,l.DEFAULT_PINNED_PAGE,t))}let f=r.pages?.allowList??r.pages?.allowlist??r.allowList??r.allowlist,p=r.pages?.denyList??r.pages?.denylist??r.denyList??r.denylist;if(Array.isArray(f)&&await m(e,l.PAGES_ALLOW_LIST)==null){let t=K(f.map(String));this._pagesAllowList.set(t),await g(e,l.PAGES_ALLOW_LIST,JSON.stringify(t))}if(Array.isArray(p)&&await m(e,l.PAGES_DENY_LIST)==null){let t=K(p.map(String));this._pagesDenyList.set(t),await g(e,l.PAGES_DENY_LIST,JSON.stringify(t))}await g(e,l.SITE_CONFIG_SEEDED,`true`);let h=this._pages.get(),_=h.filter(e=>this.isPageAllowed(e.path,e.groupId));_.length!==h.length&&(this.setPages(_),await this.persistPages(e));let v=this._activePinnedPage.get();v&&!this.isPageAllowed(v.path,v.groupId)&&await this.setActivePinnedPage(e,this.effectiveDefaultPage);let y=this._defaultPinnedPage.get();if(y&&!this.isPageAllowed(y.path,y.groupId)&&await this.setDefaultPinnedPage(e,null),Array.isArray(r.enabledTools)){let t=r.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await x.setAllEnabled(e,t),await x.setAllDeclarativeEnabled(e,t)}await g(e,l.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const $t=new Qt;export{ye as A,Ae as B,N as C,Re as D,M as E,Te as F,le as G,ve as H,Ee as I,he as J,de as K,De as L,Se as M,Ce as N,Le as O,we as P,k as Q,Oe as R,P as S,A as T,me as U,Me as V,ue as W,se as X,_e as Y,ce as Z,B as _,Pt as a,nt as b,K as c,U as d,ct as f,at as g,H as h,Gt as i,xe as j,Ne as k,ft as l,lt as m,Kt as n,Ft as o,V as p,ge as q,Z as r,jt as s,$t as t,W as u,z as v,Ve as w,Xe as x,I as y,ke as z};