shadow-claw 1.59.6 → 1.59.7

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 (324) hide show
  1. package/.well-known/mcp/server-card.json +12 -4
  2. package/.well-known/mcp.json +12 -4
  3. package/dist/cli/build/build.js +1 -1
  4. package/dist/cli/{chunk-DM4xsTry.js → chunk-3vNYrs_L.js} +1 -1
  5. package/dist/cli/{chunk-Ctg5L55n.js → chunk-66BvqAV0.js} +1 -1
  6. package/dist/cli/{chunk-Bq38OubR.js → chunk-B0qusANw.js} +1 -1
  7. package/dist/cli/{chunk-yiVdvGCJ.js → chunk-B3TrWbca.js} +7 -7
  8. package/dist/cli/{chunk-C8DBACtx.js → chunk-B88Z8T_9.js} +1 -1
  9. package/dist/cli/chunk-BCjL0JXf.js +1 -0
  10. package/dist/cli/chunk-BNcu1oiT.js +1 -0
  11. package/dist/cli/{chunk-gvNsvav0.js → chunk-C5ypckWC.js} +7 -7
  12. package/dist/cli/{chunk-Dw8GndPD.js → chunk-CAAeGOdy.js} +1 -1
  13. package/dist/cli/chunk-CFxww5Yz.js +1 -0
  14. package/dist/cli/chunk-CGIgtL6R.js +1 -0
  15. package/dist/cli/{chunk-DJqHK-qS.js → chunk-CQaCgswD.js} +7 -7
  16. package/dist/cli/chunk-CZdCRqNe.js +7 -0
  17. package/dist/cli/chunk-CafdvLx-.js +1 -0
  18. package/dist/cli/{chunk-Bc_weULz.js → chunk-CncW6_WL.js} +1 -1
  19. package/dist/cli/chunk-DDvuLVfW.js +1 -0
  20. package/dist/cli/{chunk-Cq_kQohv.js → chunk-DMs7kREC.js} +1 -1
  21. package/dist/cli/{chunk-CX2itile.js → chunk-D_te8ufL.js} +1 -1
  22. package/dist/cli/{chunk-3wTukVof.js → chunk-DhOU6GYX.js} +1 -1
  23. package/dist/cli/chunk-Dhap1VwA.js +1 -0
  24. package/dist/cli/chunk-DwvavohW.js +1 -0
  25. package/dist/cli/{chunk-DLde6nuO.js → chunk-SRBRVorc.js} +1 -1
  26. package/dist/cli/{chunk-D3y7h9Xe.js → chunk-SxK79JmB.js} +1 -1
  27. package/dist/cli/chunk-_a0CkUNS.js +139 -0
  28. package/dist/cli/{chunk-C9o6lXP3.js → chunk-hVf839t7.js} +1 -1
  29. package/dist/cli/chunk-iB8OoMmW.js +7 -0
  30. package/dist/cli/cli.js +1 -1
  31. package/dist/headless-agent.js +1 -1
  32. package/dist/lib/{app-routes-DJdIjp2V.js → app-routes-BXiRvlNl.js} +7 -25
  33. package/dist/lib/{app-routes-DJdIjp2V.js.map → app-routes-BXiRvlNl.js.map} +1 -1
  34. package/dist/lib/{attachment-capabilities-Dbb-4ZP5.js → attachment-capabilities-BjkEPip8.js} +2 -2
  35. package/dist/lib/{attachment-capabilities-Dbb-4ZP5.js.map → attachment-capabilities-BjkEPip8.js.map} +1 -1
  36. package/dist/lib/{channel-Dlru5ofR.js → channel-mmdGzPkT.js} +3 -3
  37. package/dist/lib/{channel-Dlru5ofR.js.map → channel-mmdGzPkT.js.map} +1 -1
  38. package/dist/lib/{chat-template-BuuLY8l7.js → chat-template-DPEKGJhB.js} +2 -2
  39. package/dist/lib/{chat-template-BuuLY8l7.js.map → chat-template-DPEKGJhB.js.map} +1 -1
  40. package/dist/lib/{compact-context-BtR55YPU.js → compact-context-CY9BBlUQ.js} +19 -19
  41. package/dist/lib/{compact-context-BtR55YPU.js.map → compact-context-CY9BBlUQ.js.map} +1 -1
  42. package/dist/lib/components/common/shadow-claw-provider-model-picker.js +1 -1
  43. package/dist/lib/components/index.js +27 -27
  44. package/dist/lib/components/settings/shadow-claw-accounts.js +1 -1
  45. package/dist/lib/components/settings/shadow-claw-channel-config.js +1 -1
  46. package/dist/lib/components/settings/shadow-claw-control-plane.js +1 -1
  47. package/dist/lib/components/settings/shadow-claw-git.js +1 -1
  48. package/dist/lib/components/settings/shadow-claw-integrations.js +1 -1
  49. package/dist/lib/components/settings/shadow-claw-llm.js +1 -1
  50. package/dist/lib/components/settings/shadow-claw-mcp-remote.js +1 -1
  51. package/dist/lib/components/settings/shadow-claw-networking.js +1 -1
  52. package/dist/lib/components/settings/shadow-claw-notifications.js +1 -1
  53. package/dist/lib/components/settings/shadow-claw-peerjs.js +1 -1
  54. package/dist/lib/components/settings/shadow-claw-storage.js +1 -1
  55. package/dist/lib/components/settings/shadow-claw-task-server.js +1 -1
  56. package/dist/lib/components/settings/shadow-claw-webvm.js +1 -1
  57. package/dist/lib/components/shadow-claw-a2ui.js +1 -1
  58. package/dist/lib/components/shadow-claw-accounts.js +1 -1
  59. package/dist/lib/components/shadow-claw-channel-config.js +1 -1
  60. package/dist/lib/components/shadow-claw-channels.js +1 -1
  61. package/dist/lib/components/shadow-claw-chat.js +1 -1
  62. package/dist/lib/components/shadow-claw-control-plane.js +1 -1
  63. package/dist/lib/components/shadow-claw-conversations.js +1 -1
  64. package/dist/lib/components/shadow-claw-file-viewer.js +1 -1
  65. package/dist/lib/components/shadow-claw-files.js +1 -1
  66. package/dist/lib/components/shadow-claw-git.js +1 -1
  67. package/dist/lib/components/shadow-claw-integrations.js +1 -1
  68. package/dist/lib/components/shadow-claw-llm.js +1 -1
  69. package/dist/lib/components/shadow-claw-mcp-remote.js +1 -1
  70. package/dist/lib/components/shadow-claw-networking.js +1 -1
  71. package/dist/lib/components/shadow-claw-notifications.js +1 -1
  72. package/dist/lib/components/shadow-claw-page-header.js +1 -1
  73. package/dist/lib/components/shadow-claw-pages.js +1 -1
  74. package/dist/lib/components/shadow-claw-peerjs.js +1 -1
  75. package/dist/lib/components/shadow-claw-provider-model-picker.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/{config-DxNI3TlW.js → config-BrHR97zt.js} +2 -2
  85. package/dist/lib/{config-DxNI3TlW.js.map → config-BrHR97zt.js.map} +1 -1
  86. package/dist/lib/{configure-peer-js-ChDhOZU4.js → configure-peer-js-ccNvax2N.js} +3 -3
  87. package/dist/lib/{configure-peer-js-ChDhOZU4.js.map → configure-peer-js-ccNvax2N.js.map} +1 -1
  88. package/dist/lib/{connections-DC4NZkJE.js → connections-C1FWsBsE.js} +2 -2
  89. package/dist/lib/{connections-DC4NZkJE.js.map → connections-C1FWsBsE.js.map} +1 -1
  90. package/dist/lib/{credentials-5vpz0XPk.js → credentials-CZbngHXW.js} +2 -2
  91. package/dist/lib/{credentials-5vpz0XPk.js.map → credentials-CZbngHXW.js.map} +1 -1
  92. package/dist/lib/{discover-skills-CD0sKvAI.js → discover-skills-OwlQ2sXA.js} +13 -13
  93. package/dist/lib/{discover-skills-CD0sKvAI.js.map → discover-skills-OwlQ2sXA.js.map} +1 -1
  94. package/dist/lib/{download-group-file-Dk3qaxhJ.js → download-group-file-D0wgg10Q.js} +2 -2
  95. package/dist/lib/{download-group-file-Dk3qaxhJ.js.map → download-group-file-D0wgg10Q.js.map} +1 -1
  96. package/dist/lib/{file-viewer-B4pRW-_G.js → file-viewer-DOfvX6yy.js} +5 -5
  97. package/dist/lib/{file-viewer-B4pRW-_G.js.map → file-viewer-DOfvX6yy.js.map} +1 -1
  98. package/dist/lib/{get-or-create-subscriber-id-HCcgDEPz.js → get-or-create-subscriber-id-wyzaML7Z.js} +2 -2
  99. package/dist/lib/{get-or-create-subscriber-id-HCcgDEPz.js.map → get-or-create-subscriber-id-wyzaML7Z.js.map} +1 -1
  100. package/dist/lib/{git-B3Q1euc5.js → git-D2J_j9X9.js} +5 -5
  101. package/dist/lib/{git-B3Q1euc5.js.map → git-D2J_j9X9.js.map} +1 -1
  102. package/dist/lib/{iframe-bridge-scripts-D8iuFhUk.js → iframe-bridge-scripts-Dx825LLG.js} +2 -2
  103. package/dist/lib/{iframe-bridge-scripts-D8iuFhUk.js.map → iframe-bridge-scripts-Dx825LLG.js.map} +1 -1
  104. package/dist/lib/index.js +28 -28
  105. package/dist/lib/{init-chat-split-resize-B0ODULx9.js → init-chat-split-resize-Cc0bd2z9.js} +2 -2
  106. package/dist/lib/{init-chat-split-resize-B0ODULx9.js.map → init-chat-split-resize-Cc0bd2z9.js.map} +1 -1
  107. package/dist/lib/{init-control-plane-C1FRRmjC.js → init-control-plane-B7blDVIE.js} +15 -15
  108. package/dist/lib/{init-control-plane-C1FRRmjC.js.map → init-control-plane-B7blDVIE.js.map} +1 -1
  109. package/dist/lib/{invoke-agent-CzN7sVh-.js → invoke-agent-SxvudiDT.js} +11 -11
  110. package/dist/lib/{invoke-agent-CzN7sVh-.js.map → invoke-agent-SxvudiDT.js.map} +1 -1
  111. package/dist/lib/{markdown-mbNo7cV3.js → markdown--6vTAPEH.js} +2 -2
  112. package/dist/lib/{markdown-mbNo7cV3.js.map → markdown--6vTAPEH.js.map} +1 -1
  113. package/dist/lib/{mcp-reconnect-3T7yWGEY.js → mcp-reconnect-BeqQvNWO.js} +3 -3
  114. package/dist/lib/{mcp-reconnect-3T7yWGEY.js.map → mcp-reconnect-BeqQvNWO.js.map} +1 -1
  115. package/dist/lib/{model-ranking-DGNSWYwN.js → model-ranking-BhsJV7vb.js} +2 -2
  116. package/dist/lib/{model-ranking-DGNSWYwN.js.map → model-ranking-BhsJV7vb.js.map} +1 -1
  117. package/dist/lib/{move-group-entry-NMTJ59M9.js → move-group-entry-DDpjxa10.js} +5 -5
  118. package/dist/lib/{move-group-entry-NMTJ59M9.js.map → move-group-entry-DDpjxa10.js.map} +1 -1
  119. package/dist/lib/{orchestrator-B8FV1V7x.js → orchestrator-C7fkh7T7.js} +24 -24
  120. package/dist/lib/{orchestrator-B8FV1V7x.js.map → orchestrator-C7fkh7T7.js.map} +1 -1
  121. package/dist/lib/{orchestrator-i_QJ-o22.js → orchestrator-CCARkxQC.js} +11 -11
  122. package/dist/lib/orchestrator-CCARkxQC.js.map +1 -0
  123. package/dist/lib/{parse-path-DPCn-HwI.js → parse-path-BOHQP_IQ.js} +3 -3
  124. package/dist/lib/{parse-path-DPCn-HwI.js.map → parse-path-BOHQP_IQ.js.map} +1 -1
  125. package/dist/lib/{peerjs-z5zeioPV.js → peerjs-Bfw_FWLB.js} +8 -8
  126. package/dist/lib/{peerjs-z5zeioPV.js.map → peerjs-Bfw_FWLB.js.map} +1 -1
  127. package/dist/lib/{process-peer-query-param-CJp7w7AU.js → process-peer-query-param-BxYiZNdf.js} +5 -5
  128. package/dist/lib/{process-peer-query-param-CJp7w7AU.js.map → process-peer-query-param-BxYiZNdf.js.map} +1 -1
  129. package/dist/lib/{process-pending-shared-payloads-B6_TlBFA.js → process-pending-shared-payloads-DPIbwRb3.js} +4 -4
  130. package/dist/lib/{process-pending-shared-payloads-B6_TlBFA.js.map → process-pending-shared-payloads-DPIbwRb3.js.map} +1 -1
  131. package/dist/lib/{process-room-query-param-C3FFGGn6.js → process-room-query-param-B2_d50nE.js} +4 -4
  132. package/dist/lib/{process-room-query-param-C3FFGGn6.js.map → process-room-query-param-B2_d50nE.js.map} +1 -1
  133. package/dist/lib/{provider-DcQZypu5.js → provider-BC9KPI14.js} +3 -3
  134. package/dist/lib/{provider-DcQZypu5.js.map → provider-BC9KPI14.js.map} +1 -1
  135. package/dist/lib/{push-client-Cx5rMs6J.js → push-client-rrjTdc-U.js} +5 -5
  136. package/dist/lib/{push-client-Cx5rMs6J.js.map → push-client-rrjTdc-U.js.map} +1 -1
  137. package/dist/lib/{read-group-file-bytes-CXOG_YyM.js → read-group-file-bytes-UQIk1eJG.js} +2 -2
  138. package/dist/lib/{read-group-file-bytes-CXOG_YyM.js.map → read-group-file-bytes-UQIk1eJG.js.map} +1 -1
  139. package/dist/lib/{rooms-CwlkYLDU.js → rooms-bwGoYb1q.js} +2 -2
  140. package/dist/lib/{rooms-CwlkYLDU.js.map → rooms-bwGoYb1q.js.map} +1 -1
  141. package/dist/lib/{shadow-claw-DoQ7fgl5.js → shadow-claw-CypGVlVO.js} +17 -20
  142. package/dist/lib/shadow-claw-CypGVlVO.js.map +1 -0
  143. package/dist/lib/{shadow-claw-a2ui-Br6qJMs1.js → shadow-claw-a2ui-lG0vQbW8.js} +2 -2
  144. package/dist/lib/{shadow-claw-a2ui-Br6qJMs1.js.map → shadow-claw-a2ui-lG0vQbW8.js.map} +1 -1
  145. package/dist/lib/{shadow-claw-accounts-BTDILfWw.js → shadow-claw-accounts-CkqyCxwp.js} +3 -3
  146. package/dist/lib/{shadow-claw-accounts-BTDILfWw.js.map → shadow-claw-accounts-CkqyCxwp.js.map} +1 -1
  147. package/dist/lib/{shadow-claw-channel-config-IKiL34tI.js → shadow-claw-channel-config-DJpDovkF.js} +4 -4
  148. package/dist/lib/{shadow-claw-channel-config-IKiL34tI.js.map → shadow-claw-channel-config-DJpDovkF.js.map} +1 -1
  149. package/dist/lib/{shadow-claw-channels-JgEzuHWK.js → shadow-claw-channels-DJLwRovH.js} +3 -3
  150. package/dist/lib/{shadow-claw-channels-JgEzuHWK.js.map → shadow-claw-channels-DJLwRovH.js.map} +1 -1
  151. package/dist/lib/{shadow-claw-chat-SGUDT31r.js → shadow-claw-chat-B92cPaft.js} +15 -15
  152. package/dist/lib/{shadow-claw-chat-SGUDT31r.js.map → shadow-claw-chat-B92cPaft.js.map} +1 -1
  153. package/dist/lib/{shadow-claw-control-plane-CRWFZ3vD.js → shadow-claw-control-plane-fvn-qyHj.js} +7 -7
  154. package/dist/lib/{shadow-claw-control-plane-CRWFZ3vD.js.map → shadow-claw-control-plane-fvn-qyHj.js.map} +1 -1
  155. package/dist/lib/{shadow-claw-conversations-D23GJ7qo.js → shadow-claw-conversations-CsVyDOny.js} +7 -7
  156. package/dist/lib/{shadow-claw-conversations-D23GJ7qo.js.map → shadow-claw-conversations-CsVyDOny.js.map} +1 -1
  157. package/dist/lib/{shadow-claw-file-viewer-C1V8WTiU.js → shadow-claw-file-viewer-DFfyP7s5.js} +10 -10
  158. package/dist/lib/{shadow-claw-file-viewer-C1V8WTiU.js.map → shadow-claw-file-viewer-DFfyP7s5.js.map} +1 -1
  159. package/dist/lib/{shadow-claw-files-DN7irmE1.js → shadow-claw-files-cT6HL7ye.js} +11 -11
  160. package/dist/lib/{shadow-claw-files-DN7irmE1.js.map → shadow-claw-files-cT6HL7ye.js.map} +1 -1
  161. package/dist/lib/{shadow-claw-git-D-1oIh65.js → shadow-claw-git-Cv9mQgTx.js} +6 -6
  162. package/dist/lib/{shadow-claw-git-D-1oIh65.js.map → shadow-claw-git-Cv9mQgTx.js.map} +1 -1
  163. package/dist/lib/{shadow-claw-integrations-CZjnm7cM.js → shadow-claw-integrations-RZZ-m-Id.js} +4 -4
  164. package/dist/lib/{shadow-claw-integrations-CZjnm7cM.js.map → shadow-claw-integrations-RZZ-m-Id.js.map} +1 -1
  165. package/dist/lib/{shadow-claw-llm-4Gefh5FN.js → shadow-claw-llm-CKOYzPDp.js} +9 -9
  166. package/dist/lib/{shadow-claw-llm-4Gefh5FN.js.map → shadow-claw-llm-CKOYzPDp.js.map} +1 -1
  167. package/dist/lib/{shadow-claw-mcp-remote-B9ssb3YV.js → shadow-claw-mcp-remote-BKFROurv.js} +4 -4
  168. package/dist/lib/{shadow-claw-mcp-remote-B9ssb3YV.js.map → shadow-claw-mcp-remote-BKFROurv.js.map} +1 -1
  169. package/dist/lib/{shadow-claw-networking-BN5BB4hb.js → shadow-claw-networking-DYfiUQaH.js} +2 -2
  170. package/dist/lib/{shadow-claw-networking-BN5BB4hb.js.map → shadow-claw-networking-DYfiUQaH.js.map} +1 -1
  171. package/dist/lib/{shadow-claw-notifications-71KARtkY.js → shadow-claw-notifications-JJlzriuX.js} +3 -3
  172. package/dist/lib/{shadow-claw-notifications-71KARtkY.js.map → shadow-claw-notifications-JJlzriuX.js.map} +1 -1
  173. package/dist/lib/{shadow-claw-page-header-DMGO-TSe.js → shadow-claw-page-header-C_Qr3xZM.js} +2 -2
  174. package/dist/lib/{shadow-claw-page-header-DMGO-TSe.js.map → shadow-claw-page-header-C_Qr3xZM.js.map} +1 -1
  175. package/dist/lib/{shadow-claw-pages-BiRM6qiA.js → shadow-claw-pages-BCo3ihZI.js} +11 -11
  176. package/dist/lib/{shadow-claw-pages-BiRM6qiA.js.map → shadow-claw-pages-BCo3ihZI.js.map} +1 -1
  177. package/dist/lib/{shadow-claw-peerjs-BZu7jNSe.js → shadow-claw-peerjs-CFNjfrY5.js} +6 -6
  178. package/dist/lib/{shadow-claw-peerjs-BZu7jNSe.js.map → shadow-claw-peerjs-CFNjfrY5.js.map} +1 -1
  179. package/dist/lib/{shadow-claw-provider-model-picker-BXYXEobD.js → shadow-claw-provider-model-picker-B-Ct4yW-.js} +2 -2
  180. package/dist/lib/{shadow-claw-provider-model-picker-BXYXEobD.js.map → shadow-claw-provider-model-picker-B-Ct4yW-.js.map} +1 -1
  181. package/dist/lib/{shadow-claw-settings-CcT5EK08.js → shadow-claw-settings-BMwne0bh.js} +7 -7
  182. package/dist/lib/{shadow-claw-settings-CcT5EK08.js.map → shadow-claw-settings-BMwne0bh.js.map} +1 -1
  183. package/dist/lib/{shadow-claw-storage-eTOpbvpi.js → shadow-claw-storage-DUY8B9m-.js} +5 -5
  184. package/dist/lib/{shadow-claw-storage-eTOpbvpi.js.map → shadow-claw-storage-DUY8B9m-.js.map} +1 -1
  185. package/dist/lib/{shadow-claw-task-server-DFImTUbw.js → shadow-claw-task-server-yWeoA3eL.js} +2 -2
  186. package/dist/lib/{shadow-claw-task-server-DFImTUbw.js.map → shadow-claw-task-server-yWeoA3eL.js.map} +1 -1
  187. package/dist/lib/{shadow-claw-tasks-BjaxsmUx.js → shadow-claw-tasks-Bg0uM15I.js} +9 -9
  188. package/dist/lib/{shadow-claw-tasks-BjaxsmUx.js.map → shadow-claw-tasks-Bg0uM15I.js.map} +1 -1
  189. package/dist/lib/{shadow-claw-terminal-C-4wreFe.js → shadow-claw-terminal-fyJPppY_.js} +2 -2
  190. package/dist/lib/{shadow-claw-terminal-C-4wreFe.js.map → shadow-claw-terminal-fyJPppY_.js.map} +1 -1
  191. package/dist/lib/{shadow-claw-tools-COdrGZJk.js → shadow-claw-tools-D0T8m3go.js} +7 -7
  192. package/dist/lib/{shadow-claw-tools-COdrGZJk.js.map → shadow-claw-tools-D0T8m3go.js.map} +1 -1
  193. package/dist/lib/{shadow-claw-webvm-sxqVjO0L.js → shadow-claw-webvm-CQvzJwKI.js} +3 -3
  194. package/dist/lib/{shadow-claw-webvm-sxqVjO0L.js.map → shadow-claw-webvm-CQvzJwKI.js.map} +1 -1
  195. package/dist/lib/{sync-web-mcp-registration-D4hdUwtv.js → sync-web-mcp-registration-BFtG_4kx.js} +6 -6
  196. package/dist/lib/{sync-web-mcp-registration-D4hdUwtv.js.map → sync-web-mcp-registration-BFtG_4kx.js.map} +1 -1
  197. package/dist/lib/{system-prompt-DT_KeYaL.js → system-prompt-bhGRLoL2.js} +7 -7
  198. package/dist/lib/{system-prompt-DT_KeYaL.js.map → system-prompt-bhGRLoL2.js.map} +1 -1
  199. package/dist/lib/{tools-Beuyh8y1.js → tools-B8OJ4sMF.js} +4 -4
  200. package/dist/lib/{tools-Beuyh8y1.js.map → tools-B8OJ4sMF.js.map} +1 -1
  201. package/dist/lib/{transformers-DydnReu4.js → transformers-BMURofG6.js} +2 -2
  202. package/dist/lib/{transformers-DydnReu4.js.map → transformers-BMURofG6.js.map} +1 -1
  203. package/dist/lib/{trusted-types-CfwZl_rr.js → trusted-types-HwsGS5Nj.js} +19 -17
  204. package/dist/lib/{trusted-types-CfwZl_rr.js.map → trusted-types-HwsGS5Nj.js.map} +1 -1
  205. package/dist/lib/{upload-group-file-BbBzjTcN.js → upload-group-file-CJpoNjEb.js} +3 -3
  206. package/dist/lib/{upload-group-file-BbBzjTcN.js.map → upload-group-file-CJpoNjEb.js.map} +1 -1
  207. package/dist/lib/utils/index.js +1 -1
  208. package/dist/lib/utils/namespaced-storage.js +1 -1
  209. package/dist/lib/utils/runtime-assets.js +1 -1
  210. package/dist/lib/utils/utils.js +1 -1
  211. package/dist/lib/{webmcp-DCfAFiIO.js → webmcp-BoMTvgmX.js} +3 -3
  212. package/dist/lib/{webmcp-DCfAFiIO.js.map → webmcp-BoMTvgmX.js.map} +1 -1
  213. package/dist/lib/{write-group-file-bytes-Ccn-VFUU.js → write-group-file-bytes-CNT7DqOZ.js} +3 -3
  214. package/dist/lib/{write-group-file-bytes-Ccn-VFUU.js.map → write-group-file-bytes-CNT7DqOZ.js.map} +1 -1
  215. package/dist/public/.well-known/mcp/server-card.json +12 -4
  216. package/dist/public/.well-known/mcp.json +12 -4
  217. package/dist/public/agent.worker.js +1 -1
  218. package/dist/public/attachment-capabilities-AdwXt3--.js +1 -0
  219. package/dist/public/{channel-BylT3rJC.js → channel-Dk7wl-Av.js} +1 -1
  220. package/dist/public/{chat-template-DPHJy7tr.js → chat-template-BwAnTFKf.js} +1 -1
  221. package/dist/public/{compact-context-BINQh64w.js → compact-context-fOTqwKF6.js} +2 -2
  222. package/dist/public/config-C16fFWtP.js +1 -0
  223. package/dist/public/{configure-peer-js-DChhcOfe.js → configure-peer-js-BOV0tR6G.js} +1 -1
  224. package/dist/public/{connections-CHaw0VqP.js → connections-Dxwj8yK_.js} +1 -1
  225. package/dist/public/{create-model-cache-fetch-DQebkoPL.js → create-model-cache-fetch-DSAFjOwc.js} +1 -1
  226. package/dist/public/{credentials-CgVqS119.js → credentials-CJUQ5Ep2.js} +1 -1
  227. package/dist/public/{custom-element-security-kiDhPfb8.js → custom-element-security-B2daIE5r.js} +2 -2
  228. package/dist/public/{discover-skills-Cvmx5I9V.js → discover-skills-D1sNTy2r.js} +6 -6
  229. package/dist/public/docs/example/article/index.html +28 -29
  230. package/dist/public/docs/example/article.html +28 -29
  231. package/dist/public/docs/publishing/index.html +28 -29
  232. package/dist/public/docs/publishing.html +28 -29
  233. package/dist/public/docs/skill-creator/index.html +28 -29
  234. package/dist/public/docs/skill-creator.html +28 -29
  235. package/dist/public/{download-group-file-BapoRgfU.js → download-group-file-BkMH-JKi.js} +1 -1
  236. package/dist/public/{e2e-bridge-C0g8vZKr.js → e2e-bridge-Cz95DLlb.js} +1 -1
  237. package/dist/public/get-group-dir-D--BiEyk.js +1 -0
  238. package/dist/public/{get-or-create-subscriber-id-GvRZYXwA.js → get-or-create-subscriber-id-jVHnQfbr.js} +1 -1
  239. package/dist/public/{git-CaAAZfVd.js → git-BmMlwIMP.js} +2 -2
  240. package/dist/public/{iframe-bridge-scripts-BnqtKhE4.js → iframe-bridge-scripts-Cibg0m6A.js} +1 -1
  241. package/dist/public/index.html +28 -29
  242. package/dist/public/index.js +1 -1
  243. package/dist/public/{init-chat-split-resize-Btonoy8u.js → init-chat-split-resize-C8AqCCiK.js} +1 -1
  244. package/dist/public/init-control-plane-Cb31yLTY.js +1 -0
  245. package/dist/public/{invoke-agent-B3Osw6K7.js → invoke-agent-CN7mSV0Z.js} +1 -1
  246. package/dist/public/main/index.html +28 -29
  247. package/dist/public/main/memory/index.html +28 -29
  248. package/dist/public/main/memory.html +28 -29
  249. package/dist/public/main.html +28 -29
  250. package/dist/public/{markdown-CPbU4r1U.js → markdown-CDSb5Hrl.js} +1 -1
  251. package/dist/public/{mcp-reconnect-CzROVsXG.js → mcp-reconnect-iPZPihwX.js} +1 -1
  252. package/dist/public/{memory-storage-BkoMlxOr.js → memory-storage-2m7KZ-aP.js} +1 -1
  253. package/dist/public/{model-ranking-CK0iBo3Z.js → model-ranking-BgOSaNIy.js} +1 -1
  254. package/dist/public/{move-group-entry-CTxoq7lw.js → move-group-entry-CXneuNVa.js} +1 -1
  255. package/dist/public/orchestrator-DBO4NZqd.js +63 -0
  256. package/dist/public/{orchestrator-BrDjQbGf.js → orchestrator-Dyylc8IU.js} +2 -2
  257. package/dist/public/{peerjs-CgF4Iz5W.js → peerjs-l0jiBoh6.js} +1 -1
  258. package/dist/public/{process-peer-query-param-BL2k0Hu-.js → process-peer-query-param-s-aSP1Rq.js} +1 -1
  259. package/dist/public/{process-pending-shared-payloads-C1AgGvn8.js → process-pending-shared-payloads-BN3GigPT.js} +1 -1
  260. package/dist/public/{process-room-query-param-DM0QCq3_.js → process-room-query-param-B2Qe0F0M.js} +1 -1
  261. package/dist/public/provider-YPZmsuHR.js +1 -0
  262. package/dist/public/{push-client-DJEOz7bi.js → push-client-B2LC8Qp9.js} +1 -1
  263. package/dist/public/{rooms-C6LXIJl4.js → rooms-ChCEOvkw.js} +1 -1
  264. package/dist/public/service-worker.js +1 -1
  265. package/dist/public/shadow-claw-Br8mWDUx.js +1176 -0
  266. package/dist/public/{shadow-claw-accounts--4hd_oCz.js → shadow-claw-accounts-Dm6G7KMP.js} +1 -1
  267. package/dist/public/{shadow-claw-card-IbNlZAdK.js → shadow-claw-card-CggS8uSa.js} +1 -1
  268. package/dist/public/{shadow-claw-channels-Vq_pPGa2.js → shadow-claw-channels-088vhuWO.js} +1 -1
  269. package/dist/public/{shadow-claw-chat-D7_GS25e.js → shadow-claw-chat-BRwRlq-n.js} +3 -3
  270. package/dist/public/{shadow-claw-control-plane-WTMEV8_p.js → shadow-claw-control-plane-rhKACK85.js} +2 -2
  271. package/dist/public/{shadow-claw-conversations-CLQgU1IT.js → shadow-claw-conversations-CF_yUfKl.js} +1 -1
  272. package/dist/public/{shadow-claw-empty-state-D4CrFGsN.js → shadow-claw-empty-state-CkpOSXCS.js} +1 -1
  273. package/dist/public/{shadow-claw-file-viewer-BhqiqLWQ.js → shadow-claw-file-viewer-DWCejuY3.js} +4 -4
  274. package/dist/public/{shadow-claw-files-senDiG9l.js → shadow-claw-files-L6_ioyzh.js} +2 -2
  275. package/dist/public/{shadow-claw-git-DOOCqY23.js → shadow-claw-git-DsdkwLqQ.js} +2 -2
  276. package/dist/public/{shadow-claw-integrations-Bsvc3Agq.js → shadow-claw-integrations-CSbRTOm3.js} +1 -1
  277. package/dist/public/{shadow-claw-llm-actYICAk.js → shadow-claw-llm-BitaeAVc.js} +2 -2
  278. package/dist/public/{shadow-claw-mcp-remote-BYUgrK3v.js → shadow-claw-mcp-remote-gSbV5riy.js} +1 -1
  279. package/dist/public/{shadow-claw-networking-Dk3p5Ny_.js → shadow-claw-networking-Dn_y6Cl9.js} +1 -1
  280. package/dist/public/{shadow-claw-notifications-CzPAlay8.js → shadow-claw-notifications-Cj4Lqx8U.js} +1 -1
  281. package/dist/public/{shadow-claw-page-header-CjJpVkyL.js → shadow-claw-page-header-DR4OZFt2.js} +1 -1
  282. package/dist/public/{shadow-claw-page-header-action-button-2DH5O1TD.js → shadow-claw-page-header-action-button-BnCV_2Kb.js} +1 -1
  283. package/dist/public/{shadow-claw-pages-3r5I-wI8.js → shadow-claw-pages-mpDOtNYj.js} +6 -6
  284. package/dist/public/{shadow-claw-pdf-viewer-BiCEwsoY.js → shadow-claw-pdf-viewer-DZ_84qJH.js} +1 -1
  285. package/dist/public/{shadow-claw-settings-DgB9RSZN.js → shadow-claw-settings-CfFTYTEy.js} +2 -2
  286. package/dist/public/{shadow-claw-storage-JB_43nd8.js → shadow-claw-storage-DLmiT4bG.js} +1 -1
  287. package/dist/public/{shadow-claw-task-server-oi5UIxdA.js → shadow-claw-task-server-BoMBCsiS.js} +1 -1
  288. package/dist/public/{shadow-claw-tasks-CnyiOt81.js → shadow-claw-tasks-ChEp1j7x.js} +3 -3
  289. package/dist/public/{shadow-claw-terminal-BC3RynHt.js → shadow-claw-terminal-BaoVbOda.js} +1 -1
  290. package/dist/public/{shadow-claw-toast-YjG--2Za.js → shadow-claw-toast-e8oz7z6Z.js} +1 -1
  291. package/dist/public/{shadow-claw-tools-Bbwk4vlT.js → shadow-claw-tools-BYjUBiJz.js} +1 -1
  292. package/dist/public/{shadow-claw-webvm-HZqzl2H5.js → shadow-claw-webvm-xGb13TME.js} +1 -1
  293. package/dist/public/{sync-web-mcp-registration-BaH2nAP0.js → sync-web-mcp-registration-CQluj-Kz.js} +1 -1
  294. package/dist/public/{system-prompt-Dck3N8T0.js → system-prompt-CTJn0tK-.js} +1 -1
  295. package/dist/public/{tools-DHA1dK2I.js → tools-D-52Zmfc.js} +1 -1
  296. package/dist/public/{transformers-C-DuTM2K.js → transformers-CQ9ss9rD.js} +1 -1
  297. package/dist/public/{upload-group-file-Cejr3zo1.js → upload-group-file-A8kB7lvO.js} +1 -1
  298. package/dist/public/{webmcp-CMRtu57-.js → webmcp-DIUZjVF5.js} +1 -1
  299. package/dist/public/{write-group-file-CmJuVQNO.js → write-group-file-R67DjJ-q.js} +1 -1
  300. package/dist/public/{write-group-file-bytes-Cejr3zo1.js → write-group-file-bytes-A8kB7lvO.js} +1 -1
  301. package/dist/public/{zip-reader-CuQ13eLe.js → zip-reader-DN7FB-Q0.js} +1 -1
  302. package/dist/server.js +1 -1
  303. package/package.json +1 -1
  304. package/dist/cli/chunk-BFziiMKt.js +0 -7
  305. package/dist/cli/chunk-BM3llsxb.js +0 -1
  306. package/dist/cli/chunk-Bj5qFsDi.js +0 -7
  307. package/dist/cli/chunk-Bj95zm-y.js +0 -1
  308. package/dist/cli/chunk-BpyP-esT.js +0 -1
  309. package/dist/cli/chunk-CX696s3_.js +0 -1
  310. package/dist/cli/chunk-DRxCrCAA.js +0 -139
  311. package/dist/cli/chunk-DjbCHa0h.js +0 -1
  312. package/dist/cli/chunk-DsQhAF31.js +0 -1
  313. package/dist/cli/chunk-VM-dECyG.js +0 -1
  314. package/dist/cli/chunk-heu2xRw1.js +0 -1
  315. package/dist/lib/orchestrator-i_QJ-o22.js.map +0 -1
  316. package/dist/lib/shadow-claw-DoQ7fgl5.js.map +0 -1
  317. package/dist/public/app-routes-V_-URXc5.js +0 -1
  318. package/dist/public/attachment-capabilities-B6ibLwQB.js +0 -1
  319. package/dist/public/config-C-YdSFZB.js +0 -1
  320. package/dist/public/get-group-dir-DL44kvqW.js +0 -1
  321. package/dist/public/init-control-plane-BoJijVtf.js +0 -1
  322. package/dist/public/orchestrator-CaUpEVkQ.js +0 -63
  323. package/dist/public/provider-DNIL4-Hw.js +0 -1
  324. package/dist/public/shadow-claw-DdgeYPg5.js +0 -1176
@@ -1,5 +1,5 @@
1
- import { c as isStaleHandleError, i as getOpfsRootDirName, n as getGroupDir, o as getStorageStatus, s as invalidateStorageRoot, t as parsePath } from "./parse-path-DPCn-HwI.js";
2
- import { c as writeFileHandle, l as writeOpfsPathViaWorker } from "./tools-Beuyh8y1.js";
1
+ import { c as isStaleHandleError, i as getOpfsRootDirName, n as getGroupDir, o as getStorageStatus, s as invalidateStorageRoot, t as parsePath } from "./parse-path-BOHQP_IQ.js";
2
+ import { c as writeFileHandle, l as writeOpfsPathViaWorker } from "./tools-B8OJ4sMF.js";
3
3
 
4
4
  //#region src/storage/write-group-file-bytes.ts
5
5
  /**
@@ -38,4 +38,4 @@ async function writeGroupFileBytes(db, groupId, filePath, content) {
38
38
 
39
39
  //#endregion
40
40
  export { writeGroupFileBytes as t };
41
- //# sourceMappingURL=write-group-file-bytes-Ccn-VFUU.js.map
41
+ //# sourceMappingURL=write-group-file-bytes-CNT7DqOZ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"write-group-file-bytes-Ccn-VFUU.js","names":[],"sources":["../../src/storage/write-group-file-bytes.ts"],"sourcesContent":["import { getGroupDir } from \"./get-group-dir.js\";\nimport { parsePath } from \"./parse-path.js\";\nimport {\n getOpfsRootDirName,\n getStorageStatus,\n invalidateStorageRoot,\n isStaleHandleError,\n} from \"./storage.js\";\nimport {\n writeFileHandle,\n writeOpfsPathViaWorker,\n} from \"./write-file-handle.js\";\nimport type { ShadowClawDatabase } from \"../db/types.js\";\n\n/**\n * Write binary content to a file in a group's workspace.\n * Creates intermediate directories as needed.\n */\nexport async function writeGroupFileBytes(\n db: ShadowClawDatabase,\n groupId: string,\n filePath: string,\n content: Uint8Array,\n): Promise<void> {\n const { dirs, filename } = parsePath(filePath);\n\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n const groupDir = await getGroupDir(db, groupId);\n let dir = groupDir;\n for (const seg of dirs) {\n dir = await dir.getDirectoryHandle(seg, { create: true });\n }\n\n const fileHandle = await dir.getFileHandle(filename, { create: true });\n\n try {\n await writeFileHandle(fileHandle, content);\n\n return;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const needsOpfsWorkerFallback =\n message.includes(\"Writable file streams are not supported\") &&\n (await getStorageStatus(db)).type === \"opfs\";\n\n if (!needsOpfsWorkerFallback) {\n throw err;\n }\n }\n\n const safeId = groupId.replace(/:/g, \"-\");\n await writeOpfsPathViaWorker(\n [getOpfsRootDirName(), \"groups\", safeId, ...dirs, filename],\n content,\n );\n\n return;\n } catch (err) {\n if (attempt === 0 && isStaleHandleError(err)) {\n invalidateStorageRoot();\n\n continue;\n }\n\n throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;AAkBA,eAAsB,oBACpB,IACA,SACA,UACA,SACe;CACf,MAAM,EAAE,MAAM,aAAa,UAAU,QAAQ;CAE7C,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WACjC,IAAI;EAEF,IAAI,MAAM,MADa,YAAY,IAAI,OAAO;EAE9C,KAAK,MAAM,OAAO,MAChB,MAAM,MAAM,IAAI,mBAAmB,KAAK,EAAE,QAAQ,KAAK,CAAC;EAG1D,MAAM,aAAa,MAAM,IAAI,cAAc,UAAU,EAAE,QAAQ,KAAK,CAAC;EAErE,IAAI;GACF,MAAM,gBAAgB,YAAY,OAAO;GAEzC;EACF,SAAS,KAAK;GAMZ,IAAI,GALY,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAEtD,CAAC,SAAS,yCAAyC,MACzD,MAAM,iBAAiB,EAAE,EAAC,CAAE,SAAS,SAGtC,MAAM;EAEV;EAEA,MAAM,SAAS,QAAQ,QAAQ,MAAM,GAAG;EACxC,MAAM,uBACJ;GAAC,mBAAmB;GAAG;GAAU;GAAQ,GAAG;GAAM;EAAQ,GAC1D,OACF;EAEA;CACF,SAAS,KAAK;EACZ,IAAI,YAAY,KAAK,mBAAmB,GAAG,GAAG;GAC5C,sBAAsB;GAEtB;EACF;EAEA,MAAM;CACR;AAEJ"}
1
+ {"version":3,"file":"write-group-file-bytes-CNT7DqOZ.js","names":[],"sources":["../../src/storage/write-group-file-bytes.ts"],"sourcesContent":["import { getGroupDir } from \"./get-group-dir.js\";\nimport { parsePath } from \"./parse-path.js\";\nimport {\n getOpfsRootDirName,\n getStorageStatus,\n invalidateStorageRoot,\n isStaleHandleError,\n} from \"./storage.js\";\nimport {\n writeFileHandle,\n writeOpfsPathViaWorker,\n} from \"./write-file-handle.js\";\nimport type { ShadowClawDatabase } from \"../db/types.js\";\n\n/**\n * Write binary content to a file in a group's workspace.\n * Creates intermediate directories as needed.\n */\nexport async function writeGroupFileBytes(\n db: ShadowClawDatabase,\n groupId: string,\n filePath: string,\n content: Uint8Array,\n): Promise<void> {\n const { dirs, filename } = parsePath(filePath);\n\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n const groupDir = await getGroupDir(db, groupId);\n let dir = groupDir;\n for (const seg of dirs) {\n dir = await dir.getDirectoryHandle(seg, { create: true });\n }\n\n const fileHandle = await dir.getFileHandle(filename, { create: true });\n\n try {\n await writeFileHandle(fileHandle, content);\n\n return;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const needsOpfsWorkerFallback =\n message.includes(\"Writable file streams are not supported\") &&\n (await getStorageStatus(db)).type === \"opfs\";\n\n if (!needsOpfsWorkerFallback) {\n throw err;\n }\n }\n\n const safeId = groupId.replace(/:/g, \"-\");\n await writeOpfsPathViaWorker(\n [getOpfsRootDirName(), \"groups\", safeId, ...dirs, filename],\n content,\n );\n\n return;\n } catch (err) {\n if (attempt === 0 && isStaleHandleError(err)) {\n invalidateStorageRoot();\n\n continue;\n }\n\n throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;AAkBA,eAAsB,oBACpB,IACA,SACA,UACA,SACe;CACf,MAAM,EAAE,MAAM,aAAa,UAAU,QAAQ;CAE7C,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WACjC,IAAI;EAEF,IAAI,MAAM,MADa,YAAY,IAAI,OAAO;EAE9C,KAAK,MAAM,OAAO,MAChB,MAAM,MAAM,IAAI,mBAAmB,KAAK,EAAE,QAAQ,KAAK,CAAC;EAG1D,MAAM,aAAa,MAAM,IAAI,cAAc,UAAU,EAAE,QAAQ,KAAK,CAAC;EAErE,IAAI;GACF,MAAM,gBAAgB,YAAY,OAAO;GAEzC;EACF,SAAS,KAAK;GAMZ,IAAI,GALY,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAEtD,CAAC,SAAS,yCAAyC,MACzD,MAAM,iBAAiB,EAAE,EAAC,CAAE,SAAS,SAGtC,MAAM;EAEV;EAEA,MAAM,SAAS,QAAQ,QAAQ,MAAM,GAAG;EACxC,MAAM,uBACJ;GAAC,mBAAmB;GAAG;GAAU;GAAQ,GAAG;GAAM;EAAQ,GAC1D,OACF;EAEA;CACF,SAAS,KAAK;EACZ,IAAI,YAAY,KAAK,mBAAmB,GAAG,GAAG;GAC5C,sBAAsB;GAEtB;EACF;EAEA,MAAM;CACR;AAEJ"}
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://modelcontextprotocol.io/schemas/server-card/v1.json",
3
3
  "name": "shadow-claw",
4
- "version": "1.59.6",
4
+ "version": "1.59.7",
5
5
  "description": "Multi-runtime AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.",
6
6
  "title": "ShadowClaw MCP Server",
7
7
  "websiteUrl": "https://xt-ml.github.io/shadow-claw/",
@@ -13,19 +13,27 @@
13
13
  {
14
14
  "src": "https://xt-ml.github.io/shadow-claw/assets/icons/favicon.svg",
15
15
  "mimeType": "image/svg+xml",
16
- "sizes": ["any"]
16
+ "sizes": [
17
+ "any"
18
+ ]
17
19
  },
18
20
  {
19
21
  "src": "https://xt-ml.github.io/shadow-claw/assets/icons/512.png",
20
22
  "mimeType": "image/png",
21
- "sizes": ["512x512"]
23
+ "sizes": [
24
+ "512x512"
25
+ ]
22
26
  }
23
27
  ],
24
28
  "remotes": [
25
29
  {
26
30
  "type": "streamable-http",
27
31
  "url": "http://localhost:8888/mcp",
28
- "supportedProtocolVersions": ["2026-07-28", "2025-11-25", "2024-11-05"],
32
+ "supportedProtocolVersions": [
33
+ "2026-07-28",
34
+ "2025-11-25",
35
+ "2024-11-05"
36
+ ],
29
37
  "headers": [
30
38
  {
31
39
  "name": "MCP-Protocol-Version",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://modelcontextprotocol.io/schemas/server-card/v1.json",
3
3
  "name": "shadow-claw",
4
- "version": "1.59.6",
4
+ "version": "1.59.7",
5
5
  "description": "Multi-runtime AI assistant with local and remote LLM orchestration, Web Workers, OPFS storage, and agentic tool execution.",
6
6
  "title": "ShadowClaw MCP Server",
7
7
  "websiteUrl": "https://xt-ml.github.io/shadow-claw/",
@@ -13,19 +13,27 @@
13
13
  {
14
14
  "src": "https://xt-ml.github.io/shadow-claw/assets/icons/favicon.svg",
15
15
  "mimeType": "image/svg+xml",
16
- "sizes": ["any"]
16
+ "sizes": [
17
+ "any"
18
+ ]
17
19
  },
18
20
  {
19
21
  "src": "https://xt-ml.github.io/shadow-claw/assets/icons/512.png",
20
22
  "mimeType": "image/png",
21
- "sizes": ["512x512"]
23
+ "sizes": [
24
+ "512x512"
25
+ ]
22
26
  }
23
27
  ],
24
28
  "remotes": [
25
29
  {
26
30
  "type": "streamable-http",
27
31
  "url": "http://localhost:8888/mcp",
28
- "supportedProtocolVersions": ["2026-07-28", "2025-11-25", "2024-11-05"],
32
+ "supportedProtocolVersions": [
33
+ "2026-07-28",
34
+ "2025-11-25",
35
+ "2024-11-05"
36
+ ],
29
37
  "headers": [
30
38
  {
31
39
  "name": "MCP-Protocol-Version",
@@ -1800,7 +1800,7 @@ slug: "shadow-claw-pages"
1800
1800
  (id, groupId, enabled, schedule, prompt, tools, lastRun, createdAt, type, freshContext, subagent, name, task_order, pushNotifications)
1801
1801
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);for(let e of i)a.run(fe(),n,+!!e.enabled,e.schedule??null,e.prompt??``,e.tools??null,e.lastRun??null,e.createdAt,e.type??null,e.freshContext?1:null,e.subagent?1:null,e.name??null,e.task_order??null,e.pushNotifications?1:null);return Promise.resolve(i.length)}return new Promise((r,i)=>{let a=e?.transaction(`tasks`,`readwrite`);if(!a)throw Error(`failed to get transaction, cannot clone tasks.`);let o=a.objectStore(`tasks`),s=o.index(`by-group`).openCursor(t),c=0;s.onsuccess=()=>{let e=s.result;if(e){let t={...e.value,id:fe(),groupId:n};o.put(t),c++,e.continue()}else r(c)},s.onerror=()=>i(s.error)})}function sW(e,t){return k(e,`messages`,`readwrite`,e=>e.delete(t)).then(()=>void 0)}function cW(e,t){return t?k(e,`tasks`,`readwrite`,e=>e.delete(t)).then(()=>void 0):Promise.reject(/* @__PURE__ */ Error(`Task ID is required for deletion.`))}function lW(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`sub-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}async function uW(e){if(!e)return lW();let t=await A(e,b.SUBSCRIBER_ID);if(typeof t==`string`&&t.trim().length>0)return t;let n=lW();return await pe(e,b.SUBSCRIBER_ID,n),n}function dW(e,t,n){let r=null,i,a;return typeof e==`string`?(i=e,a=t):(r=e,i=t,a=n??50),r&&O(r)?Promise.resolve().then(()=>(r.db.prepare(`SELECT * FROM messages WHERE groupId = ? ORDER BY timestamp DESC LIMIT ?`).all(i,a)??[]).reverse().map(fW)):new Promise(async(e,t)=>{try{let n=r??await ee();if(!n)return t(/* @__PURE__ */ Error(`failed to get transaction, cannot get recent messages.`));let o=n.transaction(`messages`,`readonly`);if(!o)return t(/* @__PURE__ */ Error(`failed to get transaction`));let s=o.objectStore(`messages`).index(`by-group-time`),c=IDBKeyRange.bound([i,0],[i,1/0]),l=s.openCursor(c,`prev`),u=[];l.onsuccess=()=>{let t=l.result;t&&u.length<a?(u.push(t.value),t.continue()):e(u.reverse())},l.onerror=()=>t(l.error)}catch(e){t(e)}})}function fW(e){return{...e,isFromMe:!!e.isFromMe,isTrigger:!!e.isTrigger,attachments:e.attachments?JSON.parse(e.attachments):void 0,a2uiAction:e.a2uiAction?JSON.parse(e.a2uiAction):void 0,a2uiEnvelopes:e.a2uiEnvelopes?JSON.parse(e.a2uiEnvelopes):void 0}}const pW=`group_metadata`;async function mW(e){let t=await A(e,pW);if(!t)return[];try{return JSON.parse(t)}catch{return[]}}async function hW(e,t){await pe(e,pW,JSON.stringify(t))}async function gW(e,t,n=`br:`,r){let i=await mW(e),a={groupId:`${n}${r??fe()}`,name:t,createdAt:Date.now()};return i.push(a),await hW(e,i),a}async function _W(e,t,n){let r=await mW(e),i=r.find(e=>e.groupId===t);i&&(i.name=n),await hW(e,r)}async function vW(e,t,n){let r=await mW(e),i=r.find(e=>e.groupId===t);i&&(n&&n.length>0?i.toolTags=n:delete i.toolTags),await hW(e,r)}async function yW(e,t){await hW(e,(await mW(e)).filter(e=>e.groupId!==t))}async function bW(e){let t=await mW(e);if(t.length===0){let t={groupId:v,name:`Main`,createdAt:0};return await hW(e,[t]),[t]}return t}async function xW(e,t){let n=await mW(e),r=new Map(n.map(e=>[e.groupId,e])),i=[];for(let e of t){let t=r.get(e);t&&(i.push(t),r.delete(e))}for(let e of n)r.has(e.groupId)&&i.push(e);await hW(e,i)}async function SW(e,t){let n=await mW(e),r=n.find(e=>e.groupId===t);if(!r)return null;let i=t.indexOf(`:`),a={groupId:`${i>=0?t.slice(0,i+1):`br:`}${fe()}`,name:`${r.name} (copy)`,createdAt:Date.now(),pinnedMaxTokens:r.pinnedMaxTokens,providerRuntimeOverrides:r.providerRuntimeOverrides?JSON.parse(JSON.stringify(r.providerRuntimeOverrides)):void 0,subagentModelSelectionMode:r.subagentModelSelectionMode,subagentMaxTokens:r.subagentMaxTokens,subagentPinnedProvider:r.subagentPinnedProvider,subagentPinnedModel:r.subagentPinnedModel,subagentFastProvider:r.subagentFastProvider,subagentFastModel:r.subagentFastModel,subagentSmartProvider:r.subagentSmartProvider,subagentSmartModel:r.subagentSmartModel,subagentPowerfulProvider:r.subagentPowerfulProvider,subagentPowerfulModel:r.subagentPowerfulModel,toolTags:r.toolTags?[...r.toolTags]:void 0};return n.push(a),await hW(e,n),a}async function CW(e,t,n,r,i){let a=await mW(e),o=a.find(e=>e.groupId===t);o&&(n?o.pinnedProvider=n:delete o.pinnedProvider,r?o.pinnedModel=r:delete o.pinnedModel,typeof i==`number`&&Number.isFinite(i)&&i>0?o.pinnedMaxTokens=Math.floor(i):delete o.pinnedMaxTokens),await hW(e,a)}async function wW(e,t,n,r,i,a){let o=await mW(e),s=o.find(e=>e.groupId===t);s&&(s.subagentModelSelectionMode=n,n===`manual`?(r?s.subagentPinnedProvider=r:delete s.subagentPinnedProvider,i?s.subagentPinnedModel=i:delete s.subagentPinnedModel):(delete s.subagentPinnedProvider,delete s.subagentPinnedModel),typeof a==`number`&&Number.isFinite(a)&&a>0?s.subagentMaxTokens=Math.floor(a):delete s.subagentMaxTokens),await hW(e,o)}async function TW(e,t,n){let r=await mW(e),i=r.find(e=>e.groupId===t);i&&(n&&Object.keys(n).length>0?i.providerRuntimeOverrides=JSON.parse(JSON.stringify(n)):delete i.providerRuntimeOverrides),await hW(e,r)}function EW(e,t){return k(e,`messages`,`readwrite`,e=>e.put(t)).then(()=>void 0)}function DW(e,t){let n={...t,enabled:+!!t.enabled};return k(e,`tasks`,`readwrite`,e=>e.put(n)).then(()=>void 0)}function OW(e,t,n){let r=null,i,a;return typeof e==`string`?(i=e,a=t):(r=e,i=t,a=n),r&&O(r)?Promise.resolve().then(()=>{r.db.prepare(`UPDATE tasks SET lastRun = ? WHERE id = ?`).run(a,i)}):new Promise(async(e,t)=>{try{let n=r??await ee();if(!n)return t(/* @__PURE__ */ Error(`failed to get transaction, cannot update task last run.`));let o=n.transaction(`tasks`,`readwrite`);if(!o)return t(/* @__PURE__ */ Error(`failed to get transaction`));let s=o.objectStore(`tasks`),c=s.get(i);c.onsuccess=()=>{let n=c.result;if(!n){e();return}n.lastRun=a;let r=s.put(n);r.onsuccess=()=>e(),r.onerror=()=>t(r.error)},c.onerror=()=>t(c.error)}catch(e){t(e)}})}async function kW(e,t,n){let r=(await de(e)).filter(e=>e.groupId===t),i=new Map(r.map(e=>[e.id,e])),a=[],o=0;for(let t of n){let n=i.get(t);n&&(n.order=o++,await DW(e,n),a.push(n),i.delete(t))}let s=Array.from(i.values()).sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r});for(let t of s)t.order=o++,await DW(e,t),a.push(t);return a}async function AW(e,t,n,r){let i=await re(e,t),a=await re(e,n),o=r.replace(/\\/g,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean),s=i,c=a;for(let e of o)s=await s.getDirectoryHandle(e),c=await c.getDirectoryHandle(e,{create:!0});let l=n.replace(/:/g,`-`),u=[F(),`groups`,l,...o];try{await jW(e,n,s,c,u)}catch(e){throw o.length>0&&await a.removeEntry(o[0],{recursive:!0}).catch(()=>void 0),e}}async function jW(e,t,n,r,i){for await(let[a,o]of n.entries()){if(o.kind===`directory`){await jW(e,t,o,await r.getDirectoryHandle(a,{create:!0}),[...i,a]);continue}let n=await o.getFile(),s=await r.getFileHandle(a,{create:!0});try{await ye(s,n)}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await ae(e)).type===`opfs`))throw t;await he([...i,a],n)}}}async function MW(e,t,n=`.`){for(let r=0;r<2;r++)try{let r=await re(e,t);if(n&&n!==`.`){let e=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean);for(let t of e){let e=await r.getDirectoryHandle(t);if(typeof r.isSameEntry==`function`&&await r.isSameEntry(e))throw Error(`Directory navigation stuck at "${r.name}" for segment "${t}" — the stored directory handle may be stale.`);r=e}}let i=[];for await(let[e,t]of r.entries())i.push(t.kind===`directory`?`${e}/`:e);return i.sort()}catch(e){if(r===0&&oe(e)){ie();continue}throw e}return[]}function NW(e){if(!e||typeof e!=`object`)return!1;let t=globalThis.FileSystemDirectoryHandle;return t!==void 0&&e instanceof t||typeof e.getDirectoryHandle==`function`&&typeof e.getFileHandle==`function`&&typeof e.requestPermission==`function`}async function PW(e){let t=await A(e,b.STORAGE_HANDLE);return!NW(t)||await t.requestPermission({mode:`readwrite`})===`granted`}function FW(e){let t=l();return t?`shadowclaw:${t}:${e}`:e}function IW(e){if(typeof localStorage>`u`)return null;let t=FW(e);try{let n=localStorage.getItem(t);if(n!==null)return n;if(t===e)return null;let r=localStorage.getItem(e);if(r!==null)return localStorage.setItem(t,r),r}catch(e){console.warn(`Unable to read from localStorage:`,e)}return null}function LW(e,t){if(typeof localStorage>`u`)return;let n=FW(e);try{localStorage.setItem(n,t)}catch(e){console.warn(`Unable to write to localStorage:`,e)}}async function RW(e,t){let n=await re(e,t);for await(let[e]of n.entries())await n.removeEntry(e,{recursive:!0})}async function zW(e,t,n){let r=await re(e,t),{dirs:i,filename:a}=M(n.replace(/\/$/,``)),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a,{recursive:!0})}function BW(e,t){return`${e}:${t}`}async function VW(e){let t=await A(e,b.SUPPRESSED_PAGES_LIST);if(!t||typeof t!=`string`)return[];try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return[]}async function HW(e,t,n){let r=await VW(e),i=BW(t,n);return r.some(e=>BW(e.groupId,e.path)===i)}async function UW(e,t,n){let r=await VW(e),i=BW(t,n);if(!r.some(e=>BW(e.groupId,e.path)===i)){let i=[...r,{groupId:t,path:n}];await pe(e,b.SUPPRESSED_PAGES_LIST,JSON.stringify(i))}}async function WW(e,t,n){let r=await VW(e),i=BW(t,n),a=r.filter(e=>BW(e.groupId,e.path)!==i);a.length!==r.length&&await pe(e,b.SUPPRESSED_PAGES_LIST,JSON.stringify(a))}function GW(e){return Array.from(new Set(e.map(e=>e.trim()).filter(Boolean)))}function KW(e){let t=e.trim().replace(/\\/g,`/`);return t===`/`||/^\/+$/.test(t)?`/`:t.replace(/^\/+/,``).replace(/\/+$/,``)}const qW=/\.(md|markdown|html|xhtml|txt)$/i;function JW(e){return e===`/`?`/`:e.replace(qW,``)}function YW(e){let t=e.trim().replace(/\\/g,`/`);return t===`/`||/^\/+$/.test(t)?`/`:t.replace(/^\/+/,``).replace(/\/+$/,``)}function XW(e){return e?e.replace(/^br:/i,``).replace(/^br-/i,``).trim():`main`}function ZW(e,t){let n=YW(t);if(!n)return;e.add(n);let r=JW(n);r&&r!==n&&e.add(r)}function QW(e,t,n){let r=/* @__PURE__ */ new Set;if(!e)return r;let i=XW(t);if(e===`/`){if(r.add(`/`),ZW(r,`index.html`),n){let e=KW(n);e&&e!==`/`&&ZW(r,`${e}/index.html`)}return ZW(r,`pages/index.html`),ZW(r,`pages/${i}/index.html`),ZW(r,`${i}/index.html`),r}if(ZW(r,e),n){let t=KW(n);t&&t!==`/`&&ZW(r,`${t}/${e}`)}if(e.startsWith(`pages/`)){let t=e.slice(6);ZW(r,t),t.startsWith(`${i}/`)?ZW(r,t.slice(`${i}/`.length)):ZW(r,t.replace(/^[^/]+\//,``))}else ZW(r,`pages/${e}`),ZW(r,`pages/${i}/${e}`),ZW(r,`${i}/${e}`);for(let e of Array.from(r)){let t=JW(e);if(e===`index.html`||t===`index`){r.add(`/`);break}}return r}function $W(e,t){let n=t.toLowerCase(),r=JW(t).toLowerCase(),i=n===r?[n]:[n,r];for(let t of e){let e=t.toLowerCase(),n=JW(e);for(let t of i)if(t&&(e===t||n===t||t!==`/`&&(e.startsWith(`${t}/`)||n.startsWith(`${t}/`)||e.endsWith(`/${t}`)||n.endsWith(`/${t}`)||e.includes(`/${t}/`)||n.includes(`/${t}/`))))return!0}return!1}function eG(e,t){for(let n of t){let t=KW(n);if(t&&$W(e,t))return!0}return!1}function tG(e,t,n,r){if(!e||typeof e!=`string`)return!1;let i=YW(e);if(!i)return!1;let a=[],o=[],s,c;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t,n=e.allowList??e.allowlist??[],r=e.denyList??e.denylist??[];a=GW(Array.from(n||[])),o=GW(Array.from(r||[])),s=e.groupId,c=e.basePathPrefix}else a=GW(Array.from(t||[])),o=GW(Array.from(n||[])),s=r?.groupId,c=r?.basePathPrefix;let l=QW(i,s,c);return o.length>0&&eG(l,o)?!1:a.length>0?eG(l,a):!0}function nG(e){if(!e)return``;let t=e.match(/^\r?\n([ \t]+)/);if(t){let n=t[1],r=RegExp(`^[ \\t]{1,${n.length}}`,`gm`);return e.replace(/^\r?\n/,``).replace(r,``).replace(/\r?\n[ \t]*$/,`
1802
1802
  `)}if(/^(?:\r?\n)+[ \t]*---/.test(e))return e.replace(/^(?:\r?\n)+/,``);if(/^[ \t]+---/.test(e)){let t=e.match(/^[ \t]+/);if(t){let n=t[0],r=RegExp(`^[ \\t]{1,${n.length}}`,`gm`);return e.replace(r,``)}}return e}function rG(e=v){return e===`br:main`?b.STATIC_MAIN_SITE_SEEDED:`${b.STATIC_MAIN_SITE_SEEDED}:${e}`}async function iG(e,t=v){let n=rG(t),r=await A(e,n);return r===!0||r===`true`}async function aG(e,t=v,n=!0){let r=rG(t);await pe(e,r,n)}function oG(){let e=a(`/static-main-manifest.json`);if(typeof window<`u`&&window.location?.origin)try{return new URL(e,window.location.origin).toString()}catch{return e}return e}function sG(e){let t=e.replace(/^\/+/,``),n=`static-main`;if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);typeof t?.pages?.baseUrl==`string`&&(n=t.pages.baseUrl.replace(/^\/+/,``).replace(/\/+$/,``))}}catch{}let r=a(n?`/${n}/${t}`:`/${t}`);if(typeof window<`u`&&window.location?.origin)try{return new URL(r,window.location.origin).toString()}catch{return r}return r}async function cG(){if(typeof fetch!=`function`)return null;try{let e=oG(),t=await fetch(e);if(t.ok){if((t.headers?.get?.(`content-type`)||``).includes(`text/html`))return null;let e=await t.json();if(e&&Array.isArray(e.pages))return e}}catch{}return null}async function lG(e){if(typeof fetch!=`function`)return null;try{let t=sG(e),n=await fetch(t);if(n.ok){let t=n.headers?.get?.(`content-type`)||``;if((e.endsWith(`.md`)||e.endsWith(`.markdown`)||e.endsWith(`.json`))&&t.includes(`text/html`))return null;let r=await n.text();return r.includes(`<shadow-claw`)||r.includes(`data-shadow-claw-dsd`)?null:r}}catch{}return null}function uG(e){if(typeof document>`u`)return null;let t=t=>{if(!t||!(t instanceof HTMLElement))return!1;if(!e)return!0;let n=t.getAttribute(`data-initial-path`)?.trim();return!n||n===e},n=document.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(n))return n;let r=document.querySelector(`shadow-claw`)?.shadowRoot,i=(r?.querySelector(`shadow-claw-pages`)?.shadowRoot)?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`)||r?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(i))return i;let a=document.querySelectorAll(`template`);for(let n of Array.from(a)){let r=n.content?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(r))return r;let i=n.content?.querySelectorAll(`template`);if(i)for(let n of Array.from(i)){let r=n.content?.querySelector(e?`[data-pages-rendered][data-initial-path="${e}"]`:`[data-pages-rendered]`);if(t(r))return r}}return null}function dG(e=`index.html`){let t=uG(e);if(!t)return null;let n=t.getAttribute(`data-initial-path`)?.trim();if(n&&n!==e)return null;let r=t.querySelector(`[data-markdown-frontmatter]`),i=null;if(r){let e=r.getAttribute(`data-frontmatter`);if(e)try{i=JSON.parse(e)}catch{}}let a=t.cloneNode(!0),o=a.querySelector(`[data-markdown-frontmatter]`);o&&o.remove();let s=a.innerHTML.trim();if(!s&&!i)return null;if(i&&Object.keys(i).length>0){let e=[`---`];for(let[t,n]of Object.entries(i))typeof n==`string`?e.push(`${t}: ${JSON.stringify(n)}`):typeof n==`number`||typeof n==`boolean`?e.push(`${t}: ${n}`):e.push(`${t}: ${JSON.stringify(n)}`);return e.push(`---`,``),`${e.join(`
1803
- `)}\n${s}`}return s}async function fG(e={}){let t=()=>{let e=null;if(typeof document<`u`){let t=document.getElementById(`shadow-claw-static-manifest`);if(t&&t.textContent)try{let n=JSON.parse(t.textContent);n&&Array.isArray(n.pages)&&(e={...n,pages:[...n.pages]})}catch(e){console.warn(`Failed to parse embedded static main manifest:`,e)}let n=document.querySelectorAll(`script[type="text/markdown"][data-shadow-claw-page]`);if(n.length>0){e||={pages:[]};for(let t of Array.from(n)){let n=t.getAttribute(`data-shadow-claw-page`)?.trim();if(n){let r=t.textContent||``;r=nG(r),!r.trim()&&/^memory\.(md|markdown)$/iu.test(n)&&(r=LU),!r.trim()&&(n===`index.html`||/^index\.(html?|xhtml)$/iu.test(n))&&(r=dG(n)??UU);let i=e.pages.findIndex(e=>e.displayPath===n);i>=0?e.pages[i].content=r:e.pages.push({displayPath:n,content:r})}}}let r=document.getElementById(`shadow-claw-site-config`);if(r?.textContent)try{let t=JSON.parse(r.textContent);if(Array.isArray(t?.pages?.files)){e||={pages:[]};for(let n of t.pages.files)if(typeof n==`string`&&n.trim()){let t=n.trim(),r=``;/^memory\.(md|markdown)$/iu.test(t)?r=LU:(t===`index.html`||/^index\.(html?|xhtml)$/iu.test(t))&&(r=dG(t)??UU),e.pages.some(e=>e.displayPath===t)||e.pages.push({displayPath:t,content:r})}}}catch{}let i=uG();if(i){e||={pages:[]};let t=i.getAttribute(`data-initial-path`)?.trim()||`index.html`;if(!e.pages.some(e=>e.displayPath===t)){let n=dG(t)??UU;e.pages.push({displayPath:t,content:n})}e.pages.some(e=>/^memory\.(md|markdown)$/iu.test(e.displayPath))||e.pages.push({displayPath:`MEMORY.md`,content:LU})}}return e};if(e.preferEmbedded!==!1){let e=t();if(e)return e}if(e.fetchFallback!==!1){let e=await cG();if(e)return e}if(e.preferEmbedded===!1){let e=t();if(e)return e}return{pages:[{displayPath:`index.html`,content:UU},{displayPath:`MEMORY.md`,content:LU}]}}async function pG(e,t,n=[]){for(let[r,i]of Object.entries(t))if(r===`purgePreRenderedStaticPages`&&i===!0){if(n.length>0){let t=n[0],r=n.slice(1).join(`/`);try{r?await zW(e,t,r):await RW(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await pG(e,i,[...n,r])}function mG(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t?.pages?.sortOrder===`desc`)return`desc`;if(t?.pages?.sortOrder===`asc`)return`asc`}}catch{}return`desc`}function hG(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent)?.pages?.defaultPinnedPage;if(typeof t==`string`&&t.trim().length>0)return t.trim()}}catch{}return null}function gG(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);return{allowList:GW(t?.pages?.allowList??t?.pages?.allowlist??t?.allowList??t?.allowlist??[]),denyList:GW(t?.pages?.denyList??t?.pages?.denylist??t?.denyList??t?.denylist??[])}}}catch{}return{allowList:[],denyList:[]}}function _G(e,t){let n=t??mG();return[...e].sort((e,t)=>{let r=e.path,i=t.path,a=r.split(`/`).pop()||``,o=i.split(`/`).pop()||``,s=/^index\.(html?|xhtml)$/iu.test(a),c=/^index\.(html?|xhtml)$/iu.test(o);if(s&&!c)return-1;if(!s&&c)return 1;let l=/^memory\.(md|markdown)$/iu.test(a),u=/^memory\.(md|markdown)$/iu.test(o);return l&&!u?1:!l&&u?-1:n===`asc`?r.localeCompare(i,void 0,{numeric:!0,sensitivity:`base`}):i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})})}async function vG(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(IW(n)===i)return!0}catch{}try{if(await A(e,r)===i){try{LW(n,i)}catch{}return!0}await pe(e,r,i);try{LW(n,i)}catch{}}catch{try{LW(n,i)}catch{}}return!1}async function yG(e,t=v,n=[],r={}){await qU(e,t);let i=await fG(r),a=!1;i.preRenderedStaticPages&&(await vG(e,i.purgeId)||(a=!0,await pG(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await vG(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await zW(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}try{await zW(e,t,`.agents/tools/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}}for(let n of i.pages)if(n.content?.includes(`slug: "shadow-claw--purge-pages"`)){!a&&!await vG(e,i.purgeId)&&(a=!0,await RW(e,t));break}let s=t===`br:main`&&await BU(e),c=new Set(i.pages.map(e=>BW(t,e.displayPath))),l=a?n.filter(e=>e.groupId!==t||c.has(BW(e.groupId,e.path))):[...n],{allowList:u,denyList:d}=gG(),f=0;for(let n of i.pages)if(f++,f%5==0&&await new Promise(e=>setTimeout(e,0)),!n.content?.includes(`slug: "shadow-claw--purge-pages"`)&&tG(n.displayPath,{allowList:u,denyList:d,groupId:t})){if(/^memory\.(md|markdown)$/iu.test(n.displayPath)){if(s)continue;let r=typeof n.content==`string`&&n.content.trim().length>0&&n.content!==LU?n.content:void 0;if(r===void 0?await HU(e,t):await HU(e,t,r)){let e=BW(t,n.displayPath);l.some(t=>BW(t.groupId,t.path)===e)||l.push({groupId:t,path:n.displayPath})}}else if(!await HW(e,t,n.displayPath))try{if(!await P(e,t,n.displayPath)){let r=n.content;(typeof r!=`string`||!r.trim())&&(r=n.displayPath===`index.html`?dG(`index.html`)??UU:await lG(n.displayPath)??``),await xe(e,t,n.displayPath,r)}let r=BW(t,n.displayPath);l.some(e=>BW(e.groupId,e.path)===r)||l.push({groupId:t,path:n.displayPath})}catch(e){console.warn(`Failed to seed static page file ${n.displayPath}:`,e)}}if(t===`br:main`){for(let n of i.skills||[]){let r=`.agents/skills/main/${n.displayPath}`;try{await P(e,t,r)||await xe(e,t,r,n.content)}catch(e){console.warn(`Failed to seed skill file ${r}:`,e)}}for(let n of i.tools||[]){let r=`.agents/tools/main/${n.displayPath}`;try{(o||!await P(e,t,r))&&await xe(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let p=typeof document<`u`&&(document.getElementById(`shadow-claw-static-manifest`)!==null||document.querySelector(`script[type="text/markdown"][data-shadow-claw-page]`)!==null||uG()!==null);r.preferEmbedded!==!1&&p||await aG(e,t,!0);let m=l.filter(e=>tG(e.path,{allowList:u,denyList:d,groupId:e.groupId}));return Object.defineProperty(m,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(m,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),_G(m)}var bG=class{_events;_handlers=[];_runs=/* @__PURE__ */ new Map;constructor(e){this._events=e}start(){this._listen(`streaming-start`,this._onStreamingStart),this._listen(`streaming-chunk`,this._onStreamingChunk),this._listen(`streaming-end`,this._onStreamingEnd),this._listen(`streaming-done`,this._onStreamingDone),this._listen(`streaming-error`,this._onStreamingError),this._listen(`tool-activity`,this._onToolActivity)}stop(){for(let{event:e,handler:t}of this._handlers)this._events.off(e,t);this._handlers=[],this._runs.clear()}_emit(e,t){window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{groupId:e,event:t}}))}_listen(e,t){this._events.on(e,t),this._handlers.push({event:e,handler:t})}_onStreamingChunk=({groupId:e,text:t})=>{let n=this._runs.get(e);n&&n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_CONTENT`,messageId:n.messageId,delta:t,timestamp:Date.now()})};_onStreamingDone=({groupId:e})=>{let t=this._runs.get(e);t&&(t.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_FINISHED`,threadId:t.threadId,runId:t.runId,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingEnd=({groupId:e})=>{let t=this._runs.get(e);t&&t.messageId&&(this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),t.messageId=null)};_onStreamingError=({groupId:e,error:t})=>{let n=this._runs.get(e);n&&(n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:n.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_ERROR`,message:t||`Unknown streaming error`,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingStart=({groupId:e})=>{let t=fe(),n=e,r=fe();this._runs.set(e,{runId:t,threadId:n,messageId:r,activeToolCallIds:/* @__PURE__ */ new Set}),this._emit(e,{type:`RUN_STARTED`,threadId:n,runId:t,timestamp:Date.now()}),this._emit(e,{type:`TEXT_MESSAGE_START`,messageId:r,role:`assistant`,timestamp:Date.now()})};_onToolActivity=({groupId:e,tool:t,status:n})=>{let r=this._runs.get(e);if(r){if(n===`running`){let n=fe();r.activeToolCallIds.add(n),this._emit(e,{type:`TOOL_CALL_START`,toolCallId:n,toolCallName:t,timestamp:Date.now()}),r._lastToolCallId=n}else if(n===`done`||n===`error`){let t=r._lastToolCallId;t&&(r.activeToolCallIds.delete(t),this._emit(e,{type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()}))}}}};const xG=new class{#e=new ve.State(0);#t=/* @__PURE__ */ new Map;#n=new ve.State([]);clear(){this.#t.forEach((e,t)=>this.clearTimer(t)),this.#t.clear(),this.#n.set([])}clearTimer(e){let t=this.#t.get(e);t?.timeoutId&&clearTimeout(t.timeoutId),this.#t.delete(e)}dismiss(e){this.clearTimer(e),this.#n.set(this.#n.get().filter(t=>t.id!==e))}pause(e){let t=this.#t.get(e);t&&t.timeoutId&&(clearTimeout(t.timeoutId),t.timeoutId=void 0,t.remaining=Math.max(0,t.remaining-(Date.now()-t.startedAt)),this.#t.set(e,t))}resolveAction(e){if(e&&typeof e.label==`string`&&typeof e.onClick==`function`)return e}resolveDuration(e){return typeof e!=`number`||Number.isNaN(e)||e<0?4e3:e}resolveType(e){return e&&[`success`,`warning`,`error`,`info`].includes(e)?e:`info`}resume(e){let t=this.#t.get(e);!t||t.timeoutId||t.remaining<=0||this.scheduleDismiss(e,t.remaining)}scheduleDismiss(e,t){this.clearTimer(e);let n=globalThis.setTimeout(()=>{this.dismiss(e)},t);this.#t.set(e,{timeoutId:n,remaining:t,startedAt:Date.now()})}show(e,t={}){let n=this.#e.get()+1;this.#e.set(n);let r={id:n,message:e,type:this.resolveType(t.type),duration:this.resolveDuration(t.duration),action:this.resolveAction(t.action),createdAt:Date.now()},i=[...this.#n.get(),r];if(i.length>5){let e=i[0];this.clearTimer(e.id),this.#n.set(i.slice(1))}else this.#n.set(i);return r.duration>0&&this.scheduleDismiss(r.id,r.duration),r.id}get toasts(){return this.#n.get()}async runAction(e){let t=this.#n.get().find(t=>t.id===e);t?.action&&await t.action.onClick()}};function SG(e,t={}){return xG.show(e,t)}function CG(e,t=4e3){return xG.show(e,{type:`success`,duration:t})}function wG(e,t=5e3){return xG.show(e,{type:`error`,duration:t})}function TG(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)EG(n,e);return n}function EG(e,t){let{op:n,path:r,value:i}=t;if(!r||!r.startsWith(`/`))return;let a=r.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),o=a.pop();if(o===void 0)return;let s=e;for(let e of a){if(typeof s!=`object`||!s)return;s=s[e]}typeof s==`object`&&s&&(Array.isArray(s)?DG(s,o,n,i):OG(s,o,n,i))}function DG(e,t,n,r){if(n===`add`){if(t===`-`)e.push(r);else{let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<=e.length&&e.splice(n,0,r)}}else if(n===`replace`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&(e[n]=r)}else if(n===`remove`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&e.splice(n,1)}}function OG(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}function kG(e){if(e==null)return null;let t=String(e).trim().toLowerCase();return[`1`,`true`,`yes`,`on`].includes(t)?!0:![`0`,`false`,`no`,`off`].includes(t)&&null}function AG(e,t=!1){if(e==null)return t;if(typeof e==`boolean`)return e;if(typeof e==`number`)return e===1;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return!1}function jG(e){if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t))return GW(t.map(e=>String(e)))}catch{}return GW(e.split(`,`))}let MG=/* @__PURE__ */ new Map;function NG(e){if(typeof document>`u`)return null;let t=`shadow-claw-site-config`;if(e){let n=e.getAttribute(`config`)?.trim();n&&(t=n.replace(/^#/,``))}let n=document.getElementById(t);if(!n?.textContent)return MG.delete(t),null;let r=MG.get(t);if(r&&r.rawText===n.textContent)return r.config;try{let e=JSON.parse(n.textContent);if(!e||typeof e!=`object`)return MG.delete(t),null;let r={...e};return MG.set(t,{rawText:n.textContent,config:r}),r}catch(e){return console.warn(`[ShadowClaw] Failed to parse site configuration from #${t}:`,e),null}}var PG=/* @__PURE__ */ t({OrchestratorStore:()=>HG,accumulateTokenUsage:()=>VG,orchestratorStore:()=>UG});function FG(e){if(e){if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:void 0}catch{return}}}function IG(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return typeof e==`number`&&e===1}function LG(e){return!!e}async function RG(e,t,n,r){if(!LG(r))return!0;if(!e.schedule)return await zG(e.id,t,n,r)!==`failed`;try{let r=t.replace(/\/$/,``);return(await fetch(`${r}/tasks`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,subscriberId:n})})).ok}catch{return!1}}async function zG(e,t,n,r){if(!LG(r))return`missing`;try{let r=t.replace(/\/$/,``),i=`subscriberId=${encodeURIComponent(n)}`,a=await fetch(`${r}/tasks/${encodeURIComponent(e)}?${i}`,{method:`DELETE`});return a.ok?`deleted`:a.status===404||a.status===405?`missing`:`failed`}catch{return`failed`}}async function BG(e,t,n,r){if(!LG(r))return null;try{let r=t.replace(/\/$/,``),i=await fetch(`${r}/tasks?groupId=${encodeURIComponent(e)}&subscriberId=${encodeURIComponent(n)}`,{method:`GET`});if(!i.ok||typeof i.json!=`function`)return null;let a=await i.json();return Array.isArray(a)?a.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.schedule==`string`&&typeof e.prompt==`string`).map(t=>({id:t.id,groupId:t.group_id||t.groupId||e,schedule:t.schedule,type:t.type,prompt:t.prompt,tools:FG(t.tools),channel:typeof t.channel==`string`?t.channel:void 0,enabled:t.enabled===!0||t.enabled===1,lastRun:typeof t.lastRun==`number`?t.lastRun:typeof t.last_run==`number`?t.last_run:null,createdAt:typeof t.createdAt==`number`?t.createdAt:typeof t.created_at==`number`?t.created_at:Date.now(),name:typeof t.name==`string`?t.name:void 0,order:typeof t.order==`number`?t.order:typeof t.task_order==`number`?t.task_order:void 0})):null}catch{return null}}function VG(e,t){let n=(e?.inputTokens??0)+(t.inputTokens??0),r=(e?.outputTokens??0)+(t.outputTokens??0),i=(e?.cacheReadTokens??0)+(t.cacheReadTokens??0),a=(e?.cacheCreationTokens??0)+(t.cacheCreationTokens??0);return{groupId:t.groupId||e?.groupId||``,inputTokens:n,outputTokens:r,cacheReadTokens:i,cacheCreationTokens:a,totalTokens:n+r+i+a,contextLimit:t.contextLimit||e?.contextLimit||0}}var HG=class e{static DEFAULT_PAGE_PATH=`MEMORY.md`;orchestrator;_activeGroupId;_activePage;_activePinnedPage;_defaultPinnedPage;_activityLog;_activityLogSessionStartedAtByGroup;_aguiAdapter;_aguiEvent;_contextUsage;_currentPath;_db;_error;_files;_gitProxyUrl;_groups;_hadPersistedActivePage;_initResolve;_isTyping;_lastOrchestratorDisplayState=`idle`;_messages;_modelDownloadProgress;_onlineReplayHandler;_pages;_pagesAllowList;_pagesDenyList;_peerStateByGroup;_proxyUrl;_ready;_remoteAgentStatusByGroup;_remoteAgentTypingByGroup;_replayingTaskSyncOutbox;_subscriberId;_sidebarDefaultPage;_state;_storageStatus;_streamingText;_tasks;_taskSyncOutbox;_tokenUsage;_tokenUsageAccumulator=null;_toolActivity;_unreadGroupIds;_useProxy;_vmBashFullInternetAccess;_whenInitialized;_whenReady;_readyResolve;constructor(){this._messages=new ve.State([]),this._isTyping=new ve.State(!1),this._storageStatus=new ve.State(null),this._toolActivity=new ve.State(null),this._modelDownloadProgress=new ve.State(null),this._activityLog=new ve.State([]),this._state=new ve.State(`idle`),this._tokenUsage=new ve.State(null),this._error=new ve.State(null),this._activeGroupId=new ve.State(v),this._ready=new ve.State(!1),this._tasks=new ve.State([]),this._files=new ve.State([]),this._currentPath=new ve.State(`.`),this._groups=new ve.State([]),this._unreadGroupIds=new ve.State(/* @__PURE__ */ new Set),this._streamingText=new ve.State(null),this._aguiEvent=new ve.State(null),this._contextUsage=new ve.State(null),this._useProxy=new ve.State(!1),this._proxyUrl=new ve.State(`/proxy`),this._gitProxyUrl=new ve.State(`/git-proxy`),this._vmBashFullInternetAccess=new ve.State(!1),this._activePage=new ve.State(`pages`);let e=NG()?.sidebar?.defaultPage,t=e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`;this._sidebarDefaultPage=new ve.State(t),this._pages=new ve.State([]),this._pagesAllowList=new ve.State([]),this._pagesDenyList=new ve.State([]),this._activePinnedPage=new ve.State(null),this._defaultPinnedPage=new ve.State(null),this._remoteAgentStatusByGroup=new ve.State(/* @__PURE__ */ new Map),this._remoteAgentTypingByGroup=new ve.State(/* @__PURE__ */ new Map),this._peerStateByGroup=new ve.State(/* @__PURE__ */ new Map),this._hadPersistedActivePage=!1,this._initResolve=null,this._whenInitialized=new Promise(e=>{this._initResolve=e}),this._readyResolve=null,this._whenReady=new Promise(e=>{this._readyResolve=e}),this.orchestrator=null,this._db=null,this._activityLogSessionStartedAtByGroup=/* @__PURE__ */ new Map,this._taskSyncOutbox=[],this._replayingTaskSyncOutbox=!1,this._subscriberId=null,this._onlineReplayHandler=null,this._aguiAdapter=null}get activeGroupId(){return this._activeGroupId.get()}get activePage(){return this._activePage.get()}get activePinnedPage(){return this._activePinnedPage.get()}get defaultPinnedPage(){return this._defaultPinnedPage.get()}get pagesAllowList(){return this._pagesAllowList.get()}get pagesDenyList(){return this._pagesDenyList.get()}isPageAllowed(e,t){return tG(e,{allowList:this._pagesAllowList.get(),denyList:this._pagesDenyList.get(),groupId:t??this._activeGroupId.get()})}get effectiveDefaultPage(){let e=this._defaultPinnedPage.get();return e&&this.isPageAllowed(e.path,e.groupId)?e:this._pages.get()[0]||null}get activityLog(){return this._activityLog.get()}get taskServerEnabled(){return this.orchestrator?.taskServerEnabled??!1}get aguiEvent(){return this._aguiEvent.get()}clearError(){this._error.set(null),this._state.get()===`error`&&this._state.set(`idle`)}get contextUsage(){return this._contextUsage.get()}get tokenUsageAccumulator(){return this._tokenUsageAccumulator}get currentPath(){return this._currentPath.get()}get error(){return this._error.get()}get files(){return this._files.get()}getPeerState(e){return this._peerStateByGroup.get().get(e)||null}getRemoteAgentStatus(e){return this._remoteAgentStatusByGroup.get().get(e)||`idle`}getState(){return{messages:this.messages,isTyping:this.isTyping,toolActivity:this.toolActivity,activityLog:this.activityLog,state:this.state,tokenUsage:this.tokenUsage,modelDownloadProgress:this.modelDownloadProgress,error:this.error,activeGroupId:this.activeGroupId,pages:this.pages,ready:this.ready,files:this.files,currentPath:this.currentPath,streamingText:this.streamingText,contextUsage:this.contextUsage}}getTasksForBackup(){return this._tasks.get()}get gitProxyUrl(){return this._gitProxyUrl.get()}get groups(){return this._groups.get()}get hadPersistedActivePage(){return this._hadPersistedActivePage}isRemoteAgentTyping(e){return this._remoteAgentTypingByGroup.get().get(e)||!1}get isTyping(){return this._isTyping.get()}get messages(){return this._messages.get()}get modelDownloadProgress(){return this._modelDownloadProgress.get()}get pages(){return this._pages.get()}get proxyUrl(){return this._proxyUrl.get()}get ready(){return this._ready.get()}sendMessage(e,t=[],n){n===void 0?this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t):this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t,n)}async sendFileToPeer(e,t=this._activeGroupId.get(),n){let r=t.startsWith(`peer:`),i=t.startsWith(`room:`);if(!r&&!i){let e=`Can only send files to peers in a peer or room conversation.`;throw wG(e,4500),Error(e)}let a=this.orchestrator?.router;if(!a){let e=`Network router is not initialized.`;throw wG(e,4500),Error(e)}let o=n?.fileName||e.split(`/`).pop()||e,s=n?.mimeType||`application/octet-stream`,c=n?.size||0;a.setTyping(t,!0);try{let n={path:e,fileName:o,mimeType:s,size:c};if(await a.send(t,``,[n]),this._db){let e={id:fe(),groupId:t,sender:`You`,content:``,timestamp:Date.now(),channel:i?`room`:`peerjs`,attachments:[n],isFromMe:!1,isTrigger:!1};await EW(this._db,e),this.orchestrator?.events.emit(`message`,e)}CG(`Sent ${o} to ${i?`room peers`:`peer`}`,2500)}catch(e){let t=e instanceof Error?e.message:String(e);throw console.error(`sendFileToPeer error:`,e),wG(`Failed to send file: ${t}`,6e3),e}finally{a.setTyping(t,!1)}}setActiveGroup(e,t,n=this._activePage.get()===`chat`){if(this._activeGroupId.set(t),this._messages.set([]),this._activityLog.set([]),this._error.set(null),this._isTyping.set(!1),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._currentPath.set(`.`),n){let e=new Set(this._unreadGroupIds.get());e.delete(t)&&this._unreadGroupIds.set(e)}this.loadHistory(),this.loadTasks(e),this.loadFiles(e)}setReady(e=!0){this._ready.set(e),e&&this._readyResolve&&this._readyResolve()}setRemoteAgentStatus(e,t){let n=this._remoteAgentStatusByGroup.get(),r=new Map(n);r.set(e,t),this._remoteAgentStatusByGroup.set(r)}setRemoteAgentTyping(e,t){let n=this._remoteAgentTypingByGroup.get(),r=new Map(n);t?r.set(e,!0):r.delete(e),this._remoteAgentTypingByGroup.set(r)}get sidebarDefaultPage(){return this._sidebarDefaultPage.get()}get state(){return this._state.get()}stopCurrentRequest(){this.orchestrator?.stopCurrentRequest?.(this._activeGroupId.get())}get storageStatus(){return this._storageStatus.get()}get streamingText(){return this._streamingText.get()}syncHostWorkspaceToVM(){ZU(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){QU(this.orchestrator,this._activeGroupId.get())}get tasks(){return this._tasks.get()}get tokenUsage(){return this._tokenUsage.get()}get toolActivity(){return this._toolActivity.get()}get unreadGroupIds(){return this._unreadGroupIds.get()}get useProxy(){return this._useProxy.get()}get vmBashFullInternetAccess(){return this._vmBashFullInternetAccess.get()}get whenInitialized(){return this._whenInitialized}async resetSiteConfigSeed(e){await pe(e,b.SITE_CONFIG_SEEDED,!1)}get whenReady(){return this._whenReady}async addPage(e,t,n=this._activeGroupId.get()){let r=n===`br:main`?this.normalizePagePath(t):t.trim();if(!r||!this.isPageAllowed(r,n))return;let i=this._pages.get();i.some(e=>e.path===r&&e.groupId===n)||(this.setPages([...i,{groupId:n,path:r}]),await WW(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await VU(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await de(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r)await zG(t.id,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)===`failed`?(console.warn(`Failed to delete task "${t.id}" from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t.id,queuedAt:Date.now()})):await cW(e,t.id);await this.loadTasks(e)}async cloneConversation(e,t){let n=await SW(e,t);if(!n)return null;await aW(e,t,n.groupId),await oW(e,t,n.groupId);try{let r=await I(e,t,`MEMORY.md`);r&&await xe(e,n.groupId,`MEMORY.md`,r)}catch{}try{await AW(e,t,n.groupId,`attachments`)}catch{}return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async compactContext(e){if(!this.orchestrator)return;let{compactContext:t}=await import(`./compact-context-CX4H8V57.js`);return t(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await gW(e,t);return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await yW(e,t),await iW(e,t),await this.loadGroups(e),this._activeGroupId.get()===t)){let t=this._groups.get()[0]?.groupId||`br:main`;this.setActiveGroup(e,t)}}async deleteMessage(e,t){await sW(e,t),await this.loadHistory(),this.orchestrator?.refreshContextUsage&&await this.orchestrator.refreshContextUsage(e,this._activeGroupId.get())}async deleteTask(e,t){let n=await this.getSubscriberId(e);if(await zG(t,this.getTaskServerBaseUrl(),n,this.orchestrator?.taskServerEnabled??!1)===`failed`)throw console.warn(`Failed to delete task from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t,queuedAt:Date.now()}),Error(`Failed to delete scheduled task on server; task kept locally.`);await cW(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await bW(e);if(!r.find(e=>e.groupId===n)){let i=[...r],a=``;if(this.orchestrator?.peerjsPeerAliases){for(let[e,n]of Object.entries(this.orchestrator.peerjsPeerAliases))if(n===t){a=e;break}}i.push({groupId:n,name:`Peer: ${a||t.substring(0,8)}`,createdAt:Date.now()}),await hW(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await PW(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,t){this._db=e,this.orchestrator=t,this._taskSyncOutbox=this.parseTaskSyncOutbox(await A(e,b.TASK_SYNC_OUTBOX)),await this.replayTaskSyncOutbox(e),typeof window<`u`&&!this._onlineReplayHandler&&(this._onlineReplayHandler=()=>{this._db&&this.replayTaskSyncOutbox(this._db)},window.addEventListener(`online`,this._onlineReplayHandler)),t.events.on(`a2ui-surface`,async({groupId:t,envelope:n})=>{t&&this.ensureGroupExists(e,t);let r=this._messages.get(),i=r.findIndex(e=>e.a2uiEnvelopes?.some(e=>e.surfaceId===n.surfaceId));if(i!==-1){let t=r[i],a=[...t.a2uiEnvelopes||[],n],o={...t,a2uiEnvelopes:a},s=[...r];s[i]=o,this._messages.set(s),await EW(e,o)}else{let i=!t.startsWith(`peer:`),a={id:fe(),groupId:t,sender:i?`agent`:t.replace(/^peer:/,``),content:``,timestamp:Date.now(),channel:t.startsWith(`peer:`)?`peerjs`:`browser`,isFromMe:i,isTrigger:!1,a2uiEnvelopes:[n]};t===this._activeGroupId.get()&&this._messages.set([...r,a]),await EW(e,a)}}),t.events.on(`message`,t=>{if(t.groupId&&this.ensureGroupExists(e,t.groupId,t.timestamp),t.groupId&&t.groupId!==this._activeGroupId.get()){let e=new Set(this._unreadGroupIds.get());e.add(t.groupId),this._unreadGroupIds.set(e)}else t.isFromMe&&this._streamingText.get()!==null&&this._streamingText.set(null),this._messages.set([...this._messages.get(),t])}),t.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),t.events.on(`tool-activity`,({groupId:e,tool:t,status:n})=>{e&&e!==this._activeGroupId.get()||this._toolActivity.set(n===`running`?{tool:t,status:n}:null)}),t.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),t.events.on(`thinking-log`,e=>{e.groupId&&e.groupId!==this._activeGroupId.get()||(e.level===`info`&&e.label===`Starting`?this._activityLog.set([e]):this._activityLog.set([...this._activityLog.get(),e]),this.forwardActivityLogEntryToServer(e))}),t.events.on(`state-change`,e=>{let t=typeof e==`string`?e:e.state,n=typeof e==`string`?void 0:e.groupId;if(n&&n!==this._activeGroupId.get())return;let r=this._lastOrchestratorDisplayState;this._lastOrchestratorDisplayState=t,this._state.set(t),t===`idle`&&(this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null)),t===`thinking`&&r!==`thinking`&&r!==`responding`&&(this._tokenUsageAccumulator=null)}),t.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),t.events.on(`session-reset`,()=>{this._messages.set([]),this._activityLog.set([]),this._tokenUsageAccumulator=null,this._tokenUsage.set(null),this._contextUsage.set(null),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._isTyping.set(!1),this._state.set(`idle`)}),t.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),t.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=VG(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),t.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),t.events.on(`ready`,()=>{this._ready.set(!0)}),t.events.on(`task-change`,()=>{this.loadTasks(e)}),t.events.on(`file-change`,()=>{this.loadFiles(e)}),t.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),t.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),t.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),t.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),t.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new bG(t.events),this._aguiAdapter.start(),typeof window<`u`&&window.addEventListener(`shadow-claw-agui-event`,(e=>{e.detail.groupId===this._activeGroupId.get()&&this._aguiEvent.set(e.detail);let t=e.detail.event;if(t){if(t.type===`STATE_SNAPSHOT`){let n=new Map(this._peerStateByGroup.get());n.set(e.detail.groupId,t.snapshot||{}),this._peerStateByGroup.set(n)}else if(t.type===`STATE_DELTA`){let n=new Map(this._peerStateByGroup.get()),r=TG(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await ce(e),ue(),Ee(),await XU();let n=await A(e,b.PAGES_ALLOW_LIST),r=await A(e,b.PAGES_DENY_LIST);n&&this._pagesAllowList.set(jG(String(n))),r&&this._pagesDenyList.set(jG(String(r))),await XU();let i=typeof document<`u`&&document.getElementById(`shadow-claw-static-routing`)!==null,a=await A(e,b.PAGES_LIST),o=a==null?[]:this.parsePagesList(a),c=await yG(e,v,o);c.length>0?(this.setPages(c),await this.persistPages(e)):await this.ensureDefaultPage(e),await XU(),await this.applySiteConfigDefaults(e),await XU(),await this.loadGroups(e);let l=await A(e,b.LAST_ACTIVE_GROUP);l&&l!==this._activeGroupId.get()&&this._activeGroupId.set(l),await XU();let u=await A(e,b.LAST_ACTIVE_PAGE);u&&(this._activePage.set(u),this._hadPersistedActivePage=!0);let d=await A(e,b.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(d));let f=hG(),p=null;if(f&&(p=s(f)),!p){let t=await A(e,b.DEFAULT_PINNED_PAGE);t&&(p=s(t))}p&&this.isPageAllowed(p.path,p.groupId)&&this._defaultPinnedPage.set(p),await XU();let m=typeof window<`u`&&window.history?window.history.state:null,h=!!(m?.inFeedScroll||m?.scrollSpy||m?.suppressRouter)||typeof window<`u`&&window.location&&(()=>{let e=window.location.pathname||`/`,t=w();t!==`/`&&e.startsWith(t)&&(e=`/`+e.slice(t.length));let n=e.split(`/`).filter(Boolean);return n.length===0||n.length===1&&n[0]===`index.html`})(),g=!1;if(h&&p&&this.isPageAllowed(p.path,p.groupId)&&(this._activePinnedPage.set(p),g=!0),!g){let t=await A(e,b.LAST_SELECTED_PINNED_PAGE);if(t)try{let e=JSON.parse(t);e&&typeof e.path==`string`&&typeof e.groupId==`string`&&this.isPageAllowed(e.path,e.groupId)&&(this._activePinnedPage.set(e),g=!0)}catch{}}!g&&h&&this.effectiveDefaultPage&&this.isPageAllowed(this.effectiveDefaultPage.path,this.effectiveDefaultPage.groupId)&&(this._activePinnedPage.set(this.effectiveDefaultPage),g=!0),this.orchestrator&&(this._useProxy.set(this.orchestrator.useProxy),this._proxyUrl.set(this.orchestrator.proxyUrl),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess));let[_,y,x]=await Promise.all([A(e,b.SIDEBAR_CHAT_HIDDEN),A(e,b.SIDEBAR_TASKS_HIDDEN),A(e,b.SIDEBAR_FILES_HIDDEN)]),S=NG(),C=S?.sidebar?.chatHidden,T=S?.sidebar?.tasksHidden,E=S?.sidebar?.filesHidden,ee=_==null?!!C:AG(_),D=y==null?!!T:AG(y),O=x==null?!!E:AG(x),k=()=>{let t=[];(!ee||this.activePage===`chat`)&&t.push(this.loadHistory()),(!D||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),Promise.all(t).catch(e=>{console.warn(`Secondary background store loads failed:`,e)})};if(i)typeof window.requestIdleCallback==`function`?window.requestIdleCallback(k,{timeout:2e3}):setTimeout(k,100);else{let t=[];(!ee||this.activePage===`chat`)&&t.push(this.loadHistory()),(!D||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),await Promise.all(t)}await XU(),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await ae(e));let r=await MW(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await bW(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await dW(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await de(e),r=n.filter(e=>e.groupId===t);r.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(r);let i=await this.getSubscriberId(e),a=await BG(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1);if(!a)return;let o=new Set(n.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));if(s.length===0)return;for(let t of s)await DW(e,t);let c=[...r,...s];c.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(c)}async navigateBackFolder(e){let t=this._currentPath.get();if(t===`.`)return;let n=t.split(`/`).filter(Boolean);n.pop();let r=n.length===0?`.`:n.join(`/`);await this.setCurrentPath(e,r)}async navigateIntoFolder(e,t){let n=this._currentPath.get(),r=n===`.`?t.replace(/\/$/,``):`${n}/${t.replace(/\/$/,``)}`;try{await this.setCurrentPath(e,r)}catch(t){console.error(`Failed to navigate into folder in store:`,t),wG(`Folder not found: ${r}`,4500),await this.loadFiles(e)}}async newSession(e){await this.orchestrator?.newSession?.(e,this._activeGroupId.get()),await this.loadHistory()}async removePage(t,n,r=this._activeGroupId.get()){let i=this.normalizePagePath(n);if(!i)return;let a=this._pages.get();if(!a.some(e=>e.path===i&&e.groupId===r))return;let o=a.filter(e=>e.path!==i||e.groupId!==r);await UW(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await VU(t,!0);let c=s||await BU(t);if(o.length===0&&!c){if(await HU(t,`br:main`))o.push({groupId:v,path:e.DEFAULT_PAGE_PATH});else return}this.setPages(o);let l=this._defaultPinnedPage.get();l&&l.path===i&&l.groupId===r&&await this.setDefaultPinnedPage(t,null),await this.persistPages(t)}async removeAllPages(e){let t=[...this._pages.get()];for(let n of t)await UW(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await VU(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await _W(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await xW(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await kW(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await RG(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync reordered task "${t.id}" to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}async replayTaskSyncOutbox(e){if(!(this._replayingTaskSyncOutbox||this._taskSyncOutbox.length===0)){this._replayingTaskSyncOutbox=!0;try{let t=await this.getSubscriberId(e),n=[];for(let e of this._taskSyncOutbox){let r=this.getTaskServerBaseUrl();(e.type===`upsert`?await RG(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await zG(e.id,r,t,this.orchestrator?.taskServerEnabled??!1))||n.push(e)}this._taskSyncOutbox=this.compactTaskSyncOutbox(n),await this.persistTaskSyncOutbox(e)}finally{this._replayingTaskSyncOutbox=!1}}}async resetToRootFolder(e){await this.setCurrentPath(e,`.`)}async restartCurrentRequest(){return this.orchestrator?.restartCurrentRequest?this.orchestrator.restartCurrentRequest(this._activeGroupId.get()):!1}async restoreTasksFromBackup(e,t){await this.clearAllTasks(e);let n=this._activeGroupId.get();for(let r of t){let t={...r,groupId:n,id:crypto.randomUUID?crypto.randomUUID():`task-${Date.now()}-${Math.random()}`};await this.upsertTask(e,t,{reloadTasks:!1})}await this.loadTasks(e)}async runTask(e,t=!1){let n=this._db;if(t&&n&&(await OW(e.id,Date.now()),await this.loadTasks(n)),e.type===`tools`&&Array.isArray(e.tools)&&e.tools.length>0){if(this.orchestrator?.agentWorker){let n=e.subagent?`subagent:${fe()}`:e.groupId;this.orchestrator.agentWorker.postMessage({type:`execute-task-tools`,payload:{groupId:n,tools:e.tools,isManual:t}})}else console.error(`Agent worker not available to execute tool task.`)}else{if(!e.groupId){console.error(`Task ${e.id} has no groupId - refusing to execute in active conversation to prevent context pollution.`);return}this.orchestrator?.browserChat?.submit(e.prompt,e.groupId,[],void 0,e.freshContext,e.subagent)}}async setActivePage(e,t){this._activePage.set(t),await pe(e,b.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await pe(e,b.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){t&&!this.isPageAllowed(t.path,t.groupId)&&(t=this.effectiveDefaultPage),this._activePinnedPage.set(t),t?await pe(e,b.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await pe(e,b.LAST_SELECTED_PINNED_PAGE,null)}async setDefaultPinnedPage(e,t){if(t&&!this.isPageAllowed(t.path,t.groupId))return;let n=this._defaultPinnedPage.get(),r=n&&t&&n.path===t.path&&n.groupId===t.groupId?null:t;this._defaultPinnedPage.set(r),r?await pe(e,b.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await pe(e,b.DEFAULT_PINNED_PAGE,null)}async reorderPages(e,t){this.setPages(t),await this.persistPages(e)}async setCurrentPath(e,t){let n=t.replace(/^\/+|\/+$/g,``)||`.`,r=this._activeGroupId.get();this._storageStatus.set(await ae(e));let i=await MW(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await eW(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await tW(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await nW(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await rW(this.orchestrator,e,t),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess))}async switchConversation(e,t,n){this.setActiveGroup(e,t,n??this._activePage.get()===`chat`),await pe(e,b.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await DW(e,r),await this.loadTasks(e),await RG(r,this.getTaskServerBaseUrl(),await this.getSubscriberId(e),this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to update task on server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:r.id,task:r,queuedAt:Date.now()}))}async updateConversationPinnedProvider(e,t,n,r,i){await CW(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await TW(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await wW(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await vW(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await DW(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await RG(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync task to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}compactTaskSyncOutbox(e){let t=/* @__PURE__ */ new Map;return e.forEach((e,n)=>{t.set(e.id,n)}),e.filter((e,n)=>t.get(e.id)===n)}deriveGroupName(e){return e.startsWith(`tg:`)?`Telegram ${e.slice(3)}`:e.startsWith(`im:`)?`iMessage ${e.slice(3)}`:e.startsWith(`br:`)?e===`br:main`?`Main`:`Browser Conversation`:`Conversation`}getActivityLogSessionStartedAt(e){let t=this._activityLogSessionStartedAtByGroup.get(e);if(t)return t;let n=(/* @__PURE__ */ new Date()).toISOString();return this._activityLogSessionStartedAtByGroup.set(e,n),n}getTaskServerBaseUrl(){return this.orchestrator?.taskServerUrl??`/schedule`}async getSubscriberId(e){if(this._subscriberId)return this._subscriberId;let t=await uW(e);return this._subscriberId=t,t}normalizePagePath(t){let n=t.trim().replace(/^\/+/,``).replace(/\/+/g,`/`);return n===`main/memory.md`?e.DEFAULT_PAGE_PATH:n}normalizeSidebarDefaultPage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`}parsePagesList(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{groupId:v,path:this.normalizePagePath(e)};if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.path!=`string`)return null;let n=typeof t.groupId==`string`&&t.groupId.trim().length>0?t.groupId:v,r=n===`br:main`?this.normalizePagePath(t.path):t.path.trim();return r?{groupId:n,path:r}:null}).filter(e=>!!e).filter((e,t,n)=>{let r=`${e.groupId}\u0000${e.path}`;return t===n.findIndex(e=>`${e.groupId}\u0000${e.path}`===r)}):[]}catch{return[]}}parseTaskSyncOutbox(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>!!e&&typeof e==`object`).filter(e=>e.type===`upsert`||e.type===`delete`).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({...e,queuedAt:typeof e.queuedAt==`number`?e.queuedAt:Date.now()}));return this.compactTaskSyncOutbox(n)}catch{return[]}}resolveSidebarDefaultPageForActivePage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:this._sidebarDefaultPage.get()}setPages(e){let t=e.filter(e=>this.isPageAllowed(e.path,e.groupId)),n=t.filter(e=>e.path.toLowerCase()===`memory.md`),r=t.filter(e=>e.path.toLowerCase()!==`memory.md`);this._pages.set([...r,...n])}async ensureDefaultPage(t){if(await BU(t))return;let n=await HU(t,v);await qU(t,v),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:v,path:e.DEFAULT_PAGE_PATH}]),await this.persistPages(t))}async ensureGroupExists(e,t,n){let r=this._groups.get();if(r.some(e=>e.groupId===t))return;let i=[...r,{groupId:t,name:this.deriveGroupName(t),createdAt:n||Date.now()}];this._groups.set(i);try{await hW(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!IG(await A(this._db,b.ACTIVITY_LOG_DISK_LOGGING_ENABLED)))return;let t=typeof e.groupId==`string`&&e.groupId?e.groupId:this._activeGroupId.get();if(!t)return;let n=typeof e.message==`string`?e.message.trim():``;if(!n)return;e.level===`info`&&e.label===`Starting`&&this._activityLogSessionStartedAtByGroup.set(t,(/* @__PURE__ */ new Date()).toISOString());let r=this.getActivityLogSessionStartedAt(t);try{await fetch(`/activity-log`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({groupId:t,level:e.level,label:e.label,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString(),sessionStartedAt:r})})}catch(e){console.warn(`Failed to persist activity log entry to server:`,e)}}scheduleBackgroundStaticMainSiteSeeding(e){if(typeof window>`u`)return;let t=async()=>{try{if(await iG(e,`br:main`))return;let t=await A(e,b.PAGES_LIST),n=t==null?[]:this.parsePagesList(t),r=await yG(e,v,n,{preferEmbedded:!1});r&&r.length>0&&(this.setPages(r),await this.persistPages(e))}catch(e){console.warn(`Background static main site seeding failed:`,e)}};typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:3e3}):setTimeout(()=>void t(),100)}async persistPages(e){await pe(e,b.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await pe(e,b.TASK_SYNC_OUTBOX,JSON.stringify(this._taskSyncOutbox))}async queueTaskSyncOutboxOperation(e,t){this._taskSyncOutbox=this.compactTaskSyncOutbox([...this._taskSyncOutbox,t]),await this.persistTaskSyncOutbox(e)}async applySiteConfigDefaults(e){if(typeof document<`u`)try{let t=NG();if(!t||typeof t!=`object`)return;me(t),ue(),Ee();let n=t.customElements;if((await bW(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await vW(e,v,void 0),(t.settings?.internetAccess??t.settings?.vm_bash_full_internet_access??t.settings?.fullInternetAccess??t.internetAccess)===!0&&await A(e,b.VM_BASH_FULL_INTERNET_ACCESS)!==`true`&&(await pe(e,b.VM_BASH_FULL_INTERNET_ACCESS,`true`),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=!0),this._vmBashFullInternetAccess.set(!0)),t.pages&&typeof t.pages==`object`){let{defaultPinnedPage:n}=t.pages;if(n&&typeof n==`string`){let t=s(n);t&&this.isPageAllowed(t.path,t.groupId)&&(this._defaultPinnedPage.set(t),await pe(e,b.DEFAULT_PINNED_PAGE,JSON.stringify(t)))}}let r=t.allowedCustomElements||(typeof n==`object`&&!Array.isArray(n)?n.allowedElements:void 0);r!==void 0&&(await A(e,b.ALLOWED_CUSTOM_ELEMENTS)??await pe(e,b.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(r)));let i=t.allowedCustomElementDomains||(typeof n==`object`&&!Array.isArray(n)?n.allowedDomains:void 0);if(i!==void 0&&(await A(e,b.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS)??await pe(e,b.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(i))),t.sidebar&&typeof t.sidebar==`object`){let{pagesHidden:n,chatHidden:r,tasksHidden:i,filesHidden:a,defaultPage:o}=t.sidebar;if(n!==void 0&&(await A(e,b.SIDEBAR_PAGES_HIDDEN)??await pe(e,b.SIDEBAR_PAGES_HIDDEN,String(!!n))),r!==void 0&&(await A(e,b.SIDEBAR_CHAT_HIDDEN)??await pe(e,b.SIDEBAR_CHAT_HIDDEN,String(!!r))),i!==void 0&&(await A(e,b.SIDEBAR_TASKS_HIDDEN)??await pe(e,b.SIDEBAR_TASKS_HIDDEN,String(!!i))),a!==void 0&&(await A(e,b.SIDEBAR_FILES_HIDDEN)??await pe(e,b.SIDEBAR_FILES_HIDDEN,String(!!a))),o&&typeof o==`string`){let t=this.normalizeSidebarDefaultPage(o);this._sidebarDefaultPage.set(t),await A(e,b.SIDEBAR_DEFAULT_PAGE)||await pe(e,b.SIDEBAR_DEFAULT_PAGE,o)}}if(t.settings&&typeof t.settings==`object`){let{assistantName:n,defaultProvider:r,provider:i,defaultModel:a,model:o}=t.settings;n&&typeof n==`string`&&(await A(e,b.ASSISTANT_NAME)||await pe(e,b.ASSISTANT_NAME,n));let s=r??i;if(typeof s==`string`&&s.trim().length>0&&!await A(e,b.PROVIDER)){let t=s.trim();await pe(e,b.PROVIDER,t),this.orchestrator&&(this.orchestrator.provider=t)}let c=a??o;if(typeof c==`string`&&c.trim().length>0&&!await A(e,b.MODEL)){let t=c.trim();await pe(e,b.MODEL,t),this.orchestrator&&(this.orchestrator.model=t)}let l=t.settings.internetAccess??t.settings.vm_bash_full_internet_access??t.settings.fullInternetAccess??t.internetAccess;typeof l==`boolean`&&(await A(e,b.VM_BASH_FULL_INTERNET_ACCESS)??(await pe(e,b.VM_BASH_FULL_INTERNET_ACCESS,String(l)),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=l),this._vmBashFullInternetAccess.set(l)))}let a=(t.settings&&typeof t.settings==`object`?t.settings.defaultToolsProfile:void 0)??t.defaultToolsProfile;if(typeof a==`string`&&a.trim().length>0&&!await A(e,b.ACTIVE_TOOL_PROFILE)){let t=a.trim();if(t.toLowerCase()===`none`)await we.deactivateProfile(e);else{let n=we.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await we.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(t.pages&&typeof t.pages==`object`){let{defaultPinnedPage:n}=t.pages;n&&typeof n==`string`&&(await A(e,b.DEFAULT_PINNED_PAGE)||await pe(e,b.DEFAULT_PINNED_PAGE,n))}let o=t.pages?.allowList??t.pages?.allowlist??t.allowList??t.allowlist,c=t.pages?.denyList??t.pages?.denylist??t.denyList??t.denylist;if(Array.isArray(o)&&await A(e,b.PAGES_ALLOW_LIST)==null){let t=GW(o.map(String));this._pagesAllowList.set(t),await pe(e,b.PAGES_ALLOW_LIST,JSON.stringify(t))}if(Array.isArray(c)&&await A(e,b.PAGES_DENY_LIST)==null){let t=GW(c.map(String));this._pagesDenyList.set(t),await pe(e,b.PAGES_DENY_LIST,JSON.stringify(t))}await pe(e,b.SITE_CONFIG_SEEDED,`true`);let l=this._pages.get(),u=l.filter(e=>this.isPageAllowed(e.path,e.groupId));u.length!==l.length&&(this.setPages(u),await this.persistPages(e));let d=this._activePinnedPage.get();d&&!this.isPageAllowed(d.path,d.groupId)&&await this.setActivePinnedPage(e,this.effectiveDefaultPage);let f=this._defaultPinnedPage.get();if(f&&!this.isPageAllowed(f.path,f.groupId)&&await this.setDefaultPinnedPage(e,null),Array.isArray(t.enabledTools)){let n=t.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await we.setAllEnabled(e,n),await we.setAllDeclarativeEnabled(e,n)}await pe(e,b.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const UG=new HG;async function WG(e,t,n){let r=await re(e,t),{dirs:i,filename:a}=M(n),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a),t===`br:main`&&i.length===0&&(a===`MEMORY.md`?await VU(e,!0):a===`index.html`&&await KU(e,!0));try{await UW(e,t,n)}catch{}try{await UG.removePage(e,n,t)}catch{}}async function GG(e,t,n){let r=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean);if(r.length===0)throw Error(`Empty directory path`);for(let n=0;n<2;n++)try{let n=await re(e,t);for(let e of r)n=await n.getDirectoryHandle(e,{create:!0});return}catch(e){if(n===0&&oe(e)){ie();continue}throw e}}var KG=class extends zL{db;groupId;workspacePrefix;constructor(e,t,n,r=`/home/user`){super(n),this.db=e,this.groupId=t,this.workspacePrefix=r}async appendFile(e,t){await super.appendFile(e,t);let n=this._toDbPath(e);if(n!==null){let t=await this._readPathContent(e);await xe(this.db,this.groupId,n,t)}}async cp(e,t,n){await super.cp(e,t,n);let r=this._toDbPath(t);if(r!==null)try{let e=await super.stat(t);if(!this._isDirectoryStat(e)){let e=await this._readPathContent(t);await xe(this.db,this.groupId,r,e)}}catch{}}async mkdir(e,t){await super.mkdir(e,t);let n=this._toDbPath(e);n!==null&&n!==``&&await GG(this.db,this.groupId,n)}async mv(e,t){await super.mv(e,t);let n=!1,r=t,i=this._toDbPath(t);if(i!==null)try{let i=await super.stat(t);if(this._isDirectoryStat(i)){let n=this._basename(e);n&&(r=this._joinPath(t,n))}let a=await super.stat(r);if(!this._isDirectoryStat(a)){let e=this._toDbPath(r);if(e!==null){let t=await this._readPathContent(r);await xe(this.db,this.groupId,e,t),n=!0}}}catch{}let a=this._toDbPath(e);if(a!==null)try{(i===null||n)&&await WG(this.db,this.groupId,a)}catch{}}async rm(e,t){await super.rm(e,t);let n=this._toDbPath(e);if(n!==null)try{await WG(this.db,this.groupId,n)}catch{}}async writeFile(e,t,n){await super.writeFile(e,t,n);let r=this._toDbPath(e);if(r!==null){let t=await this._readPathContent(e);await xe(this.db,this.groupId,r,t)}}_basename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]||``}_isDirectoryStat(e){return e&&typeof e.isDirectory==`function`?!!e.isDirectory():!!e?.isDirectory}_joinPath(e,t){let n=e.replace(/\/+$/,``);return n?`${n}/${t}`:`/${t}`}_toDbPath(e){return e.startsWith(this.workspacePrefix+`/`)?e.slice(this.workspacePrefix.length+1):e===this.workspacePrefix?``:null}async _readPathContent(e){try{return await super.readFileBuffer(e)}catch{return await super.readFile(e)}}};async function qG(e,t){let n={},r=/* @__PURE__ */ new Set,i=`/home/user`;async function a(o){let s=await MW(e,t,o);for(let c of s)if(c.endsWith(`/`)){let e=c.slice(0,-1),t=o===`.`?e:`${o}/${e}`;r.add(t),await a(t)}else{let r=o===`.`?c:`${o}/${c}`,a=`${i}/${r}`;n[a]=async()=>{try{return await IU(e,t,r)}catch{return``}}}}await a(`.`);let o=new KG(e,t,n,i);for(let e of[...r].sort((e,t)=>e.split(`/`).length-t.split(`/`).length))try{o.mkdirSync(`${i}/${e}`,{recursive:!0})}catch{}return o}async function JG(e,t,n,r={},i=30,a=!1){try{let i=await new MU({fs:await qG(e,n),network:{dangerouslyAllowFullInternetAccess:a,denyPrivateRanges:!a}}).exec(t,{env:{HOME:`/home/user`,PATH:`/usr/bin`,PWD:`/home/user`,...r}});return{stdout:i.stdout||``,stderr:i.stderr||``,exitCode:i.exitCode??0}}catch(e){return{stdout:``,stderr:e instanceof Error?e.message:String(e),exitCode:1}}}function YG(e){let t=e.stdout||``;return e.stderr&&(t+=(t?`
1803
+ `)}\n${s}`}return s}async function fG(e={}){let t=()=>{let e=null;if(typeof document<`u`){let t=document.getElementById(`shadow-claw-static-manifest`);if(t&&t.textContent)try{let n=JSON.parse(t.textContent);n&&Array.isArray(n.pages)&&(e={...n,pages:[...n.pages]})}catch(e){console.warn(`Failed to parse embedded static main manifest:`,e)}let n=document.querySelectorAll(`script[type="text/markdown"][data-shadow-claw-page]`);if(n.length>0){e||={pages:[]};for(let t of Array.from(n)){let n=t.getAttribute(`data-shadow-claw-page`)?.trim();if(n){let r=t.textContent||``;r=nG(r),!r.trim()&&/^memory\.(md|markdown)$/iu.test(n)&&(r=LU),!r.trim()&&(n===`index.html`||/^index\.(html?|xhtml)$/iu.test(n))&&(r=dG(n)??UU);let i=e.pages.findIndex(e=>e.displayPath===n);i>=0?e.pages[i].content=r:e.pages.push({displayPath:n,content:r})}}}let r=document.getElementById(`shadow-claw-site-config`);if(r?.textContent)try{let t=JSON.parse(r.textContent);if(Array.isArray(t?.pages?.files)){e||={pages:[]};for(let n of t.pages.files)if(typeof n==`string`&&n.trim()){let t=n.trim(),r=``;/^memory\.(md|markdown)$/iu.test(t)?r=LU:(t===`index.html`||/^index\.(html?|xhtml)$/iu.test(t))&&(r=dG(t)??UU),e.pages.some(e=>e.displayPath===t)||e.pages.push({displayPath:t,content:r})}}}catch{}let i=uG();if(i){e||={pages:[]};let t=i.getAttribute(`data-initial-path`)?.trim()||`index.html`;if(!e.pages.some(e=>e.displayPath===t)){let n=dG(t)??UU;e.pages.push({displayPath:t,content:n})}e.pages.some(e=>/^memory\.(md|markdown)$/iu.test(e.displayPath))||e.pages.push({displayPath:`MEMORY.md`,content:LU})}}return e};if(e.preferEmbedded!==!1){let e=t();if(e&&e.pages.length>0)return e}if(e.fetchFallback!==!1){let e=await cG();if(e&&e.pages.length>0)return e}if(e.preferEmbedded===!1){let e=t();if(e&&e.pages.length>0)return e}return{pages:[{displayPath:`index.html`,content:UU},{displayPath:`MEMORY.md`,content:LU}]}}async function pG(e,t,n=[]){for(let[r,i]of Object.entries(t))if(r===`purgePreRenderedStaticPages`&&i===!0){if(n.length>0){let t=n[0],r=n.slice(1).join(`/`);try{r?await zW(e,t,r):await RW(e,t)}catch(e){console.warn(`Failed to purge pre-rendered static pages for ${t}/${r}:`,e)}}}else typeof i==`object`&&i&&await pG(e,i,[...n,r])}function mG(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);if(t?.pages?.sortOrder===`desc`)return`desc`;if(t?.pages?.sortOrder===`asc`)return`asc`}}catch{}return`desc`}function hG(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent)?.pages?.defaultPinnedPage;if(typeof t==`string`&&t.trim().length>0)return t.trim()}}catch{}return null}function gG(){if(typeof document<`u`)try{let e=document.getElementById(`shadow-claw-site-config`);if(e?.textContent){let t=JSON.parse(e.textContent);return{allowList:GW(t?.pages?.allowList??t?.pages?.allowlist??t?.allowList??t?.allowlist??[]),denyList:GW(t?.pages?.denyList??t?.pages?.denylist??t?.denyList??t?.denylist??[])}}}catch{}return{allowList:[],denyList:[]}}function _G(e,t){let n=t??mG();return[...e].sort((e,t)=>{let r=e.path,i=t.path,a=r.split(`/`).pop()||``,o=i.split(`/`).pop()||``,s=/^index\.(html?|xhtml)$/iu.test(a),c=/^index\.(html?|xhtml)$/iu.test(o);if(s&&!c)return-1;if(!s&&c)return 1;let l=/^memory\.(md|markdown)$/iu.test(a),u=/^memory\.(md|markdown)$/iu.test(o);return l&&!u?1:!l&&u?-1:n===`asc`?r.localeCompare(i,void 0,{numeric:!0,sensitivity:`base`}):i.localeCompare(r,void 0,{numeric:!0,sensitivity:`base`})})}async function vG(e,t,n=`sc:purge-id`,r=`static_main_site_purge_id`){let i=t??`__legacy_purge_pages__`;try{if(IW(n)===i)return!0}catch{}try{if(await A(e,r)===i){try{LW(n,i)}catch{}return!0}await pe(e,r,i);try{LW(n,i)}catch{}}catch{try{LW(n,i)}catch{}}return!1}async function yG(e,t=v,n=[],r={}){await qU(e,t);let i=await fG(r),a=!1;i.preRenderedStaticPages&&(await vG(e,i.purgeId)||(a=!0,await pG(e,i.preRenderedStaticPages)));let o=!1;if(t===`br:main`&&i.skillsPurgeId!==void 0&&!await vG(e,i.skillsPurgeId,`sc:skills-purge-id`,`static_main_skills_purge_id`)){o=!0;try{await zW(e,t,`.agents/skills/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}try{await zW(e,t,`.agents/tools/main`)}catch(e){if(!(e&&typeof e==`object`&&`name`in e&&e.name===`NotFoundError`))throw e}}for(let n of i.pages)if(n.content?.includes(`slug: "shadow-claw--purge-pages"`)){!a&&!await vG(e,i.purgeId)&&(a=!0,await RW(e,t));break}let s=t===`br:main`&&await BU(e),c=new Set(i.pages.map(e=>BW(t,e.displayPath))),l=a?n.filter(e=>e.groupId!==t||c.has(BW(e.groupId,e.path))):[...n],{allowList:u,denyList:d}=gG(),f=0;for(let n of i.pages)if(f++,f%5==0&&await new Promise(e=>setTimeout(e,0)),!n.content?.includes(`slug: "shadow-claw--purge-pages"`)&&tG(n.displayPath,{allowList:u,denyList:d,groupId:t})){if(/^memory\.(md|markdown)$/iu.test(n.displayPath)){if(s)continue;let r=typeof n.content==`string`&&n.content.trim().length>0&&n.content!==LU?n.content:void 0;if(r===void 0?await HU(e,t):await HU(e,t,r)){let e=BW(t,n.displayPath);l.some(t=>BW(t.groupId,t.path)===e)||l.push({groupId:t,path:n.displayPath})}}else if(!await HW(e,t,n.displayPath))try{if(!await P(e,t,n.displayPath)){let r=n.content;(typeof r!=`string`||!r.trim())&&(r=n.displayPath===`index.html`?dG(`index.html`)??UU:await lG(n.displayPath)??``),await xe(e,t,n.displayPath,r)}let r=BW(t,n.displayPath);l.some(e=>BW(e.groupId,e.path)===r)||l.push({groupId:t,path:n.displayPath})}catch(e){console.warn(`Failed to seed static page file ${n.displayPath}:`,e)}}if(t===`br:main`){for(let n of i.skills||[]){let r=`.agents/skills/main/${n.displayPath}`;try{await P(e,t,r)||await xe(e,t,r,n.content)}catch(e){console.warn(`Failed to seed skill file ${r}:`,e)}}for(let n of i.tools||[]){let r=`.agents/tools/main/${n.displayPath}`;try{(o||!await P(e,t,r))&&await xe(e,t,r,n.content)}catch(e){console.warn(`Failed to seed tool file ${r}:`,e)}}}let p=typeof document<`u`&&(document.getElementById(`shadow-claw-static-manifest`)!==null||document.querySelector(`script[type="text/markdown"][data-shadow-claw-page]`)!==null||uG()!==null);r.preferEmbedded!==!1&&p||await aG(e,t,!0);let m=l.filter(e=>tG(e.path,{allowList:u,denyList:d,groupId:e.groupId}));return Object.defineProperty(m,"didPurge",{value:a,enumerable:!1,writable:!0,configurable:!0}),Object.defineProperty(m,"didPurgeSkills",{value:o,enumerable:!1,writable:!0,configurable:!0}),_G(m)}var bG=class{_events;_handlers=[];_runs=/* @__PURE__ */ new Map;constructor(e){this._events=e}start(){this._listen(`streaming-start`,this._onStreamingStart),this._listen(`streaming-chunk`,this._onStreamingChunk),this._listen(`streaming-end`,this._onStreamingEnd),this._listen(`streaming-done`,this._onStreamingDone),this._listen(`streaming-error`,this._onStreamingError),this._listen(`tool-activity`,this._onToolActivity)}stop(){for(let{event:e,handler:t}of this._handlers)this._events.off(e,t);this._handlers=[],this._runs.clear()}_emit(e,t){window.dispatchEvent(new CustomEvent(`shadow-claw-agui-event`,{detail:{groupId:e,event:t}}))}_listen(e,t){this._events.on(e,t),this._handlers.push({event:e,handler:t})}_onStreamingChunk=({groupId:e,text:t})=>{let n=this._runs.get(e);n&&n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_CONTENT`,messageId:n.messageId,delta:t,timestamp:Date.now()})};_onStreamingDone=({groupId:e})=>{let t=this._runs.get(e);t&&(t.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_FINISHED`,threadId:t.threadId,runId:t.runId,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingEnd=({groupId:e})=>{let t=this._runs.get(e);t&&t.messageId&&(this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:t.messageId,timestamp:Date.now()}),t.messageId=null)};_onStreamingError=({groupId:e,error:t})=>{let n=this._runs.get(e);n&&(n.messageId&&this._emit(e,{type:`TEXT_MESSAGE_END`,messageId:n.messageId,timestamp:Date.now()}),this._emit(e,{type:`RUN_ERROR`,message:t||`Unknown streaming error`,timestamp:Date.now()}),this._runs.delete(e))};_onStreamingStart=({groupId:e})=>{let t=fe(),n=e,r=fe();this._runs.set(e,{runId:t,threadId:n,messageId:r,activeToolCallIds:/* @__PURE__ */ new Set}),this._emit(e,{type:`RUN_STARTED`,threadId:n,runId:t,timestamp:Date.now()}),this._emit(e,{type:`TEXT_MESSAGE_START`,messageId:r,role:`assistant`,timestamp:Date.now()})};_onToolActivity=({groupId:e,tool:t,status:n})=>{let r=this._runs.get(e);if(r){if(n===`running`){let n=fe();r.activeToolCallIds.add(n),this._emit(e,{type:`TOOL_CALL_START`,toolCallId:n,toolCallName:t,timestamp:Date.now()}),r._lastToolCallId=n}else if(n===`done`||n===`error`){let t=r._lastToolCallId;t&&(r.activeToolCallIds.delete(t),this._emit(e,{type:`TOOL_CALL_END`,toolCallId:t,timestamp:Date.now()}))}}}};const xG=new class{#e=new ve.State(0);#t=/* @__PURE__ */ new Map;#n=new ve.State([]);clear(){this.#t.forEach((e,t)=>this.clearTimer(t)),this.#t.clear(),this.#n.set([])}clearTimer(e){let t=this.#t.get(e);t?.timeoutId&&clearTimeout(t.timeoutId),this.#t.delete(e)}dismiss(e){this.clearTimer(e),this.#n.set(this.#n.get().filter(t=>t.id!==e))}pause(e){let t=this.#t.get(e);t&&t.timeoutId&&(clearTimeout(t.timeoutId),t.timeoutId=void 0,t.remaining=Math.max(0,t.remaining-(Date.now()-t.startedAt)),this.#t.set(e,t))}resolveAction(e){if(e&&typeof e.label==`string`&&typeof e.onClick==`function`)return e}resolveDuration(e){return typeof e!=`number`||Number.isNaN(e)||e<0?4e3:e}resolveType(e){return e&&[`success`,`warning`,`error`,`info`].includes(e)?e:`info`}resume(e){let t=this.#t.get(e);!t||t.timeoutId||t.remaining<=0||this.scheduleDismiss(e,t.remaining)}scheduleDismiss(e,t){this.clearTimer(e);let n=globalThis.setTimeout(()=>{this.dismiss(e)},t);this.#t.set(e,{timeoutId:n,remaining:t,startedAt:Date.now()})}show(e,t={}){let n=this.#e.get()+1;this.#e.set(n);let r={id:n,message:e,type:this.resolveType(t.type),duration:this.resolveDuration(t.duration),action:this.resolveAction(t.action),createdAt:Date.now()},i=[...this.#n.get(),r];if(i.length>5){let e=i[0];this.clearTimer(e.id),this.#n.set(i.slice(1))}else this.#n.set(i);return r.duration>0&&this.scheduleDismiss(r.id,r.duration),r.id}get toasts(){return this.#n.get()}async runAction(e){let t=this.#n.get().find(t=>t.id===e);t?.action&&await t.action.onClick()}};function SG(e,t={}){return xG.show(e,t)}function CG(e,t=4e3){return xG.show(e,{type:`success`,duration:t})}function wG(e,t=5e3){return xG.show(e,{type:`error`,duration:t})}function TG(e,t){if(!e||typeof e!=`object`)return e;let n=JSON.parse(JSON.stringify(e));for(let e of t)EG(n,e);return n}function EG(e,t){let{op:n,path:r,value:i}=t;if(!r||!r.startsWith(`/`))return;let a=r.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),o=a.pop();if(o===void 0)return;let s=e;for(let e of a){if(typeof s!=`object`||!s)return;s=s[e]}typeof s==`object`&&s&&(Array.isArray(s)?DG(s,o,n,i):OG(s,o,n,i))}function DG(e,t,n,r){if(n===`add`){if(t===`-`)e.push(r);else{let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<=e.length&&e.splice(n,0,r)}}else if(n===`replace`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&(e[n]=r)}else if(n===`remove`){let n=parseInt(t,10);!isNaN(n)&&n>=0&&n<e.length&&e.splice(n,1)}}function OG(e,t,n,r){n===`add`||n===`replace`?e[t]=r:n===`remove`&&delete e[t]}function kG(e){if(e==null)return null;let t=String(e).trim().toLowerCase();return[`1`,`true`,`yes`,`on`].includes(t)?!0:![`0`,`false`,`no`,`off`].includes(t)&&null}function AG(e,t=!1){if(e==null)return t;if(typeof e==`boolean`)return e;if(typeof e==`number`)return e===1;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return!1}function jG(e){if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t))return GW(t.map(e=>String(e)))}catch{}return GW(e.split(`,`))}let MG=/* @__PURE__ */ new Map;function NG(e){if(typeof document>`u`)return null;let t=`shadow-claw-site-config`;if(e){let n=e.getAttribute(`config`)?.trim();n&&(t=n.replace(/^#/,``))}let n=document.getElementById(t);if(!n?.textContent)return MG.delete(t),null;let r=MG.get(t);if(r&&r.rawText===n.textContent)return r.config;try{let e=JSON.parse(n.textContent);if(!e||typeof e!=`object`)return MG.delete(t),null;let r={...e};return MG.set(t,{rawText:n.textContent,config:r}),r}catch(e){return console.warn(`[ShadowClaw] Failed to parse site configuration from #${t}:`,e),null}}var PG=/* @__PURE__ */ t({OrchestratorStore:()=>HG,accumulateTokenUsage:()=>VG,orchestratorStore:()=>UG});function FG(e){if(e){if(Array.isArray(e))return e;if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:void 0}catch{return}}}function IG(e){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();return t===`true`||t===`1`}return typeof e==`number`&&e===1}function LG(e){return!!e}async function RG(e,t,n,r){if(!LG(r))return!0;if(!e.schedule)return await zG(e.id,t,n,r)!==`failed`;try{let r=t.replace(/\/$/,``);return(await fetch(`${r}/tasks`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({...e,subscriberId:n})})).ok}catch{return!1}}async function zG(e,t,n,r){if(!LG(r))return`missing`;try{let r=t.replace(/\/$/,``),i=`subscriberId=${encodeURIComponent(n)}`,a=await fetch(`${r}/tasks/${encodeURIComponent(e)}?${i}`,{method:`DELETE`});return a.ok?`deleted`:a.status===404||a.status===405?`missing`:`failed`}catch{return`failed`}}async function BG(e,t,n,r){if(!LG(r))return null;try{let r=t.replace(/\/$/,``),i=await fetch(`${r}/tasks?groupId=${encodeURIComponent(e)}&subscriberId=${encodeURIComponent(n)}`,{method:`GET`});if(!i.ok||typeof i.json!=`function`)return null;let a=await i.json();return Array.isArray(a)?a.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`&&typeof e.schedule==`string`&&typeof e.prompt==`string`).map(t=>({id:t.id,groupId:t.group_id||t.groupId||e,schedule:t.schedule,type:t.type,prompt:t.prompt,tools:FG(t.tools),channel:typeof t.channel==`string`?t.channel:void 0,enabled:t.enabled===!0||t.enabled===1,lastRun:typeof t.lastRun==`number`?t.lastRun:typeof t.last_run==`number`?t.last_run:null,createdAt:typeof t.createdAt==`number`?t.createdAt:typeof t.created_at==`number`?t.created_at:Date.now(),name:typeof t.name==`string`?t.name:void 0,order:typeof t.order==`number`?t.order:typeof t.task_order==`number`?t.task_order:void 0})):null}catch{return null}}function VG(e,t){let n=(e?.inputTokens??0)+(t.inputTokens??0),r=(e?.outputTokens??0)+(t.outputTokens??0),i=(e?.cacheReadTokens??0)+(t.cacheReadTokens??0),a=(e?.cacheCreationTokens??0)+(t.cacheCreationTokens??0);return{groupId:t.groupId||e?.groupId||``,inputTokens:n,outputTokens:r,cacheReadTokens:i,cacheCreationTokens:a,totalTokens:n+r+i+a,contextLimit:t.contextLimit||e?.contextLimit||0}}var HG=class e{static DEFAULT_PAGE_PATH=`MEMORY.md`;orchestrator;_activeGroupId;_activePage;_activePinnedPage;_defaultPinnedPage;_activityLog;_activityLogSessionStartedAtByGroup;_aguiAdapter;_aguiEvent;_contextUsage;_currentPath;_db;_error;_files;_gitProxyUrl;_groups;_hadPersistedActivePage;_initResolve;_isTyping;_lastOrchestratorDisplayState=`idle`;_messages;_modelDownloadProgress;_onlineReplayHandler;_pages;_pagesAllowList;_pagesDenyList;_peerStateByGroup;_proxyUrl;_ready;_remoteAgentStatusByGroup;_remoteAgentTypingByGroup;_replayingTaskSyncOutbox;_subscriberId;_sidebarDefaultPage;_state;_storageStatus;_streamingText;_tasks;_taskSyncOutbox;_tokenUsage;_tokenUsageAccumulator=null;_toolActivity;_unreadGroupIds;_useProxy;_vmBashFullInternetAccess;_whenInitialized;_whenReady;_readyResolve;constructor(){this._messages=new ve.State([]),this._isTyping=new ve.State(!1),this._storageStatus=new ve.State(null),this._toolActivity=new ve.State(null),this._modelDownloadProgress=new ve.State(null),this._activityLog=new ve.State([]),this._state=new ve.State(`idle`),this._tokenUsage=new ve.State(null),this._error=new ve.State(null),this._activeGroupId=new ve.State(v),this._ready=new ve.State(!1),this._tasks=new ve.State([]),this._files=new ve.State([]),this._currentPath=new ve.State(`.`),this._groups=new ve.State([]),this._unreadGroupIds=new ve.State(/* @__PURE__ */ new Set),this._streamingText=new ve.State(null),this._aguiEvent=new ve.State(null),this._contextUsage=new ve.State(null),this._useProxy=new ve.State(!1),this._proxyUrl=new ve.State(`/proxy`),this._gitProxyUrl=new ve.State(`/git-proxy`),this._vmBashFullInternetAccess=new ve.State(!1),this._activePage=new ve.State(`pages`);let e=NG()?.sidebar?.defaultPage,t=e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`;this._sidebarDefaultPage=new ve.State(t),this._pages=new ve.State([]),this._pagesAllowList=new ve.State([]),this._pagesDenyList=new ve.State([]),this._activePinnedPage=new ve.State(null),this._defaultPinnedPage=new ve.State(null),this._remoteAgentStatusByGroup=new ve.State(/* @__PURE__ */ new Map),this._remoteAgentTypingByGroup=new ve.State(/* @__PURE__ */ new Map),this._peerStateByGroup=new ve.State(/* @__PURE__ */ new Map),this._hadPersistedActivePage=!1,this._initResolve=null,this._whenInitialized=new Promise(e=>{this._initResolve=e}),this._readyResolve=null,this._whenReady=new Promise(e=>{this._readyResolve=e}),this.orchestrator=null,this._db=null,this._activityLogSessionStartedAtByGroup=/* @__PURE__ */ new Map,this._taskSyncOutbox=[],this._replayingTaskSyncOutbox=!1,this._subscriberId=null,this._onlineReplayHandler=null,this._aguiAdapter=null}get activeGroupId(){return this._activeGroupId.get()}get activePage(){return this._activePage.get()}get activePinnedPage(){return this._activePinnedPage.get()}get defaultPinnedPage(){return this._defaultPinnedPage.get()}get pagesAllowList(){return this._pagesAllowList.get()}get pagesDenyList(){return this._pagesDenyList.get()}isPageAllowed(e,t){return tG(e,{allowList:this._pagesAllowList.get(),denyList:this._pagesDenyList.get(),groupId:t??this._activeGroupId.get()})}get effectiveDefaultPage(){let e=this._defaultPinnedPage.get();return e&&this.isPageAllowed(e.path,e.groupId)?e:this._pages.get()[0]||null}get activityLog(){return this._activityLog.get()}get taskServerEnabled(){return this.orchestrator?.taskServerEnabled??!1}get aguiEvent(){return this._aguiEvent.get()}clearError(){this._error.set(null),this._state.get()===`error`&&this._state.set(`idle`)}get contextUsage(){return this._contextUsage.get()}get tokenUsageAccumulator(){return this._tokenUsageAccumulator}get currentPath(){return this._currentPath.get()}get error(){return this._error.get()}get files(){return this._files.get()}getPeerState(e){return this._peerStateByGroup.get().get(e)||null}getRemoteAgentStatus(e){return this._remoteAgentStatusByGroup.get().get(e)||`idle`}getState(){return{messages:this.messages,isTyping:this.isTyping,toolActivity:this.toolActivity,activityLog:this.activityLog,state:this.state,tokenUsage:this.tokenUsage,modelDownloadProgress:this.modelDownloadProgress,error:this.error,activeGroupId:this.activeGroupId,pages:this.pages,ready:this.ready,files:this.files,currentPath:this.currentPath,streamingText:this.streamingText,contextUsage:this.contextUsage}}getTasksForBackup(){return this._tasks.get()}get gitProxyUrl(){return this._gitProxyUrl.get()}get groups(){return this._groups.get()}get hadPersistedActivePage(){return this._hadPersistedActivePage}isRemoteAgentTyping(e){return this._remoteAgentTypingByGroup.get().get(e)||!1}get isTyping(){return this._isTyping.get()}get messages(){return this._messages.get()}get modelDownloadProgress(){return this._modelDownloadProgress.get()}get pages(){return this._pages.get()}get proxyUrl(){return this._proxyUrl.get()}get ready(){return this._ready.get()}sendMessage(e,t=[],n){n===void 0?this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t):this.orchestrator?.browserChat?.submit(e,this._activeGroupId.get(),t,n)}async sendFileToPeer(e,t=this._activeGroupId.get(),n){let r=t.startsWith(`peer:`),i=t.startsWith(`room:`);if(!r&&!i){let e=`Can only send files to peers in a peer or room conversation.`;throw wG(e,4500),Error(e)}let a=this.orchestrator?.router;if(!a){let e=`Network router is not initialized.`;throw wG(e,4500),Error(e)}let o=n?.fileName||e.split(`/`).pop()||e,s=n?.mimeType||`application/octet-stream`,c=n?.size||0;a.setTyping(t,!0);try{let n={path:e,fileName:o,mimeType:s,size:c};if(await a.send(t,``,[n]),this._db){let e={id:fe(),groupId:t,sender:`You`,content:``,timestamp:Date.now(),channel:i?`room`:`peerjs`,attachments:[n],isFromMe:!1,isTrigger:!1};await EW(this._db,e),this.orchestrator?.events.emit(`message`,e)}CG(`Sent ${o} to ${i?`room peers`:`peer`}`,2500)}catch(e){let t=e instanceof Error?e.message:String(e);throw console.error(`sendFileToPeer error:`,e),wG(`Failed to send file: ${t}`,6e3),e}finally{a.setTyping(t,!1)}}setActiveGroup(e,t,n=this._activePage.get()===`chat`){if(this._activeGroupId.set(t),this._messages.set([]),this._activityLog.set([]),this._error.set(null),this._isTyping.set(!1),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._currentPath.set(`.`),n){let e=new Set(this._unreadGroupIds.get());e.delete(t)&&this._unreadGroupIds.set(e)}this.loadHistory(),this.loadTasks(e),this.loadFiles(e)}setReady(e=!0){this._ready.set(e),e&&this._readyResolve&&this._readyResolve()}setRemoteAgentStatus(e,t){let n=this._remoteAgentStatusByGroup.get(),r=new Map(n);r.set(e,t),this._remoteAgentStatusByGroup.set(r)}setRemoteAgentTyping(e,t){let n=this._remoteAgentTypingByGroup.get(),r=new Map(n);t?r.set(e,!0):r.delete(e),this._remoteAgentTypingByGroup.set(r)}get sidebarDefaultPage(){return this._sidebarDefaultPage.get()}get state(){return this._state.get()}stopCurrentRequest(){this.orchestrator?.stopCurrentRequest?.(this._activeGroupId.get())}get storageStatus(){return this._storageStatus.get()}get streamingText(){return this._streamingText.get()}syncHostWorkspaceToVM(){ZU(this.orchestrator,this._activeGroupId.get())}syncVMWorkspaceToHost(){QU(this.orchestrator,this._activeGroupId.get())}get tasks(){return this._tasks.get()}get tokenUsage(){return this._tokenUsage.get()}get toolActivity(){return this._toolActivity.get()}get unreadGroupIds(){return this._unreadGroupIds.get()}get useProxy(){return this._useProxy.get()}get vmBashFullInternetAccess(){return this._vmBashFullInternetAccess.get()}get whenInitialized(){return this._whenInitialized}async resetSiteConfigSeed(e){await pe(e,b.SITE_CONFIG_SEEDED,!1)}get whenReady(){return this._whenReady}async addPage(e,t,n=this._activeGroupId.get()){let r=n===`br:main`?this.normalizePagePath(t):t.trim();if(!r||!this.isPageAllowed(r,n))return;let i=this._pages.get();i.some(e=>e.path===r&&e.groupId===n)||(this.setPages([...i,{groupId:n,path:r}]),await WW(e,n,r),n===`br:main`&&r===`MEMORY.md`&&await VU(e,!1),await this.persistPages(e))}async clearAllTasks(e){let t=await de(e),n=this._activeGroupId.get(),r=t.filter(e=>e.groupId===n),i=await this.getSubscriberId(e);for(let t of r)await zG(t.id,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)===`failed`?(console.warn(`Failed to delete task "${t.id}" from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t.id,queuedAt:Date.now()})):await cW(e,t.id);await this.loadTasks(e)}async cloneConversation(e,t){let n=await SW(e,t);if(!n)return null;await aW(e,t,n.groupId),await oW(e,t,n.groupId);try{let r=await I(e,t,`MEMORY.md`);r&&await xe(e,n.groupId,`MEMORY.md`,r)}catch{}try{await AW(e,t,n.groupId,`attachments`)}catch{}return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async compactContext(e){if(!this.orchestrator)return;let{compactContext:t}=await import(`./compact-context-CX4H8V57.js`);return t(this.orchestrator,e,this._activeGroupId.get())}async createConversation(e,t){let n=await gW(e,t);return this.setActiveGroup(e,n.groupId),await this.loadGroups(e),n}async deleteConversation(e,t){if(!(this._groups.get().length<=1)&&(await yW(e,t),await iW(e,t),await this.loadGroups(e),this._activeGroupId.get()===t)){let t=this._groups.get()[0]?.groupId||`br:main`;this.setActiveGroup(e,t)}}async deleteMessage(e,t){await sW(e,t),await this.loadHistory(),this.orchestrator?.refreshContextUsage&&await this.orchestrator.refreshContextUsage(e,this._activeGroupId.get())}async deleteTask(e,t){let n=await this.getSubscriberId(e);if(await zG(t,this.getTaskServerBaseUrl(),n,this.orchestrator?.taskServerEnabled??!1)===`failed`)throw console.warn(`Failed to delete task from server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`delete`,id:t,queuedAt:Date.now()}),Error(`Failed to delete scheduled task on server; task kept locally.`);await cW(e,t),await this.loadTasks(e)}async ensurePeerConversation(e,t){let n=`peer:${t}`,r=await bW(e);if(!r.find(e=>e.groupId===n)){let i=[...r],a=``;if(this.orchestrator?.peerjsPeerAliases){for(let[e,n]of Object.entries(this.orchestrator.peerjsPeerAliases))if(n===t){a=e;break}}i.push({groupId:n,name:`Peer: ${a||t.substring(0,8)}`,createdAt:Date.now()}),await hW(e,i),await this.loadGroups(e)}return n}async grantStorageAccess(e){try{await PW(e),await this.loadFiles(e)}catch(e){console.error(`Failed to grant storage access:`,e)}}async init(e,t){this._db=e,this.orchestrator=t,this._taskSyncOutbox=this.parseTaskSyncOutbox(await A(e,b.TASK_SYNC_OUTBOX)),await this.replayTaskSyncOutbox(e),typeof window<`u`&&!this._onlineReplayHandler&&(this._onlineReplayHandler=()=>{this._db&&this.replayTaskSyncOutbox(this._db)},window.addEventListener(`online`,this._onlineReplayHandler)),t.events.on(`a2ui-surface`,async({groupId:t,envelope:n})=>{t&&this.ensureGroupExists(e,t);let r=this._messages.get(),i=r.findIndex(e=>e.a2uiEnvelopes?.some(e=>e.surfaceId===n.surfaceId));if(i!==-1){let t=r[i],a=[...t.a2uiEnvelopes||[],n],o={...t,a2uiEnvelopes:a},s=[...r];s[i]=o,this._messages.set(s),await EW(e,o)}else{let i=!t.startsWith(`peer:`),a={id:fe(),groupId:t,sender:i?`agent`:t.replace(/^peer:/,``),content:``,timestamp:Date.now(),channel:t.startsWith(`peer:`)?`peerjs`:`browser`,isFromMe:i,isTrigger:!1,a2uiEnvelopes:[n]};t===this._activeGroupId.get()&&this._messages.set([...r,a]),await EW(e,a)}}),t.events.on(`message`,t=>{if(t.groupId&&this.ensureGroupExists(e,t.groupId,t.timestamp),t.groupId&&t.groupId!==this._activeGroupId.get()){let e=new Set(this._unreadGroupIds.get());e.add(t.groupId),this._unreadGroupIds.set(e)}else t.isFromMe&&this._streamingText.get()!==null&&this._streamingText.set(null),this._messages.set([...this._messages.get(),t])}),t.events.on(`typing`,({groupId:e,typing:t})=>{e&&e!==this._activeGroupId.get()||this._isTyping.set(t)}),t.events.on(`tool-activity`,({groupId:e,tool:t,status:n})=>{e&&e!==this._activeGroupId.get()||this._toolActivity.set(n===`running`?{tool:t,status:n}:null)}),t.events.on(`model-download-progress`,e=>{this._modelDownloadProgress.set(e.status===`done`?null:e)}),t.events.on(`thinking-log`,e=>{e.groupId&&e.groupId!==this._activeGroupId.get()||(e.level===`info`&&e.label===`Starting`?this._activityLog.set([e]):this._activityLog.set([...this._activityLog.get(),e]),this.forwardActivityLogEntryToServer(e))}),t.events.on(`state-change`,e=>{let t=typeof e==`string`?e:e.state,n=typeof e==`string`?void 0:e.groupId;if(n&&n!==this._activeGroupId.get())return;let r=this._lastOrchestratorDisplayState;this._lastOrchestratorDisplayState=t,this._state.set(t),t===`idle`&&(this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null)),t===`thinking`&&r!==`thinking`&&r!==`responding`&&(this._tokenUsageAccumulator=null)}),t.events.on(`error`,({error:e})=>{console.error(`[Orchestrator Error Event]`,e),this._error.set(e),this._state.set(`error`)}),t.events.on(`session-reset`,()=>{this._messages.set([]),this._activityLog.set([]),this._tokenUsageAccumulator=null,this._tokenUsage.set(null),this._contextUsage.set(null),this._toolActivity.set(null),this._modelDownloadProgress.set(null),this._streamingText.set(null),this._isTyping.set(!1),this._state.set(`idle`)}),t.events.on(`context-compacted`,e=>{e?.groupId&&e.groupId!==this._activeGroupId.get()||(this._tokenUsage.set(null),this.loadHistory())}),t.events.on(`token-usage`,e=>{if(!e||e.groupId&&e.groupId!==this._activeGroupId.get())return;let t=VG(this._tokenUsageAccumulator,e);this._tokenUsageAccumulator=t,this._tokenUsage.set(t),this.orchestrator?.refreshContextUsage&&this._db&&this.orchestrator.refreshContextUsage(this._db,this._activeGroupId.get())}),t.events.on(`context-usage`,e=>{this._contextUsage.set(e)}),t.events.on(`ready`,()=>{this._ready.set(!0)}),t.events.on(`task-change`,()=>{this.loadTasks(e)}),t.events.on(`file-change`,()=>{this.loadFiles(e)}),t.events.on(`streaming-start`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(``)}),t.events.on(`streaming-chunk`,({groupId:e,text:t})=>{if(e!==this._activeGroupId.get())return;let n=this._streamingText.get();this._streamingText.set((n||``)+t)}),t.events.on(`streaming-end`,({groupId:e})=>{e===this._activeGroupId.get()&&this._streamingText.set(null)}),t.events.on(`streaming-done`,({groupId:e})=>{this._activeGroupId.get()}),t.events.on(`streaming-error`,({groupId:e})=>{this._activeGroupId.get()}),this._aguiAdapter=new bG(t.events),this._aguiAdapter.start(),typeof window<`u`&&window.addEventListener(`shadow-claw-agui-event`,(e=>{e.detail.groupId===this._activeGroupId.get()&&this._aguiEvent.set(e.detail);let t=e.detail.event;if(t){if(t.type===`STATE_SNAPSHOT`){let n=new Map(this._peerStateByGroup.get());n.set(e.detail.groupId,t.snapshot||{}),this._peerStateByGroup.set(n)}else if(t.type===`STATE_DELTA`){let n=new Map(this._peerStateByGroup.get()),r=TG(n.get(e.detail.groupId)||{},t.delta||[]);n.set(e.detail.groupId,r),this._peerStateByGroup.set(n)}}})),await ce(e),ue(),Ee(),await XU();let n=await A(e,b.PAGES_ALLOW_LIST),r=await A(e,b.PAGES_DENY_LIST);n&&this._pagesAllowList.set(jG(String(n))),r&&this._pagesDenyList.set(jG(String(r))),await XU();let i=typeof document<`u`&&document.getElementById(`shadow-claw-static-routing`)!==null,a=await A(e,b.PAGES_LIST),o=a==null?[]:this.parsePagesList(a),c=await yG(e,v,o);c.length>0?(this.setPages(c),await this.persistPages(e)):await this.ensureDefaultPage(e),await XU(),await this.applySiteConfigDefaults(e),await XU(),await this.loadGroups(e);let l=await A(e,b.LAST_ACTIVE_GROUP);l&&l!==this._activeGroupId.get()&&this._activeGroupId.set(l),await XU();let u=await A(e,b.LAST_ACTIVE_PAGE);u&&(this._activePage.set(u),this._hadPersistedActivePage=!0);let d=await A(e,b.SIDEBAR_DEFAULT_PAGE);this._sidebarDefaultPage.set(this.normalizeSidebarDefaultPage(d));let f=hG(),p=null;if(f&&(p=s(f)),!p){let t=await A(e,b.DEFAULT_PINNED_PAGE);t&&(p=s(t))}p&&this.isPageAllowed(p.path,p.groupId)&&this._defaultPinnedPage.set(p),await XU();let m=typeof window<`u`&&window.history?window.history.state:null,h=!!(m?.inFeedScroll||m?.scrollSpy||m?.suppressRouter)||typeof window<`u`&&window.location&&(()=>{let e=window.location.pathname||`/`,t=w();t!==`/`&&e.startsWith(t)&&(e=`/`+e.slice(t.length));let n=e.split(`/`).filter(Boolean);return n.length===0||n.length===1&&n[0]===`index.html`})(),g=!1;if(h&&p&&this.isPageAllowed(p.path,p.groupId)&&(this._activePinnedPage.set(p),g=!0),!g){let t=await A(e,b.LAST_SELECTED_PINNED_PAGE);if(t)try{let e=JSON.parse(t);e&&typeof e.path==`string`&&typeof e.groupId==`string`&&this.isPageAllowed(e.path,e.groupId)&&(this._activePinnedPage.set(e),g=!0)}catch{}}!g&&h&&this.effectiveDefaultPage&&this.isPageAllowed(this.effectiveDefaultPage.path,this.effectiveDefaultPage.groupId)&&(this._activePinnedPage.set(this.effectiveDefaultPage),g=!0),this.orchestrator&&(this._useProxy.set(this.orchestrator.useProxy),this._proxyUrl.set(this.orchestrator.proxyUrl),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess));let[_,y,x]=await Promise.all([A(e,b.SIDEBAR_CHAT_HIDDEN),A(e,b.SIDEBAR_TASKS_HIDDEN),A(e,b.SIDEBAR_FILES_HIDDEN)]),S=NG(),C=S?.sidebar?.chatHidden,T=S?.sidebar?.tasksHidden,E=S?.sidebar?.filesHidden,ee=_==null?!!C:AG(_),D=y==null?!!T:AG(y),O=x==null?!!E:AG(x),k=()=>{let t=[];(!ee||this.activePage===`chat`)&&t.push(this.loadHistory()),(!D||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),Promise.all(t).catch(e=>{console.warn(`Secondary background store loads failed:`,e)})};if(i)typeof window.requestIdleCallback==`function`?window.requestIdleCallback(k,{timeout:2e3}):setTimeout(k,100);else{let t=[];(!ee||this.activePage===`chat`)&&t.push(this.loadHistory()),(!D||this.activePage===`tasks`)&&t.push(this.loadTasks(e)),(!O||this.activePage===`files`)&&t.push(this.loadFiles(e)),await Promise.all(t)}await XU(),this._initResolve?.(),this.scheduleBackgroundStaticMainSiteSeeding(e)}async loadFiles(e){let t=this._activeGroupId.get(),n=this._currentPath.get();try{this._storageStatus.set(await ae(e));let r=await MW(e,t,n);this._files.set(r)}catch(e){console.error(`Failed to load files in store:`,e)}}async loadGroups(e){let t=await bW(e);this._groups.set(t)}async loadHistory(){let e=this._activeGroupId.get(),t=await dW(e,200);this._activeGroupId.get()===e&&this._messages.set(t)}async loadTasks(e){let t=this._activeGroupId.get(),n=await de(e),r=n.filter(e=>e.groupId===t);r.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(r);let i=await this.getSubscriberId(e),a=await BG(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1);if(!a)return;let o=new Set(n.map(e=>e.id)),s=a.filter(e=>!o.has(e.id));if(s.length===0)return;for(let t of s)await DW(e,t);let c=[...r,...s];c.sort((e,t)=>{let n=e.order??0,r=t.order??0;return n===r?e.createdAt-t.createdAt:n-r}),this._tasks.set(c)}async navigateBackFolder(e){let t=this._currentPath.get();if(t===`.`)return;let n=t.split(`/`).filter(Boolean);n.pop();let r=n.length===0?`.`:n.join(`/`);await this.setCurrentPath(e,r)}async navigateIntoFolder(e,t){let n=this._currentPath.get(),r=n===`.`?t.replace(/\/$/,``):`${n}/${t.replace(/\/$/,``)}`;try{await this.setCurrentPath(e,r)}catch(t){console.error(`Failed to navigate into folder in store:`,t),wG(`Folder not found: ${r}`,4500),await this.loadFiles(e)}}async newSession(e){await this.orchestrator?.newSession?.(e,this._activeGroupId.get()),await this.loadHistory()}async removePage(t,n,r=this._activeGroupId.get()){let i=this.normalizePagePath(n);if(!i)return;let a=this._pages.get();if(!a.some(e=>e.path===i&&e.groupId===r))return;let o=a.filter(e=>e.path!==i||e.groupId!==r);await UW(t,r,i);let s=r===`br:main`&&i===`MEMORY.md`;s&&await VU(t,!0);let c=s||await BU(t);if(o.length===0&&!c){if(await HU(t,`br:main`))o.push({groupId:v,path:e.DEFAULT_PAGE_PATH});else return}this.setPages(o);let l=this._defaultPinnedPage.get();l&&l.path===i&&l.groupId===r&&await this.setDefaultPinnedPage(t,null),await this.persistPages(t)}async removeAllPages(e){let t=[...this._pages.get()];for(let n of t)await UW(e,n.groupId,n.path),n.groupId===`br:main`&&n.path===`MEMORY.md`&&await VU(e,!0);this.setPages([]),await this.setDefaultPinnedPage(e,null),await this.setActivePinnedPage(e,null),await this.persistPages(e)}async renameConversation(e,t,n){await _W(e,t,n),await this.loadGroups(e)}async reorderConversations(e,t){await xW(e,t),await this.loadGroups(e)}async reorderTasks(e,t,n){let r=await kW(e,t,n);await this.loadTasks(e);let i=await this.getSubscriberId(e);for(let t of r)await RG(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync reordered task "${t.id}" to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}async replayTaskSyncOutbox(e){if(!(this._replayingTaskSyncOutbox||this._taskSyncOutbox.length===0)){this._replayingTaskSyncOutbox=!0;try{let t=await this.getSubscriberId(e),n=[];for(let e of this._taskSyncOutbox){let r=this.getTaskServerBaseUrl();(e.type===`upsert`?await RG(e.task,r,t,this.orchestrator?.taskServerEnabled??!1):await zG(e.id,r,t,this.orchestrator?.taskServerEnabled??!1))||n.push(e)}this._taskSyncOutbox=this.compactTaskSyncOutbox(n),await this.persistTaskSyncOutbox(e)}finally{this._replayingTaskSyncOutbox=!1}}}async resetToRootFolder(e){await this.setCurrentPath(e,`.`)}async restartCurrentRequest(){return this.orchestrator?.restartCurrentRequest?this.orchestrator.restartCurrentRequest(this._activeGroupId.get()):!1}async restoreTasksFromBackup(e,t){await this.clearAllTasks(e);let n=this._activeGroupId.get();for(let r of t){let t={...r,groupId:n,id:crypto.randomUUID?crypto.randomUUID():`task-${Date.now()}-${Math.random()}`};await this.upsertTask(e,t,{reloadTasks:!1})}await this.loadTasks(e)}async runTask(e,t=!1){let n=this._db;if(t&&n&&(await OW(e.id,Date.now()),await this.loadTasks(n)),e.type===`tools`&&Array.isArray(e.tools)&&e.tools.length>0){if(this.orchestrator?.agentWorker){let n=e.subagent?`subagent:${fe()}`:e.groupId;this.orchestrator.agentWorker.postMessage({type:`execute-task-tools`,payload:{groupId:n,tools:e.tools,isManual:t}})}else console.error(`Agent worker not available to execute tool task.`)}else{if(!e.groupId){console.error(`Task ${e.id} has no groupId - refusing to execute in active conversation to prevent context pollution.`);return}this.orchestrator?.browserChat?.submit(e.prompt,e.groupId,[],void 0,e.freshContext,e.subagent)}}async setActivePage(e,t){this._activePage.set(t),await pe(e,b.LAST_ACTIVE_PAGE,t);let n=this.resolveSidebarDefaultPageForActivePage(t);n!==this._sidebarDefaultPage.get()&&(this._sidebarDefaultPage.set(n),await pe(e,b.SIDEBAR_DEFAULT_PAGE,n))}async setActivePinnedPage(e,t){t&&!this.isPageAllowed(t.path,t.groupId)&&(t=this.effectiveDefaultPage),this._activePinnedPage.set(t),t?await pe(e,b.LAST_SELECTED_PINNED_PAGE,JSON.stringify(t)):await pe(e,b.LAST_SELECTED_PINNED_PAGE,null)}async setDefaultPinnedPage(e,t){if(t&&!this.isPageAllowed(t.path,t.groupId))return;let n=this._defaultPinnedPage.get(),r=n&&t&&n.path===t.path&&n.groupId===t.groupId?null:t;this._defaultPinnedPage.set(r),r?await pe(e,b.DEFAULT_PINNED_PAGE,JSON.stringify(r)):await pe(e,b.DEFAULT_PINNED_PAGE,null)}async reorderPages(e,t){this.setPages(t),await this.persistPages(e)}async setCurrentPath(e,t){let n=t.replace(/^\/+|\/+$/g,``)||`.`,r=this._activeGroupId.get();this._storageStatus.set(await ae(e));let i=await MW(e,r,n);this._currentPath.set(n),this._files.set(i)}async setGitProxyUrl(e,t){this.orchestrator&&(await eW(this.orchestrator,e,t),this._gitProxyUrl.set(this.orchestrator.gitProxyUrl))}async setProxyUrl(e,t){this.orchestrator&&(await tW(this.orchestrator,e,t),this._proxyUrl.set(this.orchestrator.proxyUrl))}async setUseProxy(e,t){this.orchestrator&&(await nW(this.orchestrator,e,t),this._useProxy.set(this.orchestrator.useProxy))}async setVMBashFullInternetAccess(e,t){this.orchestrator&&(await rW(this.orchestrator,e,t),this._vmBashFullInternetAccess.set(this.orchestrator.vmBashFullInternetAccess))}async switchConversation(e,t,n){this.setActiveGroup(e,t,n??this._activePage.get()===`chat`),await pe(e,b.LAST_ACTIVE_GROUP,t)}async toggleTask(e,t,n){let r={...t,enabled:n};await DW(e,r),await this.loadTasks(e),await RG(r,this.getTaskServerBaseUrl(),await this.getSubscriberId(e),this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to update task on server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:r.id,task:r,queuedAt:Date.now()}))}async updateConversationPinnedProvider(e,t,n,r,i){await CW(e,t,n,r,i),await this.loadGroups(e)}async updateConversationProviderRuntimeOverrides(e,t,n){await TW(e,t,n),await this.loadGroups(e)}async updateConversationSubagentSettings(e,t,n,r,i,a){await wW(e,t,n,r,i,a),await this.loadGroups(e)}async updateConversationToolTags(e,t,n){await vW(e,t,n),await this.loadGroups(e)}async upsertTask(e,t,n){let r=n?.reloadTasks!==!1;await DW(e,t),r&&await this.loadTasks(e);let i=await this.getSubscriberId(e);await RG(t,this.getTaskServerBaseUrl(),i,this.orchestrator?.taskServerEnabled??!1)||(console.warn(`Failed to sync task to server — queued for replay.`),await this.queueTaskSyncOutboxOperation(e,{type:`upsert`,id:t.id,task:t,queuedAt:Date.now()}))}compactTaskSyncOutbox(e){let t=/* @__PURE__ */ new Map;return e.forEach((e,n)=>{t.set(e.id,n)}),e.filter((e,n)=>t.get(e.id)===n)}deriveGroupName(e){return e.startsWith(`tg:`)?`Telegram ${e.slice(3)}`:e.startsWith(`im:`)?`iMessage ${e.slice(3)}`:e.startsWith(`br:`)?e===`br:main`?`Main`:`Browser Conversation`:`Conversation`}getActivityLogSessionStartedAt(e){let t=this._activityLogSessionStartedAtByGroup.get(e);if(t)return t;let n=(/* @__PURE__ */ new Date()).toISOString();return this._activityLogSessionStartedAtByGroup.set(e,n),n}getTaskServerBaseUrl(){return this.orchestrator?.taskServerUrl??`/schedule`}async getSubscriberId(e){if(this._subscriberId)return this._subscriberId;let t=await uW(e);return this._subscriberId=t,t}normalizePagePath(t){let n=t.trim().replace(/^\/+/,``).replace(/\/+/g,`/`);return n===`main/memory.md`?e.DEFAULT_PAGE_PATH:n}normalizeSidebarDefaultPage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:`chat`}parsePagesList(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{groupId:v,path:this.normalizePagePath(e)};if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.path!=`string`)return null;let n=typeof t.groupId==`string`&&t.groupId.trim().length>0?t.groupId:v,r=n===`br:main`?this.normalizePagePath(t.path):t.path.trim();return r?{groupId:n,path:r}:null}).filter(e=>!!e).filter((e,t,n)=>{let r=`${e.groupId}\u0000${e.path}`;return t===n.findIndex(e=>`${e.groupId}\u0000${e.path}`===r)}):[]}catch{return[]}}parseTaskSyncOutbox(e){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=t.filter(e=>!!e&&typeof e==`object`).filter(e=>e.type===`upsert`||e.type===`delete`).filter(e=>typeof e.id==`string`&&e.id.length>0).map(e=>({...e,queuedAt:typeof e.queuedAt==`number`?e.queuedAt:Date.now()}));return this.compactTaskSyncOutbox(n)}catch{return[]}}resolveSidebarDefaultPageForActivePage(e){return e===`pages`||e===`chat`||e===`tasks`||e===`files`?e:this._sidebarDefaultPage.get()}setPages(e){let t=e.filter(e=>this.isPageAllowed(e.path,e.groupId)),n=t.filter(e=>e.path.toLowerCase()===`memory.md`),r=t.filter(e=>e.path.toLowerCase()!==`memory.md`);this._pages.set([...r,...n])}async ensureDefaultPage(t){if(await BU(t))return;let n=await HU(t,v);await qU(t,v),!(!n||this._pages.get().length>0)&&(this.setPages([{groupId:v,path:e.DEFAULT_PAGE_PATH}]),await this.persistPages(t))}async ensureGroupExists(e,t,n){let r=this._groups.get();if(r.some(e=>e.groupId===t))return;let i=[...r,{groupId:t,name:this.deriveGroupName(t),createdAt:n||Date.now()}];this._groups.set(i);try{await hW(e,i)}catch(e){console.error(`Failed to persist new conversation metadata:`,e)}}async forwardActivityLogEntryToServer(e){if(!this._db||!IG(await A(this._db,b.ACTIVITY_LOG_DISK_LOGGING_ENABLED)))return;let t=typeof e.groupId==`string`&&e.groupId?e.groupId:this._activeGroupId.get();if(!t)return;let n=typeof e.message==`string`?e.message.trim():``;if(!n)return;e.level===`info`&&e.label===`Starting`&&this._activityLogSessionStartedAtByGroup.set(t,(/* @__PURE__ */ new Date()).toISOString());let r=this.getActivityLogSessionStartedAt(t);try{await fetch(`/activity-log`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({groupId:t,level:e.level,label:e.label,message:n,timestamp:(/* @__PURE__ */ new Date()).toISOString(),sessionStartedAt:r})})}catch(e){console.warn(`Failed to persist activity log entry to server:`,e)}}scheduleBackgroundStaticMainSiteSeeding(e){if(typeof window>`u`)return;let t=async()=>{try{if(await iG(e,`br:main`))return;let t=await A(e,b.PAGES_LIST),n=t==null?[]:this.parsePagesList(t),r=await yG(e,v,n,{preferEmbedded:!1});r&&r.length>0&&(this.setPages(r),await this.persistPages(e))}catch(e){console.warn(`Background static main site seeding failed:`,e)}};typeof window.requestIdleCallback==`function`?window.requestIdleCallback(()=>void t(),{timeout:3e3}):setTimeout(()=>void t(),100)}async persistPages(e){await pe(e,b.PAGES_LIST,JSON.stringify(this._pages.get()))}async persistTaskSyncOutbox(e){await pe(e,b.TASK_SYNC_OUTBOX,JSON.stringify(this._taskSyncOutbox))}async queueTaskSyncOutboxOperation(e,t){this._taskSyncOutbox=this.compactTaskSyncOutbox([...this._taskSyncOutbox,t]),await this.persistTaskSyncOutbox(e)}async applySiteConfigDefaults(e){if(typeof document<`u`)try{let t=NG();if(!t||typeof t!=`object`)return;me(t),ue(),Ee();let n=t.customElements;if((await bW(e)).find(e=>e.groupId===`br:main`)?.toolTags&&await vW(e,v,void 0),(t.settings?.internetAccess??t.settings?.vm_bash_full_internet_access??t.settings?.fullInternetAccess??t.internetAccess)===!0&&await A(e,b.VM_BASH_FULL_INTERNET_ACCESS)!==`true`&&(await pe(e,b.VM_BASH_FULL_INTERNET_ACCESS,`true`),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=!0),this._vmBashFullInternetAccess.set(!0)),t.pages&&typeof t.pages==`object`){let{defaultPinnedPage:n}=t.pages;if(n&&typeof n==`string`){let t=s(n);t&&this.isPageAllowed(t.path,t.groupId)&&(this._defaultPinnedPage.set(t),await pe(e,b.DEFAULT_PINNED_PAGE,JSON.stringify(t)))}}let r=t.allowedCustomElements||(typeof n==`object`&&!Array.isArray(n)?n.allowedElements:void 0);r!==void 0&&(await A(e,b.ALLOWED_CUSTOM_ELEMENTS)??await pe(e,b.ALLOWED_CUSTOM_ELEMENTS,JSON.stringify(r)));let i=t.allowedCustomElementDomains||(typeof n==`object`&&!Array.isArray(n)?n.allowedDomains:void 0);if(i!==void 0&&(await A(e,b.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS)??await pe(e,b.ALLOWED_CUSTOM_ELEMENT_HOST_PATTERNS,JSON.stringify(i))),t.sidebar&&typeof t.sidebar==`object`){let{pagesHidden:n,chatHidden:r,tasksHidden:i,filesHidden:a,defaultPage:o}=t.sidebar;if(n!==void 0&&(await A(e,b.SIDEBAR_PAGES_HIDDEN)??await pe(e,b.SIDEBAR_PAGES_HIDDEN,String(!!n))),r!==void 0&&(await A(e,b.SIDEBAR_CHAT_HIDDEN)??await pe(e,b.SIDEBAR_CHAT_HIDDEN,String(!!r))),i!==void 0&&(await A(e,b.SIDEBAR_TASKS_HIDDEN)??await pe(e,b.SIDEBAR_TASKS_HIDDEN,String(!!i))),a!==void 0&&(await A(e,b.SIDEBAR_FILES_HIDDEN)??await pe(e,b.SIDEBAR_FILES_HIDDEN,String(!!a))),o&&typeof o==`string`){let t=this.normalizeSidebarDefaultPage(o);this._sidebarDefaultPage.set(t),await A(e,b.SIDEBAR_DEFAULT_PAGE)||await pe(e,b.SIDEBAR_DEFAULT_PAGE,o)}}if(t.settings&&typeof t.settings==`object`){let{assistantName:n,defaultProvider:r,provider:i,defaultModel:a,model:o}=t.settings;n&&typeof n==`string`&&(await A(e,b.ASSISTANT_NAME)||await pe(e,b.ASSISTANT_NAME,n));let s=r??i;if(typeof s==`string`&&s.trim().length>0&&!await A(e,b.PROVIDER)){let t=s.trim();await pe(e,b.PROVIDER,t),this.orchestrator&&(this.orchestrator.provider=t)}let c=a??o;if(typeof c==`string`&&c.trim().length>0&&!await A(e,b.MODEL)){let t=c.trim();await pe(e,b.MODEL,t),this.orchestrator&&(this.orchestrator.model=t)}let l=t.settings.internetAccess??t.settings.vm_bash_full_internet_access??t.settings.fullInternetAccess??t.internetAccess;typeof l==`boolean`&&(await A(e,b.VM_BASH_FULL_INTERNET_ACCESS)??(await pe(e,b.VM_BASH_FULL_INTERNET_ACCESS,String(l)),this.orchestrator&&(this.orchestrator.vmBashFullInternetAccess=l),this._vmBashFullInternetAccess.set(l)))}let a=(t.settings&&typeof t.settings==`object`?t.settings.defaultToolsProfile:void 0)??t.defaultToolsProfile;if(typeof a==`string`&&a.trim().length>0&&!await A(e,b.ACTIVE_TOOL_PROFILE)){let t=a.trim();if(t.toLowerCase()===`none`)await we.deactivateProfile(e);else{let n=we.profiles.find(e=>e.id.toLowerCase()===t.toLowerCase()||e.name.toLowerCase()===t.toLowerCase());n?await we.activateProfile(e,n.id):console.warn(`Default tools profile "${t}" specified in site-config was not found.`)}}if(t.pages&&typeof t.pages==`object`){let{defaultPinnedPage:n}=t.pages;n&&typeof n==`string`&&(await A(e,b.DEFAULT_PINNED_PAGE)||await pe(e,b.DEFAULT_PINNED_PAGE,n))}let o=t.pages?.allowList??t.pages?.allowlist??t.allowList??t.allowlist,c=t.pages?.denyList??t.pages?.denylist??t.denyList??t.denylist;if(Array.isArray(o)&&await A(e,b.PAGES_ALLOW_LIST)==null){let t=GW(o.map(String));this._pagesAllowList.set(t),await pe(e,b.PAGES_ALLOW_LIST,JSON.stringify(t))}if(Array.isArray(c)&&await A(e,b.PAGES_DENY_LIST)==null){let t=GW(c.map(String));this._pagesDenyList.set(t),await pe(e,b.PAGES_DENY_LIST,JSON.stringify(t))}await pe(e,b.SITE_CONFIG_SEEDED,`true`);let l=this._pages.get(),u=l.filter(e=>this.isPageAllowed(e.path,e.groupId));u.length!==l.length&&(this.setPages(u),await this.persistPages(e));let d=this._activePinnedPage.get();d&&!this.isPageAllowed(d.path,d.groupId)&&await this.setActivePinnedPage(e,this.effectiveDefaultPage);let f=this._defaultPinnedPage.get();if(f&&!this.isPageAllowed(f.path,f.groupId)&&await this.setDefaultPinnedPage(e,null),Array.isArray(t.enabledTools)){let n=t.enabledTools.filter(e=>typeof e==`string`&&e.trim().length>0);await we.setAllEnabled(e,n),await we.setAllDeclarativeEnabled(e,n)}await pe(e,b.SITE_CONFIG_SEEDED,`true`)}catch(e){console.warn(`Failed to apply site-config defaults:`,e)}}};const UG=new HG;async function WG(e,t,n){let r=await re(e,t),{dirs:i,filename:a}=M(n),o=r;for(let e of i)o=await o.getDirectoryHandle(e);await o.removeEntry(a),t===`br:main`&&i.length===0&&(a===`MEMORY.md`?await VU(e,!0):a===`index.html`&&await KU(e,!0));try{await UW(e,t,n)}catch{}try{await UG.removePage(e,n,t)}catch{}}async function GG(e,t,n){let r=n.replace(/\\/g,`/`).replace(/^\/home\/user\//,`/`).replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(Boolean);if(r.length===0)throw Error(`Empty directory path`);for(let n=0;n<2;n++)try{let n=await re(e,t);for(let e of r)n=await n.getDirectoryHandle(e,{create:!0});return}catch(e){if(n===0&&oe(e)){ie();continue}throw e}}var KG=class extends zL{db;groupId;workspacePrefix;constructor(e,t,n,r=`/home/user`){super(n),this.db=e,this.groupId=t,this.workspacePrefix=r}async appendFile(e,t){await super.appendFile(e,t);let n=this._toDbPath(e);if(n!==null){let t=await this._readPathContent(e);await xe(this.db,this.groupId,n,t)}}async cp(e,t,n){await super.cp(e,t,n);let r=this._toDbPath(t);if(r!==null)try{let e=await super.stat(t);if(!this._isDirectoryStat(e)){let e=await this._readPathContent(t);await xe(this.db,this.groupId,r,e)}}catch{}}async mkdir(e,t){await super.mkdir(e,t);let n=this._toDbPath(e);n!==null&&n!==``&&await GG(this.db,this.groupId,n)}async mv(e,t){await super.mv(e,t);let n=!1,r=t,i=this._toDbPath(t);if(i!==null)try{let i=await super.stat(t);if(this._isDirectoryStat(i)){let n=this._basename(e);n&&(r=this._joinPath(t,n))}let a=await super.stat(r);if(!this._isDirectoryStat(a)){let e=this._toDbPath(r);if(e!==null){let t=await this._readPathContent(r);await xe(this.db,this.groupId,e,t),n=!0}}}catch{}let a=this._toDbPath(e);if(a!==null)try{(i===null||n)&&await WG(this.db,this.groupId,a)}catch{}}async rm(e,t){await super.rm(e,t);let n=this._toDbPath(e);if(n!==null)try{await WG(this.db,this.groupId,n)}catch{}}async writeFile(e,t,n){await super.writeFile(e,t,n);let r=this._toDbPath(e);if(r!==null){let t=await this._readPathContent(e);await xe(this.db,this.groupId,r,t)}}_basename(e){let t=e.split(`/`).filter(Boolean);return t[t.length-1]||``}_isDirectoryStat(e){return e&&typeof e.isDirectory==`function`?!!e.isDirectory():!!e?.isDirectory}_joinPath(e,t){let n=e.replace(/\/+$/,``);return n?`${n}/${t}`:`/${t}`}_toDbPath(e){return e.startsWith(this.workspacePrefix+`/`)?e.slice(this.workspacePrefix.length+1):e===this.workspacePrefix?``:null}async _readPathContent(e){try{return await super.readFileBuffer(e)}catch{return await super.readFile(e)}}};async function qG(e,t){let n={},r=/* @__PURE__ */ new Set,i=`/home/user`;async function a(o){let s=await MW(e,t,o);for(let c of s)if(c.endsWith(`/`)){let e=c.slice(0,-1),t=o===`.`?e:`${o}/${e}`;r.add(t),await a(t)}else{let r=o===`.`?c:`${o}/${c}`,a=`${i}/${r}`;n[a]=async()=>{try{return await IU(e,t,r)}catch{return``}}}}await a(`.`);let o=new KG(e,t,n,i);for(let e of[...r].sort((e,t)=>e.split(`/`).length-t.split(`/`).length))try{o.mkdirSync(`${i}/${e}`,{recursive:!0})}catch{}return o}async function JG(e,t,n,r={},i=30,a=!1){try{let i=await new MU({fs:await qG(e,n),network:{dangerouslyAllowFullInternetAccess:a,denyPrivateRanges:!a}}).exec(t,{env:{HOME:`/home/user`,PATH:`/usr/bin`,PWD:`/home/user`,...r}});return{stdout:i.stdout||``,stderr:i.stderr||``,exitCode:i.exitCode??0}}catch(e){return{stdout:``,stderr:e instanceof Error?e.message:String(e),exitCode:1}}}function YG(e){let t=e.stdout||``;return e.stderr&&(t+=(t?`
1804
1804
  `:``)+e.stderr),e.exitCode!==0&&!t&&(t=`[exit code: ${e.exitCode}]`),t||`(no output)`}async function XG(e,t,n,r,i){return YG(await JG(e,t,n,{},r,i))}async function ZG(e){return kG(await A(e,b.VM_BASH_FULL_INTERNET_ACCESS))??!1}async function QG(e){if(bn())return!0;let t=Date.now()+e;for(;Date.now()<t;)if(await new Promise(e=>{setTimeout(e,50)}),bn())return!0;return bn()}async function $G(e,t,n){let r=await A(e,b.VM_BASH_TIMEOUT_SEC),i=Number(r),a=Number.isFinite(i)?Math.min(Math.max(i,1),_):900,o=Number(t.timeout),s=Number.isFinite(o)?Math.min(Math.max(o,1),_):a,c=await ZG(e),l=Cn(),u=t.stdin?String(t.stdin):``,d=u.length>0,f=`.shadowclaw_stdin`,p=t.command;if(te()){let e=globalThis.__headlessBashExecutor;if(typeof e==`function`)return e({command:p,stdin:u,timeoutSec:s});throw Error(`Headless bash executor is not configured. Register nativeBashExecutor before executing bash in headless mode.`)}if(d){if(l===`ext2`){let e=`EOF_SC_${Date.now()}`;p=`(cat << '${e}'\n${u}\n${e}\n) | (${p})`}else p=`{\n${p}\n} < /home/user/${f}; _code=$?; rm -f /home/user/${f}; exit $_code`}try{if(d&&l!==`ext2`&&await xe(e,n,f,u),l===`disabled`)return await XG(e,p,n,s,c);if(!bn()){await _n();let e=xn();!bn()&&e.booting&&await QG(Math.min(s*1e3,3e4))}if(bn())return await vn(p,s,{db:e,groupId:n});let t=xn();return B({type:`show-toast`,payload:{duration:7e3,message:`WebVM unavailable for this bash command. ${t.error?`Reason: ${t.error}`:t.booting?`Reason: WebVM is still booting.`:`Reason: WebVM is unavailable.`} Falling back to JavaScript Bash Emulator and retrying WebVM on the next command.`,type:`warning`}}),await XG(e,p,n,s,c)}finally{d&&l!==`ext2`&&await WG(e,n,f).catch(()=>{})}}async function eK(e,t,n,r){let{dirs:i,filename:a}=M(n);for(let n=0;n<2;n++)try{let n=await re(e,t);for(let e of i)n=await n.getDirectoryHandle(e,{create:!0});let o=await n.getFileHandle(a,{create:!0});try{await ye(o,r);return}catch(t){if(!((t instanceof Error?t.message:String(t)).includes(`Writable file streams are not supported`)&&(await ae(e)).type===`opfs`))throw t}let s=t.replace(/:/g,`-`);await he([F(),`groups`,s,...i,a],r);return}catch(e){if(n===0&&oe(e)){ie();continue}throw e}}const tK=[{id:`imap`,name:`IMAP Mail`,protocol:`imap`,description:`Read mailboxes and fetch message metadata/content.`,version:`0.1.0`,actions:[`messages.read`,`messages.send`],authTypes:[`basic_userpass`,`oauth`],serviceTypes:[`http_api`],configurableFields:[`host`,`port`,`secure`,`mailboxPath`,`smtpHost`,`smtpPort`,`smtpSecure`,`fromAddress`,`executionMode`,`pollIntervalSec`]}];function nK(){return[...tK].sort((e,t)=>e.id.localeCompare(t.id))}function rK(e){return e&&tK.find(t=>t.id===e)||null}function iK(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.serviceType||!t.authType?null:{serviceType:t.serviceType,authType:t.authType,providerId:t.providerId||void 0,accountId:t.accountId||void 0,username:t.username||void 0,headerName:t.headerName||void 0,encryptedSecret:t.encryptedSecret||void 0}}function aK(e){if(!e||typeof e!=`object`)return null;let t=e;return!t.id||!t.label||!t.pluginId||typeof t.enabled!=`boolean`||typeof t.createdAt!=`number`||typeof t.updatedAt!=`number`||!rK(t.pluginId)?null:{id:t.id,label:t.label,pluginId:t.pluginId,enabled:t.enabled,config:t.config&&typeof t.config==`object`?{...t.config}:{},credentialRef:iK(t.credentialRef),createdAt:t.createdAt,updatedAt:t.updatedAt}}async function oK(e){let t=await A(e,b.INTEGRATION_CONNECTIONS);if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=aK(e);t&&n.push(t)}return n}async function sK(e,t){await pe(e,b.INTEGRATION_CONNECTIONS,t)}async function cK(e){return oK(e)}async function lK(e,t){if(!t)return null;let n=await oK(e);return n.find(e=>e.id===t)||n.find(e=>e.label.toLowerCase()===t.toLowerCase())||null}async function uK(e,t){if(!t.label?.trim())throw Error(`Email connection label is required`);let n=rK(t.pluginId);if(!n)throw Error(`Unknown email plugin: ${t.pluginId}`);let r=await oK(e),i=Date.now();if(t.id){let a=r.findIndex(e=>e.id===t.id);if(a!==-1){let o=r[a],s={...o,label:t.label.trim(),pluginId:n.id,enabled:t.enabled??o.enabled,config:t.config?{...t.config}:o.config,updatedAt:i};return r[a]=s,await sK(e,r),s}}let a={id:t.id||fe(),label:t.label.trim(),pluginId:n.id,enabled:t.enabled??!0,config:t.config?{...t.config}:{},credentialRef:null,createdAt:i,updatedAt:i};return r.push(a),await sK(e,r),a}async function dK(e,t,n){if(!t)return null;let r=await oK(e),i=r.findIndex(e=>e.id===t);if(i===-1)return null;let a={...r[i],credentialRef:n?iK(n):null,updatedAt:Date.now()};return r[i]=a,await sK(e,r),a}async function fK(e,t){if(!t)return!1;let n=await oK(e),r=n.filter(e=>e.id!==t);return r.length!==n.length&&(await sK(e,r),!0)}function pK(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n==`string`){let e=n.trim();e&&t.push({path:e});continue}if(!n||typeof n!=`object`)continue;let e=typeof n.path==`string`?n.path.trim():``;if(!e)continue;let r=typeof n.filename==`string`?n.filename.trim():``,i=typeof n.content_type==`string`?n.content_type.trim():``;t.push({path:e,filename:r||void 0,contentType:i||void 0})}return t}function mK(e,t,n){if(e==null||e===``||typeof e==`boolean`)return t;let r=typeof e==`number`?e:Number(e);if(!Number.isFinite(r))return t;let i=r;return typeof n?.min==`number`&&(i=Math.max(n.min,i)),typeof n?.max==`number`&&(i=Math.min(n.max,i)),i}function hK(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`).map(e=>e.trim()).filter(Boolean):[]}function gK(e){if(!Array.isArray(e))return[];let t=e.map(e=>typeof e==`number`?e:Number(e)).filter(e=>Number.isFinite(e)&&e>0).map(e=>Math.floor(e));return Array.from(new Set(t))}const _K=mK,vK=hK,yK=gK;function bK(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n){let i=e.subarray(r,r+n);t+=String.fromCharCode(...i)}return btoa(t)}function xK(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function SK(e,t=`attachment.bin`){if(!e)return t;let n=e.replace(/\\/g,`/`).split(`/`).filter(Boolean);return n[n.length-1]||t}function CK(e,t={}){let n=t.replacement??`_`,r=t.fallback??`attachment.bin`,i=e.trim();t.stripControlChars&&(i=i.replace(/[\u0000-\u001f\u007f]+/g,``)),t.stripLeadingDots&&(i=i.replace(/^\.+/,``));let a=t.stripControlChars?/[\\/:*?"<>|]/g:/[\\/:*?"<>|\x00-\x1f\u007f]/g;if(t.collapseReplacement&&n){let e=n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);i=i.replace(t.stripControlChars?/[\\/:*?"<>|]+/g:/[\\/:*?"<>|\x00-\x1f\u007f]+/g,n),i=i.replace(RegExp(`${e}+`,`g`),n)}else i=i.replace(a,n);return i=i.trim(),t.stripLeadingDots&&(i=i.replace(/^\.+/,``).trim()),i||r}const wK={apng:`image/apng`,avif:`image/avif`,bmp:`image/bmp`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,ico:`image/x-icon`,jpeg:`image/jpeg`,jpg:`image/jpeg`,png:`image/png`,svg:`image/svg+xml`,tif:`image/tiff`,tiff:`image/tiff`,webp:`image/webp`},TK={...wK,"3gp":`video/3gpp`,aac:`audio/aac`,avi:`video/x-msvideo`,bin:`application/octet-stream`,css:`text/css`,csv:`text/csv`,db:`application/vnd.sqlite3`,dll:`application/octet-stream`,dmg:`application/octet-stream`,dylib:`application/octet-stream`,exe:`application/vnd.microsoft.portable-executable`,flac:`audio/flac`,flv:`video/x-flv`,gz:`application/gzip`,htm:`text/html`,html:`text/html`,iso:`application/octet-stream`,js:`text/javascript`,json:`application/json`,m4a:`audio/mp4`,m4v:`video/mp4`,markdown:`text/markdown`,md:`text/markdown`,mjs:`text/javascript`,mkv:`video/x-matroska`,mov:`video/mp4`,mp3:`audio/mpeg`,mp4:`video/mp4`,oga:`audio/ogg`,ogg:`audio/ogg`,ogv:`video/ogg`,pdf:`application/pdf`,rar:`application/vnd.rar`,so:`application/octet-stream`,sqlite:`application/vnd.sqlite3`,sqlite3:`application/vnd.sqlite3`,tar:`application/x-tar`,ts:`text/typescript`,tsx:`text/typescript`,txt:`text/plain`,wasm:`application/wasm`,wav:`audio/wav`,weba:`audio/webm`,webm:`video/webm`,wmv:`video/x-ms-wmv`,xml:`application/xml`,yaml:`text/yaml`,yml:`text/yaml`,zip:`application/zip`};function EK(e){return e&&(e.split(/[?#]/,1)[0].replace(/\\/g,`/`).split(`/`).pop()||``).toLowerCase().split(`.`).pop()||``}function DK(e,t){let n=EK(e);return TK[n]??t}function OK(e){let t=EK(e);return wK[t]||null}function kK(e){return OK(e)!==null}function AK(e){let t=EK(e);if(t===`md`||t===`markdown`||t===`txt`)return`text/plain`;if(t===`pdf`)return`application/pdf`;if(wK[t])return wK[t]}async function jK(e,t,n,r=!1){let i=(typeof n.username==`string`?n.username.trim():``)||t.credentialRef?.username||(typeof t.config.username==`string`?t.config.username:``);if(!i)return`Error: Integration connection ${t.id} is missing username credentials.`;if(t.credentialRef?.authType===`oauth`){let n=t.credentialRef.accountId;if(!n)return`Error: Integration connection ${t.id} is missing linked OAuth account.`;let a=await L(e,void 0,{accountId:n,authMode:`oauth`,forceRefresh:r});if(!a||a.reauthRequired||!a.token){let e=t.credentialRef?.providerId||`the configured`;return`Error: OAuth account reconnect required for integration ${t.id}.\nOpen Settings -> Integrations, edit this email connection, and click Connect OAuth for ${e} to re-authorize.`}return{authType:`oauth`,username:i,accessToken:a.token}}let a=(typeof n.password==`string`?n.password.trim():``)||t.credentialRef?.encryptedSecret&&await Re(t.credentialRef.encryptedSecret)||``;return a?{authType:`basic_userpass`,username:i,password:a}:`Error: Integration connection ${t.id} is missing password credentials.`}async function MK(e,t,n,r){let i=CK(r),a=i.lastIndexOf(`.`),o=a>0?i.slice(0,a):i,s=a>0?i.slice(a):``,c=n.trim().replace(/^\/+|\/+$/g,``);for(let n=0;n<1e3;n++){let r=n===0?i:`${o}-${n+1}${s}`,a=c?`${c}/${r}`:r;if(!await P(e,t,a))return a}return c?`${c}/${fe()}-${i}`:`${fe()}-${i}`}async function NK(e,t,n){let r=typeof t.action==`string`?t.action.trim():``;if(!r)return`Error: manage_email requires action.`;if(r===`list_plugins`){let e=nK();return e.length?e.map(e=>`- ${e.id} (${e.protocol})\n Name: ${e.name}\n Actions: ${e.actions.join(`, `)}\n Auth: ${e.authTypes.join(`, `)}\n Fields: ${e.configurableFields.join(`, `)||`(none)`}`).join(`
1805
1805
 
1806
1806
  `):`No integration plugins are available.`}if(r===`list_connections`){let t=await cK(e);return t.length?t.map(e=>{let t=rK(e.pluginId),n=Object.keys(e.config||{});return`- ${e.id} (${e.label})\n Plugin: ${e.pluginId}${t?` (${t.name})`:``}\n Enabled: ${e.enabled}\n Config keys: ${n.join(`, `)||`(none)`}`}).join(`
@@ -0,0 +1 @@
1
+ import{et as e}from"./config-C16fFWtP.js";import{n as t}from"./mime-ClqNyXPc.js";function n(e=``,n=``){let r=(e&&e!==`application/octet-stream`?e:t(n)||e).toLowerCase(),i=n.toLowerCase();return r.startsWith(`text/`)||r.includes(`json`)||r.includes(`xml`)||i.endsWith(`.md`)||i.endsWith(`.txt`)?`text`:r.startsWith(`image/`)?`image`:r.startsWith(`audio/`)?`audio`:r.startsWith(`video/`)?`video`:r===`application/pdf`||i.endsWith(`.pdf`)?`document`:`file`}function r(t){let n=(t||``).toLowerCase(),r=e.getModelInfo(n);if(r){let e=r.supportsImageInput===!0||r.routesByRequestFeatures===!0,t=r.supportsAudioInput===!0||r.routesByRequestFeatures===!0,n=r.supportsVideoInput===!0||r.routesByRequestFeatures===!0,i=r.supportsDocumentInput===!0||r.routesByRequestFeatures===!0;if(r.supportsImageInput!==void 0||r.supportsAudioInput!==void 0||r.supportsVideoInput!==void 0||r.supportsDocumentInput!==void 0||r.routesByRequestFeatures)return{images:e,audio:t,video:n,documents:i,routerByFeatures:!!r.routesByRequestFeatures,source:`metadata`}}let i=n.includes(`no-vision`)||n.includes(`non-vision`)||n.includes(`text-only`),a=n===`openrouter/free`||n===`openrouter/auto`,o=!i&&[`gpt-4o`,`gpt-4.1`,`gpt-5`,`gpt-6`,`astra`,`claude-3`,`claude-4`,`claude-5`,`claude-sonnet`,`claude-haiku`,`claude-opus`,`claude-fable`,`claude-mythos`,`gemini`,`omni`,`llava`,`qwen-vl`,`-vl`,`vision`,`pixtral`].some(e=>n.includes(e)),s=!i&&(n.includes(`claude-3-5`)||n.includes(`claude-3.5`)||n.includes(`claude-3-7`)||n.includes(`claude-3.7`)||n.includes(`claude-4`)||n.includes(`claude-5`)||n.includes(`claude-fable`)||n.includes(`claude-mythos`)||n.includes(`gemini`)||n.includes(`gpt-4.1`)||n.includes(`gpt-5`)||n.includes(`gpt-6`)||n.includes(`astra`)||/claude-(?:sonnet|haiku|opus|fable|mythos)-\d/.test(n));return o?{images:!0,audio:n.includes(`omni`)||n.includes(`audio`),video:n.includes(`omni`)||n.includes(`video`)||n.includes(`gemini`),documents:s,routerByFeatures:a,source:`heuristic`}:{images:!1,audio:!1,video:!1,documents:!1,routerByFeatures:a,source:`unknown`}}function i(e){let t=r(e),n=[t.images?`images native`:`images fallback`,t.audio?`audio native`:`audio fallback`,t.video?`video native`:`video fallback`,t.documents?`PDFs native`:`PDFs fallback`];return t.routerByFeatures&&n.push(`router can adapt by request features`),n.join(` · `)}export{n,r,i as t};
@@ -1 +1 @@
1
- import{o as e,r as t}from"./config-C-YdSFZB.js";import{t as n}from"./get-config-Bkvl__ZS.js";import{c as r,t as i}from"./orchestrator-CaUpEVkQ.js";import{t as a}from"./set-config-DSiuMe0k.js";import{r as o}from"./crypto-4ETeplbS.js";function s(e,t){return e.channelRegistry?.getChannelType(t)??`browser`}function c(e,t){switch(t){case`browser`:return e.browserChat;case`telegram`:return e.telegram;case`imessage`:return e.imessage;case`peerjs`:return e.peerjs;default:return null}}function l(e,t){return t===`browser`||e.channelEnabledByType[t]!==!1}function u(e){return{enabled:l(e,`peerjs`),myAlias:e.peerjsMyAlias,myPeerId:e.peerjsMyPeerId,peerAliases:{...e.peerjsPeerAliases},serverHost:e.peerjsServerHost,serverPath:e.peerjsServerPath,serverPort:e.peerjsServerPort,serverSecure:e.peerjsServerSecure,trustedPeerIds:[...e.peerjsTrustedPeerIds]}}function d(e){return{botToken:e.telegramBotToken,chatIds:[...e.telegramChatIds],enabled:l(e,`telegram`),useProxy:e.telegramUseProxy}}function f(e){return{apiKey:e.imessageApiKey,chatIds:[...e.imessageChatIds],enabled:l(e,`imessage`),serverUrl:e.imessageServerUrl}}function p(e){return`${t.CHANNEL_ENABLED_PREFIX}${e}`}function m(e,t){if(t===`browser`)return!0;if(!l(e,t))return!1;switch(t){case`telegram`:return e.telegramBotToken.length>0;case`imessage`:return e.imessageServerUrl.length>0;case`peerjs`:return e.peerjsMyPeerId.length>0;default:return!0}}function h(e,t,n=!1){let r=c(e,t);r&&(m(e,t)?r.running?typeof r.ensureConnected==`function`&&r.ensureConnected(n):r.start():r.stop())}function g(e,t=!1){h(e,`browser`,t),h(e,`telegram`,t),h(e,`imessage`,t),h(e,`peerjs`,t)}function _(e){i.setRemoteAgentTyping(e,!1)}async function v(e,t,r=n){let i=await r(t,p(e));return i?i!==`false`:!1}async function y(e,t,n,r,i=a){if(n===`browser`)return;let o=!!r;e.channelEnabledByType[n]=o,await i(t,p(n),o?`true`:`false`),h(e,n)}function b(t,n,r=e,i=[],a){t.browserChat.submit(n,r,i,a)}async function x(e,t,n,r=a){if(!n){await r(e,t,``);return}let i=await o(n);if(!i)throw Error(`Failed to encrypt secret config for ${t}`);await r(e,t,i)}async function S(e,n,i,o,s,c=a,u=x){let d=i.trim().replace(/\/+$/,``),f=o.trim(),p=r(s);e.imessageServerUrl=d,e.imessageApiKey=f,e.imessageChatIds=p,await c(n,t.IMESSAGE_SERVER_URL,d),await u(n,t.IMESSAGE_API_KEY,f),await c(n,t.IMESSAGE_CHAT_IDS,JSON.stringify(p)),e.imessage.stop(),e.imessage.configure(d,f,p),d&&l(e,`imessage`)&&e.imessage.start()}async function C(e,n,i,o,s=!1,c=a,u=x){let d=i.trim(),f=r(o),p=!!s;e.telegramBotToken=d,e.telegramChatIds=f,e.telegramUseProxy=p,await u(n,t.TELEGRAM_BOT_TOKEN,d),await c(n,t.TELEGRAM_CHAT_IDS,JSON.stringify(f)),await c(n,t.TELEGRAM_USE_PROXY,p?`true`:`false`),e.telegram.stop(),e.telegram.configure(d,f,p),d&&l(e,`telegram`)&&e.telegram.start()}export{l as a,u as c,y as d,b as f,C as i,d as l,_ as n,s as o,S as r,f as s,g as t,v as u};
1
+ import{o as e,r as t}from"./config-C16fFWtP.js";import{t as n}from"./get-config-Bkvl__ZS.js";import{c as r,t as i}from"./orchestrator-DBO4NZqd.js";import{t as a}from"./set-config-DSiuMe0k.js";import{r as o}from"./crypto-4ETeplbS.js";function s(e,t){return e.channelRegistry?.getChannelType(t)??`browser`}function c(e,t){switch(t){case`browser`:return e.browserChat;case`telegram`:return e.telegram;case`imessage`:return e.imessage;case`peerjs`:return e.peerjs;default:return null}}function l(e,t){return t===`browser`||e.channelEnabledByType[t]!==!1}function u(e){return{enabled:l(e,`peerjs`),myAlias:e.peerjsMyAlias,myPeerId:e.peerjsMyPeerId,peerAliases:{...e.peerjsPeerAliases},serverHost:e.peerjsServerHost,serverPath:e.peerjsServerPath,serverPort:e.peerjsServerPort,serverSecure:e.peerjsServerSecure,trustedPeerIds:[...e.peerjsTrustedPeerIds]}}function d(e){return{botToken:e.telegramBotToken,chatIds:[...e.telegramChatIds],enabled:l(e,`telegram`),useProxy:e.telegramUseProxy}}function f(e){return{apiKey:e.imessageApiKey,chatIds:[...e.imessageChatIds],enabled:l(e,`imessage`),serverUrl:e.imessageServerUrl}}function p(e){return`${t.CHANNEL_ENABLED_PREFIX}${e}`}function m(e,t){if(t===`browser`)return!0;if(!l(e,t))return!1;switch(t){case`telegram`:return e.telegramBotToken.length>0;case`imessage`:return e.imessageServerUrl.length>0;case`peerjs`:return e.peerjsMyPeerId.length>0;default:return!0}}function h(e,t,n=!1){let r=c(e,t);r&&(m(e,t)?r.running?typeof r.ensureConnected==`function`&&r.ensureConnected(n):r.start():r.stop())}function g(e,t=!1){h(e,`browser`,t),h(e,`telegram`,t),h(e,`imessage`,t),h(e,`peerjs`,t)}function _(e){i.setRemoteAgentTyping(e,!1)}async function v(e,t,r=n){let i=await r(t,p(e));return i?i!==`false`:!1}async function y(e,t,n,r,i=a){if(n===`browser`)return;let o=!!r;e.channelEnabledByType[n]=o,await i(t,p(n),o?`true`:`false`),h(e,n)}function b(t,n,r=e,i=[],a){t.browserChat.submit(n,r,i,a)}async function x(e,t,n,r=a){if(!n){await r(e,t,``);return}let i=await o(n);if(!i)throw Error(`Failed to encrypt secret config for ${t}`);await r(e,t,i)}async function S(e,n,i,o,s,c=a,u=x){let d=i.trim().replace(/\/+$/,``),f=o.trim(),p=r(s);e.imessageServerUrl=d,e.imessageApiKey=f,e.imessageChatIds=p,await c(n,t.IMESSAGE_SERVER_URL,d),await u(n,t.IMESSAGE_API_KEY,f),await c(n,t.IMESSAGE_CHAT_IDS,JSON.stringify(p)),e.imessage.stop(),e.imessage.configure(d,f,p),d&&l(e,`imessage`)&&e.imessage.start()}async function C(e,n,i,o,s=!1,c=a,u=x){let d=i.trim(),f=r(o),p=!!s;e.telegramBotToken=d,e.telegramChatIds=f,e.telegramUseProxy=p,await u(n,t.TELEGRAM_BOT_TOKEN,d),await c(n,t.TELEGRAM_CHAT_IDS,JSON.stringify(f)),await c(n,t.TELEGRAM_USE_PROXY,p?`true`:`false`),e.telegram.stop(),e.telegram.configure(d,f,p),d&&l(e,`telegram`)&&e.telegram.start()}export{l as a,u as c,y as d,b as f,C as i,d as l,_ as n,s as o,S as r,f as s,g as t,v as u};
@@ -1,3 +1,3 @@
1
- import{z as e}from"./config-C-YdSFZB.js";import{n as t}from"./create-model-cache-fetch-DQebkoPL.js";var n=Object.defineProperty,r=(e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,i=(e,t,n)=>(r(e,typeof t==`symbol`?t:t+``,n),n),a=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ExponentiationBinaryOperator:`ExponentiationBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`});a.OpenStatement,a.CloseStatement,a.OpenExpression,a.CloseExpression,a.OpenParen,a.CloseParen,a.OpenCurlyBracket,a.CloseCurlyBracket,a.OpenSquareBracket,a.CloseSquareBracket,a.Comma,a.Dot,a.Colon,a.Pipe,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.AdditiveBinaryOperator,a.AdditiveBinaryOperator,a.AdditiveBinaryOperator,a.ExponentiationBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.Equals;function o(e){return e.replace(/\b\w/g,e=>e.toUpperCase())}function s(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function c(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?/* @__PURE__ */ RegExp(`(?=)`,`gu`):new RegExp(s(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var l=/* @__PURE__ */ new Map,u=class{type=`RuntimeValue`;value;get builtins(){return l}constructor(e=void 0){this.value=e}__bool__(){return new m(!!this.value)}toString(){return String(this.value)}},d=class extends u{type=`IntegerValue`},f=class extends u{type=`FloatValue`;toString(){return Object.is(this.value,-0)?`-0.0`:this.value%1==0?this.value.toFixed(1):this.value.toString()}},p=class extends u{type=`StringValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`upper`,new S(()=>new p(this.value.toUpperCase()))],[`lower`,new S(()=>new p(this.value.toLowerCase()))],[`strip`,new S(()=>new p(this.value.trim()))],[`title`,new S(()=>new p(o(this.value)))],[`capitalize`,new S(()=>new p(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new d(this.value.length)],[`rstrip`,new S(()=>new p(this.value.trimEnd()))],[`lstrip`,new S(()=>new p(this.value.trimStart()))],[`startswith`,new S(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof p)return new m(this.value.startsWith(t.value));if(t instanceof x){for(let e of t.value){if(!(e instanceof p))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new m(!0)}return new m(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new S(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof p)return new m(this.value.endsWith(t.value));if(t instanceof x){for(let e of t.value){if(!(e instanceof p))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new m(!0)}return new m(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new S(e=>{let t=e[0]??new C;if(!(t instanceof p||t instanceof C))throw Error(`sep argument must be a string or null`);let n=e[1]??new d(-1);if(!(n instanceof d))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof C){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new x(r.map(e=>new p(e)))})],[`replace`,new S(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof p&&n instanceof p))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new C:e[2]:new C,!(r instanceof d||r instanceof C))throw Error(`replace() count argument must be a number or null`);return new p(c(this.value,t.value,n.value,r.value))})]])}},m=class extends u{type=`BooleanValue`},h=/[\x7f-\uffff]/g;function g(e){return e.replace(h,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function _(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=g(t)),t}case`ArrayValue`:case`NamespaceValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=`
1
+ import{et as e}from"./config-C16fFWtP.js";import{n as t}from"./create-model-cache-fetch-DSAFjOwc.js";var n=Object.defineProperty,r=(e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,i=(e,t,n)=>(r(e,typeof t==`symbol`?t:t+``,n),n),a=Object.freeze({Text:`Text`,NumericLiteral:`NumericLiteral`,StringLiteral:`StringLiteral`,Identifier:`Identifier`,Equals:`Equals`,OpenParen:`OpenParen`,CloseParen:`CloseParen`,OpenStatement:`OpenStatement`,CloseStatement:`CloseStatement`,OpenExpression:`OpenExpression`,CloseExpression:`CloseExpression`,OpenSquareBracket:`OpenSquareBracket`,CloseSquareBracket:`CloseSquareBracket`,OpenCurlyBracket:`OpenCurlyBracket`,CloseCurlyBracket:`CloseCurlyBracket`,Comma:`Comma`,Dot:`Dot`,Colon:`Colon`,Pipe:`Pipe`,CallOperator:`CallOperator`,AdditiveBinaryOperator:`AdditiveBinaryOperator`,MultiplicativeBinaryOperator:`MultiplicativeBinaryOperator`,ExponentiationBinaryOperator:`ExponentiationBinaryOperator`,ComparisonBinaryOperator:`ComparisonBinaryOperator`,UnaryOperator:`UnaryOperator`,Comment:`Comment`});a.OpenStatement,a.CloseStatement,a.OpenExpression,a.CloseExpression,a.OpenParen,a.CloseParen,a.OpenCurlyBracket,a.CloseCurlyBracket,a.OpenSquareBracket,a.CloseSquareBracket,a.Comma,a.Dot,a.Colon,a.Pipe,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.ComparisonBinaryOperator,a.AdditiveBinaryOperator,a.AdditiveBinaryOperator,a.AdditiveBinaryOperator,a.ExponentiationBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.MultiplicativeBinaryOperator,a.Equals;function o(e){return e.replace(/\b\w/g,e=>e.toUpperCase())}function s(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function c(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?/* @__PURE__ */ RegExp(`(?=)`,`gu`):new RegExp(s(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var l=/* @__PURE__ */ new Map,u=class{type=`RuntimeValue`;value;get builtins(){return l}constructor(e=void 0){this.value=e}__bool__(){return new m(!!this.value)}toString(){return String(this.value)}},d=class extends u{type=`IntegerValue`},f=class extends u{type=`FloatValue`;toString(){return Object.is(this.value,-0)?`-0.0`:this.value%1==0?this.value.toFixed(1):this.value.toString()}},p=class extends u{type=`StringValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`upper`,new S(()=>new p(this.value.toUpperCase()))],[`lower`,new S(()=>new p(this.value.toLowerCase()))],[`strip`,new S(()=>new p(this.value.trim()))],[`title`,new S(()=>new p(o(this.value)))],[`capitalize`,new S(()=>new p(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new d(this.value.length)],[`rstrip`,new S(()=>new p(this.value.trimEnd()))],[`lstrip`,new S(()=>new p(this.value.trimStart()))],[`startswith`,new S(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof p)return new m(this.value.startsWith(t.value));if(t instanceof x){for(let e of t.value){if(!(e instanceof p))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new m(!0)}return new m(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new S(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof p)return new m(this.value.endsWith(t.value));if(t instanceof x){for(let e of t.value){if(!(e instanceof p))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new m(!0)}return new m(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new S(e=>{let t=e[0]??new C;if(!(t instanceof p||t instanceof C))throw Error(`sep argument must be a string or null`);let n=e[1]??new d(-1);if(!(n instanceof d))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof C){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new x(r.map(e=>new p(e)))})],[`replace`,new S(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof p&&n instanceof p))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new C:e[2]:new C,!(r instanceof d||r instanceof C))throw Error(`replace() count argument must be a number or null`);return new p(c(this.value,t.value,n.value,r.value))})]])}},m=class extends u{type=`BooleanValue`},h=/[\x7f-\uffff]/g;function g(e){return e.replace(h,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function _(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=g(t)),t}case`ArrayValue`:case`NamespaceValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=`
2
2
  `+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>_(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=g(s));let c=`${s}${l}${_(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var v=class extends u{type=`ObjectValue`;_builtins;__bool__(){return new m(this.value.size>0)}get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`get`,new S(([e,t])=>{if(!(e instanceof p))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new C})],[`items`,new S(()=>this.items())],[`keys`,new S(()=>this.keys())],[`values`,new S(()=>this.values())],[`dictsort`,new S(e=>{let t=/* @__PURE__ */ new Map,n=e.filter(e=>e instanceof y?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new m(!1);if(!(r instanceof m))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new p(`key`);if(!(i instanceof p))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new m(!1);if(!(a instanceof m))throw Error(`reverse must be a boolean`);return new x(Array.from(this.value.entries()).map(([e,t])=>new x([new p(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=k(o,s,r.value);return a.value?-c:c}))})]])}items(){return new x(Array.from(this.value.entries()).map(([e,t])=>new x([new p(e),t])))}keys(){return new x(Array.from(this.value.keys()).map(e=>new p(e)))}values(){return new x(Array.from(this.value.values()))}toString(){return _(this,{},0,!1)}},y=class extends v{type=`KeywordArgumentsValue`},b=class extends u{type=`NamespaceValue`;toString(){return _(this,{},0,!1)}},x=class extends u{type=`ArrayValue`;_builtins;get builtins(){return this._builtins??=/* @__PURE__ */ new Map([[`length`,new d(this.value.length)]])}__bool__(){return new m(this.value.length>0)}toString(){return _(this,{},0,!1)}},S=class extends u{type=`FunctionValue`},C=class extends u{type=`NullValue`},w=class extends u{type=`UndefinedValue`};function T(e){let t;if(e instanceof x?t=e.value:e instanceof p&&(t=Array.from(e.value,e=>new p(e))),!t||t.length!==2)throw Error(`namespace expected an object or an iterable of [key, value] pairs`);let[n,r]=t;if(!(n instanceof p))throw Error(`namespace keys must be strings`);return[n,r]}var E=class{constructor(e){this.parent=e}variables=/* @__PURE__ */ new Map([[`namespace`,new S(e=>{let t=e.slice(),n;if(t.at(-1)instanceof y&&(n=t.pop()),t.length>1)throw Error(`namespace expected at most 1 argument, got ${t.length}`);let r=/* @__PURE__ */ new Map;if(t.length===1){let e=t[0];if(e instanceof v)for(let[t,n]of e.value)r.set(t,n);else if(e instanceof x)for(let t of e.value){let[e,n]=T(t);r.set(e.value,n)}else throw Error(`'${e.type}' object is not iterable`)}if(n)for(let[e,t]of n.value)r.set(e,t);return new b(r)})]]);tests=E.TESTS;set(e,t){return this.declareVariable(e,A(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new w}catch{return new w}}};i(E,`TESTS`,/* @__PURE__ */ new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof S],[`odd`,e=>{if(!(e instanceof d))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof d))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof d||e instanceof f],[`integer`,e=>e instanceof d],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof v],[`sequence`,e=>e instanceof x||e instanceof v||e instanceof p],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]));function D(e){return e instanceof d||e instanceof f||e instanceof m}function O(e){return e instanceof m?Number(e.value):e.value}function k(e,t,n=!1){if(e instanceof C&&t instanceof C)return 0;if(e instanceof C||t instanceof C)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(e instanceof w&&t instanceof w)return 0;if(e instanceof w||t instanceof w)throw Error(`Cannot compare ${e.type} with ${t.type}`);if(D(e)&&D(t)){let n=O(e),r=O(t);return n<r?-1:+(n>r)}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),r<i?-1:+(r>i)}default:throw Error(`Cannot compare type: ${e.type}`)}}function A(e){switch(typeof e){case`number`:return Number.isInteger(e)?new d(e):new f(e);case`string`:return new p(e);case`boolean`:return new m(e);case`undefined`:return new w;case`object`:return e===null?new C:Array.isArray(e)?new x(e.map(A)):new v(new Map(Object.entries(e).map(([e,t])=>[e,A(t)])));case`function`:return new S((t,n)=>A(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}Object.freeze({CONDITIONAL:0,LOGICAL_OR:1,LOGICAL_AND:2,LOGICAL_NOT:3,COMPARISON:4,ADDITIVE:5,MULTIPLICATIVE:6,EXPONENTIATION:7,TEST:8,FILTER:9,UNARY_SIGN:10,ATOM:11});const j=/* @__PURE__ */ new Map;function M(e){return typeof e==`string`?e:e?Array.isArray(e)?e.map(e=>{if(!e)return``;if(typeof e==`string`)return e;if(e.type===`text`)return e.text||e.value||``;if(e.type===`tool_use`)return`[TOOL_CALL ${e.name}] ${JSON.stringify(e.input||{})}`;if(e.type===`tool_result`){let t=typeof e.content==`string`?e.content:JSON.stringify(e.content||``);return`[TOOL_RESULT ${e.tool_use_id||``}] ${t}`}return e.type===`attachment`?`[ATTACHMENT ${e.mediaType||`file`}] ${e.fileName||`attachment`}`:``}).filter(Boolean).join(`
3
3
  `):typeof e==`object`?JSON.stringify(e):String(e):``}async function N(n,r){let i=String(n||``).trim();if(!i)return null;if(j.has(i))return j.get(i);let a=r||(typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0);if(!a)return null;let o=r||t(a),s=`https://huggingface.co/${encodeURI(i)}/resolve/main/tokenizer_config.json`;try{let t=await o(s);if(t.ok){let n=await t.json();if(n&&typeof n==`object`){if(!n.chat_template)try{let e=await o(`https://huggingface.co/${encodeURI(i)}/resolve/main/chat_template.jinja`);if(e.ok){let t=await e.text();t&&t.trim()&&(n.chat_template=t.trim())}}catch{}if(typeof n.model_max_length==`number`&&Number.isFinite(n.model_max_length)&&n.model_max_length>0&&n.model_max_length<=2097152){let t=e.getModelInfo(i);e.registerModelInfo(i,{contextWindow:n.model_max_length,maxOutput:t?.maxOutput??null,...t||{}})}return j.set(i,n),n}}}catch{}return null}function P(e,t){let n=String(t||``).trim(),r=[],i=/* @__PURE__ */ new Map;for(let t of e){if(t?.tool_calls&&Array.isArray(t.tool_calls))for(let e of t.tool_calls){let t=e?.id||e?.tool_call_id,n=e?.function?.name||e?.name;t&&n&&i.set(t,n)}if(Array.isArray(t?.content))for(let e of t.content)e?.type===`tool_use`&&e.id&&e.name&&i.set(e.id,e.name)}for(let t of e){if(!t)continue;let e=String(t.role||`user`).toLowerCase(),a=M(t.content);if(e===`system`)n=n?`${n}\n\n${a}`:a;else if(e===`tool`){let e=t.name||(t.tool_call_id?i.get(t.tool_call_id):void 0)||`unknown`;r.push({role:`tool`,content:a,...t.tool_call_id?{tool_call_id:t.tool_call_id}:{},name:e})}else if(e===`assistant`||e===`model`){let e=t.tool_calls,n=a;if(Array.isArray(t.content)){let r=t.content.filter(e=>e?.type===`tool_use`);r.length>0&&(e||=r.map(e=>({id:e.id||`call_${Math.random().toString(36).slice(2,9)}`,type:`function`,function:{name:e.name,arguments:typeof e.input==`object`&&e.input!==null?e.input:{}}})),n=M(t.content.filter(e=>e?.type!==`tool_use`)))}Array.isArray(e)&&(e=e.map(e=>{if(!e||typeof e!=`object`)return e;let t=e.function;if(t&&typeof t==`object`&&typeof t.arguments==`string`)try{let n=JSON.parse(t.arguments);if(n&&typeof n==`object`&&!Array.isArray(n))return{...e,function:{...t,arguments:n}}}catch{}return e})),r.push({role:`assistant`,content:n,...e?{tool_calls:e}:{}})}else if(Array.isArray(t.content)&&t.content.some(e=>e?.type===`tool_result`))for(let e of t.content)if(e?.type===`tool_result`){let t=typeof e.content==`string`?e.content:JSON.stringify(e.content||``),n=e.name||(e.tool_use_id?i.get(e.tool_use_id):void 0)||`unknown`;r.push({role:`tool`,content:t,...e.tool_use_id?{tool_call_id:e.tool_use_id}:{},name:n})}else{let t=M([e]);t&&r.push({role:`user`,content:t})}else r.push({role:`user`,content:a})}let a=[];for(let e of r)if(a.length>0&&a[a.length-1].role===e.role&&e.role!==`tool`){let t=a[a.length-1];t.content=t.content?`${t.content}\n\n${e.content}`:e.content,e.tool_calls&&(t.tool_calls=[...t.tool_calls||[],...e.tool_calls])}else a.push({...e});a.length>0&&a[0].role===`assistant`&&a.unshift({role:`user`,content:`Hello`}),a.length===0&&!n&&a.push({role:`user`,content:`Hello`});let o=[];return n&&o.push({role:`system`,content:n}),o.push(...a),o}export{P as n,N as t};