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,4 +1,4 @@
1
- import{p as e}from"./custom-element-security-kiDhPfb8.js";import{b as t,r as n}from"./config-C-YdSFZB.js";import{n as r}from"./db-BUuJo1Gf.js";import{t as i}from"./get-config-Bkvl__ZS.js";import{t as a}from"./html-BwtE_7wp.js";import{a as o,r as s}from"./toast-CtIuHprH.js";import"./shadow-claw-card-IbNlZAdK.js";import"./shadow-claw-empty-state-D4CrFGsN.js";import{o as c}from"./shadow-claw-DdgeYPg5.js";function l(e){return!e||e.authMode===`token`||e.authMode===`token`?`token`:e.authMode===`basic`?`basic`:e.authMode===`oauth`||e.oauthProviderId||e.oauthClientId||e.oauthClientSecret||e.refreshToken||e.accessTokenExpiresAt||e.tokenType||e.oauthReauthRequired?`oauth`:`token`}const u=new CSSStyleSheet;u.replaceSync(`*,
1
+ import{p as e}from"./custom-element-security-B2daIE5r.js";import{b as t,r as n}from"./config-C16fFWtP.js";import{n as r}from"./db-BUuJo1Gf.js";import{t as i}from"./get-config-Bkvl__ZS.js";import{t as a}from"./html-BwtE_7wp.js";import{a as o,r as s}from"./toast-CtIuHprH.js";import"./shadow-claw-card-CggS8uSa.js";import"./shadow-claw-empty-state-CkpOSXCS.js";import{o as c}from"./shadow-claw-Br8mWDUx.js";function l(e){return!e||e.authMode===`token`||e.authMode===`token`?`token`:e.authMode===`basic`?`basic`:e.authMode===`oauth`||e.oauthProviderId||e.oauthClientId||e.oauthClientSecret||e.refreshToken||e.accessTokenExpiresAt||e.tokenType||e.oauthReauthRequired?`oauth`:`token`}const u=new CSSStyleSheet;u.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -1,4 +1,4 @@
1
- import{o as e}from"./shadow-claw-DdgeYPg5.js";const t=new CSSStyleSheet;t.replaceSync(`:host {
1
+ import{o as e}from"./shadow-claw-Br8mWDUx.js";const t=new CSSStyleSheet;t.replaceSync(`:host {
2
2
  display: contents;
3
3
  }
4
4
 
@@ -1,4 +1,4 @@
1
- import{i as e,t}from"./rolldown-runtime-DBVvNlSN.js";import{n}from"./db-BUuJo1Gf.js";import{t as r}from"./orchestrator-CaUpEVkQ.js";import{t as i}from"./ulid-BSJxYh6W.js";import{a,r as o,s}from"./toast-CtIuHprH.js";import{_ as c,g as l}from"./provider-DNIL4-Hw.js";import{c as u,d,o as f,u as p}from"./transformers-C-DuTM2K.js";import"./shadow-claw-page-header-action-button-2DH5O1TD.js";import{c as m,d as h,i as g,l as _,r as v,s as y}from"./channel-BylT3rJC.js";import{t as b}from"./configure-peer-js-DChhcOfe.js";import{i as x}from"./rooms-C6LXIJl4.js";import"./shadow-claw-page-header-CjJpVkyL.js";import{a as S,o as C}from"./shadow-claw-DdgeYPg5.js";var w=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){return typeof Promise==`function`&&Promise.prototype&&Promise.prototype.then}})),T=/* @__PURE__ */ t((e=>{let t,n=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];e.getSymbolSize=function(e){if(!e)throw Error(`"version" cannot be null or undefined`);if(e<1||e>40)throw Error(`"version" should be in range from 1 to 40`);return e*4+17},e.getSymbolTotalCodewords=function(e){return n[e]},e.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},e.setToSJISFunction=function(e){if(typeof e!=`function`)throw Error(`"toSJISFunc" is not a valid function.`);t=e},e.isKanjiModeEnabled=function(){return t!==void 0},e.toSJIS=function(e){return t(e)}})),E=/* @__PURE__ */ t((e=>{e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(t){if(typeof t!=`string`)throw Error(`Param is not a string`);switch(t.toLowerCase()){case`l`:case`low`:return e.L;case`m`:case`medium`:return e.M;case`q`:case`quartile`:return e.Q;case`h`:case`high`:return e.H;default:throw Error(`Unknown EC Level: `+t)}}e.isValid=function(e){return e&&e.bit!==void 0&&e.bit>=0&&e.bit<4},e.from=function(n,r){if(e.isValid(n))return n;try{return t(n)}catch{return r}}})),D=/* @__PURE__ */ t(((e,t)=>{function n(){this.buffer=[],this.length=0}n.prototype={get:function(e){let t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)==1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){let t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}},t.exports=n})),ee=/* @__PURE__ */ t(((e,t)=>{function n(e){if(!e||e<1)throw Error(`BitMatrix size must be defined and greater than 0`);this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}n.prototype.set=function(e,t,n,r){let i=e*this.size+t;this.data[i]=n,r&&(this.reservedBit[i]=!0)},n.prototype.get=function(e,t){return this.data[e*this.size+t]},n.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},n.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]},t.exports=n})),te=/* @__PURE__ */ t((e=>{let t=T().getSymbolSize;e.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=t(e),i=r===145?26:Math.ceil((r-13)/(2*n-2))*2,a=[r-7];for(let e=1;e<n-1;e++)a[e]=a[e-1]-i;return a.push(6),a.reverse()},e.getPositions=function(t){let n=[],r=e.getRowColCoords(t),i=r.length;for(let e=0;e<i;e++)for(let t=0;t<i;t++)e===0&&t===0||e===0&&t===i-1||e===i-1&&t===0||n.push([r[e],r[t]]);return n}})),ne=/* @__PURE__ */ t((e=>{let t=T().getSymbolSize;e.getPositions=function(e){let n=t(e);return[[0,0],[n-7,0],[0,n-7]]}})),O=/* @__PURE__ */ t((e=>{e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};let t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(e){return e!=null&&e!==``&&!isNaN(e)&&e>=0&&e<=7},e.from=function(t){return e.isValid(t)?parseInt(t,10):void 0},e.getPenaltyN1=function(e){let n=e.size,r=0,i=0,a=0,o=null,s=null;for(let c=0;c<n;c++){i=a=0,o=s=null;for(let l=0;l<n;l++){let n=e.get(c,l);n===o?i++:(i>=5&&(r+=t.N1+(i-5)),o=n,i=1),n=e.get(l,c),n===s?a++:(a>=5&&(r+=t.N1+(a-5)),s=n,a=1)}i>=5&&(r+=t.N1+(i-5)),a>=5&&(r+=t.N1+(a-5))}return r},e.getPenaltyN2=function(e){let n=e.size,r=0;for(let t=0;t<n-1;t++)for(let i=0;i<n-1;i++){let n=e.get(t,i)+e.get(t,i+1)+e.get(t+1,i)+e.get(t+1,i+1);(n===4||n===0)&&r++}return r*t.N2},e.getPenaltyN3=function(e){let n=e.size,r=0,i=0,a=0;for(let t=0;t<n;t++){i=a=0;for(let o=0;o<n;o++)i=i<<1&2047|e.get(t,o),o>=10&&(i===1488||i===93)&&r++,a=a<<1&2047|e.get(o,t),o>=10&&(a===1488||a===93)&&r++}return r*t.N3},e.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let t=0;t<r;t++)n+=e.data[t];return Math.abs(Math.ceil(n*100/r/5)-10)*t.N4};function n(t,n,r){switch(t){case e.Patterns.PATTERN000:return(n+r)%2==0;case e.Patterns.PATTERN001:return n%2==0;case e.Patterns.PATTERN010:return r%3==0;case e.Patterns.PATTERN011:return(n+r)%3==0;case e.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(r/3))%2==0;case e.Patterns.PATTERN101:return n*r%2+n*r%3==0;case e.Patterns.PATTERN110:return(n*r%2+n*r%3)%2==0;case e.Patterns.PATTERN111:return(n*r%3+(n+r)%2)%2==0;default:throw Error(`bad maskPattern:`+t)}}e.applyMask=function(e,t){let r=t.size;for(let i=0;i<r;i++)for(let a=0;a<r;a++)t.isReserved(a,i)||t.xor(a,i,n(e,a,i))},e.getBestMask=function(t,n){let r=Object.keys(e.Patterns).length,i=0,a=1/0;for(let o=0;o<r;o++){n(o),e.applyMask(o,t);let r=e.getPenaltyN1(t)+e.getPenaltyN2(t)+e.getPenaltyN3(t)+e.getPenaltyN4(t);e.applyMask(o,t),r<a&&(a=r,i=o)}return i}})),k=/* @__PURE__ */ t((e=>{let t=E(),n=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];e.getBlocksCount=function(e,r){switch(r){case t.L:return n[(e-1)*4+0];case t.M:return n[(e-1)*4+1];case t.Q:return n[(e-1)*4+2];case t.H:return n[(e-1)*4+3];default:return}},e.getTotalCodewordsCount=function(e,n){switch(n){case t.L:return r[(e-1)*4+0];case t.M:return r[(e-1)*4+1];case t.Q:return r[(e-1)*4+2];case t.H:return r[(e-1)*4+3];default:return}}})),re=/* @__PURE__ */ t((e=>{let t=/* @__PURE__ */ new Uint8Array(512),n=/* @__PURE__ */ new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)t[r]=e,n[e]=r,e<<=1,e&256&&(e^=285);for(let e=255;e<512;e++)t[e]=t[e-255]})(),e.log=function(e){if(e<1)throw Error(`log(`+e+`)`);return n[e]},e.exp=function(e){return t[e]},e.mul=function(e,r){return e===0||r===0?0:t[n[e]+n[r]]}})),A=/* @__PURE__ */ t((e=>{let t=re();e.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let i=0;i<e.length;i++)for(let a=0;a<n.length;a++)r[i+a]^=t.mul(e[i],n[a]);return r},e.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let e=r[0];for(let i=0;i<n.length;i++)r[i]^=t.mul(n[i],e);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r},e.generateECPolynomial=function(n){let r=new Uint8Array([1]);for(let i=0;i<n;i++)r=e.mul(r,new Uint8Array([1,t.exp(i)]));return r}})),ie=/* @__PURE__ */ t(((e,t)=>{let n=A();function r(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}r.prototype.initialize=function(e){this.degree=e,this.genPoly=n.generateECPolynomial(this.degree)},r.prototype.encode=function(e){if(!this.genPoly)throw Error(`Encoder not initialized`);let t=new Uint8Array(e.length+this.degree);t.set(e);let r=n.mod(t,this.genPoly),i=this.degree-r.length;if(i>0){let e=new Uint8Array(this.degree);return e.set(r,i),e}return r},t.exports=r})),j=/* @__PURE__ */ t((e=>{e.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}})),M=/* @__PURE__ */ t((e=>{let t=`(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+`;t=t.replace(/u/g,`\\u`);let n=`(?:(?![A-Z0-9 $%*+\\-./:]|`+t+`)(?:.|[\r
1
+ import{i as e,t}from"./rolldown-runtime-DBVvNlSN.js";import{n}from"./db-BUuJo1Gf.js";import{t as r}from"./orchestrator-DBO4NZqd.js";import{t as i}from"./ulid-BSJxYh6W.js";import{a,r as o,s}from"./toast-CtIuHprH.js";import{_ as c,g as l}from"./provider-YPZmsuHR.js";import{c as u,d,o as f,u as p}from"./transformers-CQ9ss9rD.js";import"./shadow-claw-page-header-action-button-BnCV_2Kb.js";import{c as m,d as h,i as g,l as _,r as v,s as y}from"./channel-Dk7wl-Av.js";import{t as b}from"./configure-peer-js-BOV0tR6G.js";import{i as x}from"./rooms-ChCEOvkw.js";import"./shadow-claw-page-header-DR4OZFt2.js";import{a as S,o as C}from"./shadow-claw-Br8mWDUx.js";var w=/* @__PURE__ */ t(((e,t)=>{t.exports=function(){return typeof Promise==`function`&&Promise.prototype&&Promise.prototype.then}})),T=/* @__PURE__ */ t((e=>{let t,n=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];e.getSymbolSize=function(e){if(!e)throw Error(`"version" cannot be null or undefined`);if(e<1||e>40)throw Error(`"version" should be in range from 1 to 40`);return e*4+17},e.getSymbolTotalCodewords=function(e){return n[e]},e.getBCHDigit=function(e){let t=0;for(;e!==0;)t++,e>>>=1;return t},e.setToSJISFunction=function(e){if(typeof e!=`function`)throw Error(`"toSJISFunc" is not a valid function.`);t=e},e.isKanjiModeEnabled=function(){return t!==void 0},e.toSJIS=function(e){return t(e)}})),E=/* @__PURE__ */ t((e=>{e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2};function t(t){if(typeof t!=`string`)throw Error(`Param is not a string`);switch(t.toLowerCase()){case`l`:case`low`:return e.L;case`m`:case`medium`:return e.M;case`q`:case`quartile`:return e.Q;case`h`:case`high`:return e.H;default:throw Error(`Unknown EC Level: `+t)}}e.isValid=function(e){return e&&e.bit!==void 0&&e.bit>=0&&e.bit<4},e.from=function(n,r){if(e.isValid(n))return n;try{return t(n)}catch{return r}}})),D=/* @__PURE__ */ t(((e,t)=>{function n(){this.buffer=[],this.length=0}n.prototype={get:function(e){let t=Math.floor(e/8);return(this.buffer[t]>>>7-e%8&1)==1},put:function(e,t){for(let n=0;n<t;n++)this.putBit((e>>>t-n-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(e){let t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),e&&(this.buffer[t]|=128>>>this.length%8),this.length++}},t.exports=n})),ee=/* @__PURE__ */ t(((e,t)=>{function n(e){if(!e||e<1)throw Error(`BitMatrix size must be defined and greater than 0`);this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}n.prototype.set=function(e,t,n,r){let i=e*this.size+t;this.data[i]=n,r&&(this.reservedBit[i]=!0)},n.prototype.get=function(e,t){return this.data[e*this.size+t]},n.prototype.xor=function(e,t,n){this.data[e*this.size+t]^=n},n.prototype.isReserved=function(e,t){return this.reservedBit[e*this.size+t]},t.exports=n})),te=/* @__PURE__ */ t((e=>{let t=T().getSymbolSize;e.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=t(e),i=r===145?26:Math.ceil((r-13)/(2*n-2))*2,a=[r-7];for(let e=1;e<n-1;e++)a[e]=a[e-1]-i;return a.push(6),a.reverse()},e.getPositions=function(t){let n=[],r=e.getRowColCoords(t),i=r.length;for(let e=0;e<i;e++)for(let t=0;t<i;t++)e===0&&t===0||e===0&&t===i-1||e===i-1&&t===0||n.push([r[e],r[t]]);return n}})),ne=/* @__PURE__ */ t((e=>{let t=T().getSymbolSize;e.getPositions=function(e){let n=t(e);return[[0,0],[n-7,0],[0,n-7]]}})),O=/* @__PURE__ */ t((e=>{e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};let t={N1:3,N2:3,N3:40,N4:10};e.isValid=function(e){return e!=null&&e!==``&&!isNaN(e)&&e>=0&&e<=7},e.from=function(t){return e.isValid(t)?parseInt(t,10):void 0},e.getPenaltyN1=function(e){let n=e.size,r=0,i=0,a=0,o=null,s=null;for(let c=0;c<n;c++){i=a=0,o=s=null;for(let l=0;l<n;l++){let n=e.get(c,l);n===o?i++:(i>=5&&(r+=t.N1+(i-5)),o=n,i=1),n=e.get(l,c),n===s?a++:(a>=5&&(r+=t.N1+(a-5)),s=n,a=1)}i>=5&&(r+=t.N1+(i-5)),a>=5&&(r+=t.N1+(a-5))}return r},e.getPenaltyN2=function(e){let n=e.size,r=0;for(let t=0;t<n-1;t++)for(let i=0;i<n-1;i++){let n=e.get(t,i)+e.get(t,i+1)+e.get(t+1,i)+e.get(t+1,i+1);(n===4||n===0)&&r++}return r*t.N2},e.getPenaltyN3=function(e){let n=e.size,r=0,i=0,a=0;for(let t=0;t<n;t++){i=a=0;for(let o=0;o<n;o++)i=i<<1&2047|e.get(t,o),o>=10&&(i===1488||i===93)&&r++,a=a<<1&2047|e.get(o,t),o>=10&&(a===1488||a===93)&&r++}return r*t.N3},e.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let t=0;t<r;t++)n+=e.data[t];return Math.abs(Math.ceil(n*100/r/5)-10)*t.N4};function n(t,n,r){switch(t){case e.Patterns.PATTERN000:return(n+r)%2==0;case e.Patterns.PATTERN001:return n%2==0;case e.Patterns.PATTERN010:return r%3==0;case e.Patterns.PATTERN011:return(n+r)%3==0;case e.Patterns.PATTERN100:return(Math.floor(n/2)+Math.floor(r/3))%2==0;case e.Patterns.PATTERN101:return n*r%2+n*r%3==0;case e.Patterns.PATTERN110:return(n*r%2+n*r%3)%2==0;case e.Patterns.PATTERN111:return(n*r%3+(n+r)%2)%2==0;default:throw Error(`bad maskPattern:`+t)}}e.applyMask=function(e,t){let r=t.size;for(let i=0;i<r;i++)for(let a=0;a<r;a++)t.isReserved(a,i)||t.xor(a,i,n(e,a,i))},e.getBestMask=function(t,n){let r=Object.keys(e.Patterns).length,i=0,a=1/0;for(let o=0;o<r;o++){n(o),e.applyMask(o,t);let r=e.getPenaltyN1(t)+e.getPenaltyN2(t)+e.getPenaltyN3(t)+e.getPenaltyN4(t);e.applyMask(o,t),r<a&&(a=r,i=o)}return i}})),k=/* @__PURE__ */ t((e=>{let t=E(),n=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],r=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];e.getBlocksCount=function(e,r){switch(r){case t.L:return n[(e-1)*4+0];case t.M:return n[(e-1)*4+1];case t.Q:return n[(e-1)*4+2];case t.H:return n[(e-1)*4+3];default:return}},e.getTotalCodewordsCount=function(e,n){switch(n){case t.L:return r[(e-1)*4+0];case t.M:return r[(e-1)*4+1];case t.Q:return r[(e-1)*4+2];case t.H:return r[(e-1)*4+3];default:return}}})),re=/* @__PURE__ */ t((e=>{let t=/* @__PURE__ */ new Uint8Array(512),n=/* @__PURE__ */ new Uint8Array(256);(function(){let e=1;for(let r=0;r<255;r++)t[r]=e,n[e]=r,e<<=1,e&256&&(e^=285);for(let e=255;e<512;e++)t[e]=t[e-255]})(),e.log=function(e){if(e<1)throw Error(`log(`+e+`)`);return n[e]},e.exp=function(e){return t[e]},e.mul=function(e,r){return e===0||r===0?0:t[n[e]+n[r]]}})),A=/* @__PURE__ */ t((e=>{let t=re();e.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let i=0;i<e.length;i++)for(let a=0;a<n.length;a++)r[i+a]^=t.mul(e[i],n[a]);return r},e.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let e=r[0];for(let i=0;i<n.length;i++)r[i]^=t.mul(n[i],e);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r},e.generateECPolynomial=function(n){let r=new Uint8Array([1]);for(let i=0;i<n;i++)r=e.mul(r,new Uint8Array([1,t.exp(i)]));return r}})),ie=/* @__PURE__ */ t(((e,t)=>{let n=A();function r(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}r.prototype.initialize=function(e){this.degree=e,this.genPoly=n.generateECPolynomial(this.degree)},r.prototype.encode=function(e){if(!this.genPoly)throw Error(`Encoder not initialized`);let t=new Uint8Array(e.length+this.degree);t.set(e);let r=n.mod(t,this.genPoly),i=this.degree-r.length;if(i>0){let e=new Uint8Array(this.degree);return e.set(r,i),e}return r},t.exports=r})),j=/* @__PURE__ */ t((e=>{e.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}})),M=/* @__PURE__ */ t((e=>{let t=`(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+`;t=t.replace(/u/g,`\\u`);let n=`(?:(?![A-Z0-9 $%*+\\-./:]|`+t+`)(?:.|[\r
2
2
  ]))+`;e.KANJI=new RegExp(t,`g`),e.BYTE_KANJI=/* @__PURE__ */ RegExp(`[^A-Z0-9 $%*+\\-./:]+`,`g`),e.BYTE=new RegExp(n,`g`),e.NUMERIC=/* @__PURE__ */ RegExp(`[0-9]+`,`g`),e.ALPHANUMERIC=/* @__PURE__ */ RegExp(`[A-Z $%*+\\-./:]+`,`g`);let r=RegExp(`^`+t+`$`),i=/* @__PURE__ */ RegExp(`^[0-9]+$`),a=/* @__PURE__ */ RegExp(`^[A-Z0-9 $%*+\\-./:]+$`);e.testKanji=function(e){return r.test(e)},e.testNumeric=function(e){return i.test(e)},e.testAlphanumeric=function(e){return a.test(e)}})),N=/* @__PURE__ */ t((e=>{let t=j(),n=M();e.NUMERIC={id:`Numeric`,bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:`Alphanumeric`,bit:2,ccBits:[9,11,13]},e.BYTE={id:`Byte`,bit:4,ccBits:[8,16,16]},e.KANJI={id:`Kanji`,bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(e,n){if(!e.ccBits)throw Error(`Invalid mode: `+e);if(!t.isValid(n))throw Error(`Invalid version: `+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]},e.getBestModeForData=function(t){return n.testNumeric(t)?e.NUMERIC:n.testAlphanumeric(t)?e.ALPHANUMERIC:n.testKanji(t)?e.KANJI:e.BYTE},e.toString=function(e){if(e&&e.id)return e.id;throw Error(`Invalid mode`)},e.isValid=function(e){return e&&e.bit&&e.ccBits};function r(t){if(typeof t!=`string`)throw Error(`Param is not a string`);switch(t.toLowerCase()){case`numeric`:return e.NUMERIC;case`alphanumeric`:return e.ALPHANUMERIC;case`kanji`:return e.KANJI;case`byte`:return e.BYTE;default:throw Error(`Unknown mode: `+t)}}e.from=function(t,n){if(e.isValid(t))return t;try{return r(t)}catch{return n}}})),ae=/* @__PURE__ */ t((e=>{let t=T(),n=k(),r=E(),i=N(),a=j(),o=7973,s=t.getBCHDigit(o);function c(t,n,r){for(let i=1;i<=40;i++)if(n<=e.getCapacity(i,r,t))return i}function l(e,t){return i.getCharCountIndicator(e,t)+4}function u(e,t){let n=0;return e.forEach(function(e){let r=l(e.mode,t);n+=r+e.getBitsLength()}),n}function d(t,n){for(let r=1;r<=40;r++)if(u(t,r)<=e.getCapacity(r,n,i.MIXED))return r}e.from=function(e,t){return a.isValid(e)?parseInt(e,10):t},e.getCapacity=function(e,r,o){if(!a.isValid(e))throw Error(`Invalid QR Code version`);o===void 0&&(o=i.BYTE);let s=(t.getSymbolTotalCodewords(e)-n.getTotalCodewordsCount(e,r))*8;if(o===i.MIXED)return s;let c=s-l(o,e);switch(o){case i.NUMERIC:return Math.floor(c/10*3);case i.ALPHANUMERIC:return Math.floor(c/11*2);case i.KANJI:return Math.floor(c/13);case i.BYTE:default:return Math.floor(c/8)}},e.getBestVersionForData=function(e,t){let n,i=r.from(t,r.M);if(Array.isArray(e)){if(e.length>1)return d(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return c(n.mode,n.getLength(),i)},e.getEncodedBits=function(e){if(!a.isValid(e)||e<7)throw Error(`Invalid QR Code version`);let n=e<<12;for(;t.getBCHDigit(n)-s>=0;)n^=o<<t.getBCHDigit(n)-s;return e<<12|n}})),oe=/* @__PURE__ */ t((e=>{let t=T(),n=1335,r=t.getBCHDigit(n);e.getEncodedBits=function(e,i){let a=e.bit<<3|i,o=a<<10;for(;t.getBCHDigit(o)-r>=0;)o^=n<<t.getBCHDigit(o)-r;return(a<<10|o)^21522}})),se=/* @__PURE__ */ t(((e,t)=>{let n=N();function r(e){this.mode=n.NUMERIC,this.data=e.toString()}r.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(e){let t,n,r;for(t=0;t+3<=this.data.length;t+=3)n=this.data.substr(t,3),r=parseInt(n,10),e.put(r,10);let i=this.data.length-t;i>0&&(n=this.data.substr(t),r=parseInt(n,10),e.put(r,i*3+1))},t.exports=r})),ce=/* @__PURE__ */ t(((e,t)=>{let n=N(),r=/* @__PURE__ */ `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`.split(``);function i(e){this.mode=n.ALPHANUMERIC,this.data=e}i.getBitsLength=function(e){return 11*Math.floor(e/2)+e%2*6},i.prototype.getLength=function(){return this.data.length},i.prototype.getBitsLength=function(){return i.getBitsLength(this.data.length)},i.prototype.write=function(e){let t=0;for(;t+2<=this.data.length;t+=2){let n=r.indexOf(this.data[t])*45;n+=r.indexOf(this.data[t+1]),e.put(n,11)}this.data.length%2&&e.put(r.indexOf(this.data[t]),6)},t.exports=i})),le=/* @__PURE__ */ t(((e,t)=>{let n=N();function r(e){this.mode=n.BYTE,this.data=typeof e==`string`?new TextEncoder().encode(e):new Uint8Array(e)}r.getBitsLength=function(e){return e*8},r.prototype.getLength=function(){return this.data.length},r.prototype.getBitsLength=function(){return r.getBitsLength(this.data.length)},r.prototype.write=function(e){for(let t=0,n=this.data.length;t<n;t++)e.put(this.data[t],8)},t.exports=r})),ue=/* @__PURE__ */ t(((e,t)=>{let n=N(),r=T();function i(e){this.mode=n.KANJI,this.data=e}i.getBitsLength=function(e){return e*13},i.prototype.getLength=function(){return this.data.length},i.prototype.getBitsLength=function(){return i.getBitsLength(this.data.length)},i.prototype.write=function(e){let t=0;for(;t<this.data.length;t++){let n=r.toSJIS(this.data[t]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw Error(`Invalid SJIS character: `+this.data[t]+`
3
3
  Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),e.put(n,13)}},t.exports=i})),de=/* @__PURE__ */ t(((e,t)=>{var n={single_source_shortest_paths:function(e,t,r){var i={},a={};a[t]=0;var o=n.PriorityQueue.make();o.push(t,0);for(var s,c,l,u,d,f,p,m,h;!o.empty();)for(l in s=o.pop(),c=s.value,u=s.cost,d=e[c]||{},d)d.hasOwnProperty(l)&&(f=d[l],p=u+f,m=a[l],h=a[l]===void 0,(h||m>p)&&(a[l]=p,o.push(l,p),i[l]=c));if(r!==void 0&&a[r]===void 0){var g=[`Could not find a path from `,t,` to `,r,`.`].join(``);throw Error(g)}return i},extract_shortest_path_from_predecessor_list:function(e,t){for(var n=[],r=t;r;)n.push(r),e[r],r=e[r];return n.reverse(),n},find_path:function(e,t,r){var i=n.single_source_shortest_paths(e,t,r);return n.extract_shortest_path_from_predecessor_list(i,r)},PriorityQueue:{make:function(e){var t=n.PriorityQueue,r={},i;for(i in e||={},t)t.hasOwnProperty(i)&&(r[i]=t[i]);return r.queue=[],r.sorter=e.sorter||t.default_sorter,r},default_sorter:function(e,t){return e.cost-t.cost},push:function(e,t){var n={value:e,cost:t};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t!==void 0&&(t.exports=n)})),fe=/* @__PURE__ */ t((e=>{let t=N(),n=se(),r=ce(),i=le(),a=ue(),o=M(),s=T(),c=de();function l(e){return unescape(encodeURIComponent(e)).length}function u(e,t,n){let r=[],i;for(;(i=e.exec(n))!==null;)r.push({data:i[0],index:i.index,mode:t,length:i[0].length});return r}function d(e){let n=u(o.NUMERIC,t.NUMERIC,e),r=u(o.ALPHANUMERIC,t.ALPHANUMERIC,e),i,a;return s.isKanjiModeEnabled()?(i=u(o.BYTE,t.BYTE,e),a=u(o.KANJI,t.KANJI,e)):(i=u(o.BYTE_KANJI,t.BYTE,e),a=[]),n.concat(r,i,a).sort(function(e,t){return e.index-t.index}).map(function(e){return{data:e.data,mode:e.mode,length:e.length}})}function f(e,o){switch(o){case t.NUMERIC:return n.getBitsLength(e);case t.ALPHANUMERIC:return r.getBitsLength(e);case t.KANJI:return a.getBitsLength(e);case t.BYTE:return i.getBitsLength(e)}}function p(e){return e.reduce(function(e,t){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===t.mode?(e[e.length-1].data+=t.data,e):(e.push(t),e)},[])}function m(e){let n=[];for(let r=0;r<e.length;r++){let i=e[r];switch(i.mode){case t.NUMERIC:n.push([i,{data:i.data,mode:t.ALPHANUMERIC,length:i.length},{data:i.data,mode:t.BYTE,length:i.length}]);break;case t.ALPHANUMERIC:n.push([i,{data:i.data,mode:t.BYTE,length:i.length}]);break;case t.KANJI:n.push([i,{data:i.data,mode:t.BYTE,length:l(i.data)}]);break;case t.BYTE:n.push([{data:i.data,mode:t.BYTE,length:l(i.data)}])}}return n}function h(e,n){let r={},i={start:{}},a=[`start`];for(let o=0;o<e.length;o++){let s=e[o],c=[];for(let e=0;e<s.length;e++){let l=s[e],u=``+o+e;c.push(u),r[u]={node:l,lastCount:0},i[u]={};for(let e=0;e<a.length;e++){let o=a[e];r[o]&&r[o].node.mode===l.mode?(i[o][u]=f(r[o].lastCount+l.length,l.mode)-f(r[o].lastCount,l.mode),r[o].lastCount+=l.length):(r[o]&&(r[o].lastCount=l.length),i[o][u]=f(l.length,l.mode)+4+t.getCharCountIndicator(l.mode,n))}}a=c}for(let e=0;e<a.length;e++)i[a[e]].end=0;return{map:i,table:r}}function g(e,o){let c,l=t.getBestModeForData(e);if(c=t.from(o,l),c!==t.BYTE&&c.bit<l.bit)throw Error(`"`+e+`" cannot be encoded with mode `+t.toString(c)+`.
4
4
  Suggested mode is: `+t.toString(l));switch(c===t.KANJI&&!s.isKanjiModeEnabled()&&(c=t.BYTE),c){case t.NUMERIC:return new n(e);case t.ALPHANUMERIC:return new r(e);case t.KANJI:return new a(e);case t.BYTE:return new i(e)}}e.fromArray=function(e){return e.reduce(function(e,t){return typeof t==`string`?e.push(g(t,null)):t.data&&e.push(g(t.data,t.mode)),e},[])},e.fromString=function(t,n){let r=h(m(d(t,s.isKanjiModeEnabled())),n),i=c.find_path(r.map,`start`,`end`),a=[];for(let e=1;e<i.length-1;e++)a.push(r.table[i[e]].node);return e.fromArray(p(a))},e.rawSplit=function(t){return e.fromArray(d(t,s.isKanjiModeEnabled()))}})),pe=/* @__PURE__ */ t((e=>{let t=T(),n=E(),r=D(),i=ee(),a=te(),o=ne(),s=O(),c=k(),l=ie(),u=ae(),d=oe(),f=N(),p=fe();function m(e,t){let n=e.size,r=o.getPositions(t);for(let t=0;t<r.length;t++){let i=r[t][0],a=r[t][1];for(let t=-1;t<=7;t++)if(!(i+t<=-1||n<=i+t))for(let r=-1;r<=7;r++)a+r<=-1||n<=a+r||(t>=0&&t<=6&&(r===0||r===6)||r>=0&&r<=6&&(t===0||t===6)||t>=2&&t<=4&&r>=2&&r<=4?e.set(i+t,a+r,!0,!0):e.set(i+t,a+r,!1,!0))}}function h(e){let t=e.size;for(let n=8;n<t-8;n++){let t=n%2==0;e.set(n,6,t,!0),e.set(6,n,t,!0)}}function g(e,t){let n=a.getPositions(t);for(let t=0;t<n.length;t++){let r=n[t][0],i=n[t][1];for(let t=-2;t<=2;t++)for(let n=-2;n<=2;n++)t===-2||t===2||n===-2||n===2||t===0&&n===0?e.set(r+t,i+n,!0,!0):e.set(r+t,i+n,!1,!0)}}function _(e,t){let n=e.size,r=u.getEncodedBits(t),i,a,o;for(let t=0;t<18;t++)i=Math.floor(t/3),a=t%3+n-8-3,o=(r>>t&1)==1,e.set(i,a,o,!0),e.set(a,i,o,!0)}function v(e,t,n){let r=e.size,i=d.getEncodedBits(t,n),a,o;for(a=0;a<15;a++)o=(i>>a&1)==1,a<6?e.set(a,8,o,!0):a<8?e.set(a+1,8,o,!0):e.set(r-15+a,8,o,!0),a<8?e.set(8,r-a-1,o,!0):a<9?e.set(8,15-a-1+1,o,!0):e.set(8,15-a-1,o,!0);e.set(r-8,8,1,!0)}function y(e,t){let n=e.size,r=-1,i=n-1,a=7,o=0;for(let s=n-1;s>0;s-=2)for(s===6&&s--;;){for(let n=0;n<2;n++)if(!e.isReserved(i,s-n)){let r=!1;o<t.length&&(r=(t[o]>>>a&1)==1),e.set(i,s-n,r),a--,a===-1&&(o++,a=7)}if(i+=r,i<0||n<=i){i-=r,r=-r;break}}}function b(e,n,i){let a=new r;i.forEach(function(t){a.put(t.mode.bit,4),a.put(t.getLength(),f.getCharCountIndicator(t.mode,e)),t.write(a)});let o=(t.getSymbolTotalCodewords(e)-c.getTotalCodewordsCount(e,n))*8;for(a.getLengthInBits()+4<=o&&a.put(0,4);a.getLengthInBits()%8!=0;)a.putBit(0);let s=(o-a.getLengthInBits())/8;for(let e=0;e<s;e++)a.put(e%2?17:236,8);return x(a,e,n)}function x(e,n,r){let i=t.getSymbolTotalCodewords(n),a=i-c.getTotalCodewordsCount(n,r),o=c.getBlocksCount(n,r),s=o-i%o,u=Math.floor(i/o),d=Math.floor(a/o),f=d+1,p=u-d,m=new l(p),h=0,g=Array(o),_=Array(o),v=0,y=new Uint8Array(e.buffer);for(let e=0;e<o;e++){let t=e<s?d:f;g[e]=y.slice(h,h+t),_[e]=m.encode(g[e]),h+=t,v=Math.max(v,t)}let b=new Uint8Array(i),x=0,S,C;for(S=0;S<v;S++)for(C=0;C<o;C++)S<g[C].length&&(b[x++]=g[C][S]);for(S=0;S<p;S++)for(C=0;C<o;C++)b[x++]=_[C][S];return b}function S(e,n,r,a){let o;if(Array.isArray(e))o=p.fromArray(e);else if(typeof e==`string`){let t=n;if(!t){let n=p.rawSplit(e);t=u.getBestVersionForData(n,r)}o=p.fromString(e,t||40)}else throw Error(`Invalid data`);let c=u.getBestVersionForData(o,r);if(!c)throw Error(`The amount of data is too big to be stored in a QR Code`);if(!n)n=c;else if(n<c)throw Error(`
@@ -1,4 +1,4 @@
1
- import{i as e,r as t,t as n}from"./rolldown-runtime-DBVvNlSN.js";import{_ as r,p as i}from"./custom-element-security-kiDhPfb8.js";import{t as a}from"./browser-B1SoUj6D.js";import{C as o,r as s}from"./config-C-YdSFZB.js";import{i as c}from"./app-routes-V_-URXc5.js";import{n as l}from"./db-BUuJo1Gf.js";import{n as u,t as d}from"./tx-promise-DNVEN3Wa.js";import{t as f}from"./get-config-Bkvl__ZS.js";import{t as p}from"./html-BwtE_7wp.js";import{t as m}from"./dist-CeFyqf9k.js";import{C as h,f as g,k as _,t as v}from"./orchestrator-CaUpEVkQ.js";import{t as y}from"./set-config-DSiuMe0k.js";import{a as b,i as x,r as S,s as C}from"./toast-CtIuHprH.js";import{t as w}from"./parse-boolean-config-BigJ9U46.js";import{t as T}from"./buffer-B98mcmH0.js";import{n as E}from"./e2e-bridge-C0g8vZKr.js";import{a as D}from"./transformers-C-DuTM2K.js";import{i as O}from"./model-ranking-CK0iBo3Z.js";import"./shadow-claw-page-header-action-button-2DH5O1TD.js";import"./shadow-claw-page-header-CjJpVkyL.js";import{i as k}from"./mime-ClqNyXPc.js";import{n as A,r as j,t as M}from"./attachment-capabilities-B6ibLwQB.js";import{renderMarkdown as N}from"./markdown-CPbU4r1U.js";import{a as P,n as F}from"./peerjs-CgF4Iz5W.js";import{t as I}from"./download-group-file-BapoRgfU.js";import{n as L,t as R}from"./date-B1vUpTS_.js";import"./shadow-claw-dialog-BVGf_c3S.js";import{a as z,n as B,o as V}from"./shadow-claw-DdgeYPg5.js"
1
+ import{i as e,r as t,t as n}from"./rolldown-runtime-DBVvNlSN.js";import{_ as r,p as i}from"./custom-element-security-B2daIE5r.js";import{t as a}from"./browser-B1SoUj6D.js";import{C as o,V as s,r as c}from"./config-C16fFWtP.js";import{n as l}from"./db-BUuJo1Gf.js";import{n as u,t as d}from"./tx-promise-DNVEN3Wa.js";import{t as f}from"./get-config-Bkvl__ZS.js";import{t as p}from"./html-BwtE_7wp.js";import{t as m}from"./dist-CeFyqf9k.js";import{C as h,f as g,k as _,t as v}from"./orchestrator-DBO4NZqd.js";import{t as y}from"./set-config-DSiuMe0k.js";import{a as b,i as x,r as S,s as C}from"./toast-CtIuHprH.js";import{t as w}from"./parse-boolean-config-BigJ9U46.js";import{t as T}from"./buffer-B98mcmH0.js";import{n as E}from"./e2e-bridge-Cz95DLlb.js";import{a as D}from"./transformers-CQ9ss9rD.js";import{i as O}from"./model-ranking-BgOSaNIy.js";import"./shadow-claw-page-header-action-button-BnCV_2Kb.js";import"./shadow-claw-page-header-DR4OZFt2.js";import{i as k}from"./mime-ClqNyXPc.js";import{n as A,r as j,t as M}from"./attachment-capabilities-AdwXt3--.js";import{renderMarkdown as N}from"./markdown-CDSb5Hrl.js";import{a as P,n as F}from"./peerjs-l0jiBoh6.js";import{t as I}from"./download-group-file-BkMH-JKi.js";import{n as L,t as R}from"./date-B1vUpTS_.js";import"./shadow-claw-dialog-BVGf_c3S.js";import{a as z,n as B,o as V}from"./shadow-claw-Br8mWDUx.js"
2
2
  /*!
3
3
 
4
4
  JSZip v3.10.2 - A JavaScript class for generating and reading zip files
@@ -2419,10 +2419,10 @@ dialog.chat__prompt-api-dialog::backdrop {
2419
2419
  <input class="chat__attachment-input" type="file" multiple />
2420
2420
  </section>
2421
2421
  </template>
2422
- `,`text/html`),Re=Le.querySelector(`template`);let ze=[];ze=Re?Array.from(Re.content.children):Array.from(Le.head.children).concat(Array.from(Le.body.children));var Be=ze;const Ve=131072,He=8e4;async function Ue(e,t){if(!e||typeof e.transaction!=`function`)return!0;try{return w(await f(e,t),!0)}catch{return!0}}const We=`shadow-claw-chat`;var Ge=class extends V{static styles=Ie;static template=Be;activityLogCollapsedOverride=null;activityLogVisibilityMediaQuery=null;db=null;#e;#t;#n;#r;#i;#a;#o;constructor(){super(),q.reset(),this.db=null,this.#n=0,this.#i=0,this.#a=!1,this.#o=0,this.#r=!0,this.#e=0,this.#t=[]}async connectedCallback(){if(!this.shadowRoot)throw Error(`shadowRoot not found`);this.db=await l(),await this.restoreInputAreaHeight(),this.dispatchTerminalSlotReady(),this.setupEffects(),this.setupActivityLogVisibility(),this.bindEventListeners(),await this.checkPromptApiOnboarding()}disconnectedCallback(){this.activityLogVisibilityCleanup(),q.revokeAttachmentObjectUrls(),q.resetNearBottom(),super.disconnectedCallback()}activityLogVisibilityCleanup=()=>{};applyActivityLogVisibility(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.chat__activity-log`);if(!(t instanceof HTMLElement))return;let n=this.activityLogVisibilityMediaQuery?!this.activityLogVisibilityMediaQuery.matches:!1;(typeof this.activityLogCollapsedOverride==`boolean`?this.activityLogCollapsedOverride:n)?t.classList.add(`chat__activity-log--collapsed`):t.classList.remove(`chat__activity-log--collapsed`)}bindEventListeners(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.chat__messages`);if(t instanceof HTMLElement){t.addEventListener(`scroll`,()=>{this.#a||(this.#o+=1,this.isContainerNearBottom(t)||(this.#r=!1)),q.setNearBottom(this.isContainerNearBottom(t)),this.persistGroupScrollState(t)}),t.addEventListener(`click`,e=>{this.handleMessageLinkClick(e)}),t.addEventListener(`shadow-claw-a2ui-action`,async e=>{let{groupId:t,action:n}=e.detail;if(t.startsWith(`room:`)){await v.orchestrator?.routeRoomA2UIAction(t,n);return}if(t.startsWith(`peer:`)){let e=(v.orchestrator?.router)?.findChannel(t);e&&`sendA2UIAction`in e&&await e.sendA2UIAction(t,n)}let r=JSON.stringify(n.dataModel,null,2),i=`[A2UI ACTION]\nsurfaceId: "${n.surfaceId}"\nactionId: "${n.actionId}"\ndataModel:\n${r}\n\nInstructions: The user triggered the "${n.actionId}" action on surface "${n.surfaceId}". The dataModel above contains the current form values. Use the appropriate tool(s) to fulfill the action based on the actionId and dataModel values. After you have a result, call render_component with action "updateDataModel" on surfaceId "${n.surfaceId}" to update the surface (e.g. patch the output field with the result). Do NOT respond with plain text only — always update the surface via render_component.`;v.sendMessage(i,[],n)}),t.addEventListener(`shadow-claw-a2ui-function-response`,async e=>{let{groupId:t,response:n}=e.detail;if(!t.startsWith(`room:`)&&t.startsWith(`peer:`)){let e=(v.orchestrator?.router)?.findChannel(t);e&&`sendA2UIAction`in e&&await e.sendA2UIAction(t,n)}});let e=new ResizeObserver(()=>{this.shouldAutoFollow(t)&&(this.setMessagesScrollTop(t,t.scrollHeight),this.persistGroupScrollState(t))});e.observe(t),this.addCleanup(()=>e.disconnect())}let n=e.querySelector(`.chat__input`);n instanceof HTMLTextAreaElement&&n.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.sendMessage()),e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.sendMessage())});let r=e.querySelector(`.chat__input-area`),i=e.querySelector(`.chat__input-resize-handle`);r instanceof HTMLElement&&i instanceof HTMLElement&&this.bindInputResizeEvents(r,i),e.querySelector(`[data-action="send-message"]`)?.addEventListener(`click`,()=>this.sendMessage()),e.querySelector(`[data-action="attach-files"]`)?.addEventListener(`click`,()=>{let t=e.querySelector(`.chat__attachment-input`);t instanceof HTMLInputElement&&(t.value=``,t.click())}),e.querySelector(`.chat__attachment-input`)?.addEventListener(`change`,e=>{e.target instanceof HTMLInputElement&&this.queueSelectedFiles(e.target)}),e.querySelector(`[data-action="compact-chat"]`)?.addEventListener(`click`,()=>this.handleCompactChat()),e.querySelector(`[data-action="clear-chat"]`)?.addEventListener(`click`,()=>this.handleClearChat()),e.querySelector(`[data-action="stop-chat"]`)?.addEventListener(`click`,()=>this.handleStopChat()),e.querySelector(`[data-action="download-chat"]`)?.addEventListener(`click`,()=>this.downloadChat()),e.querySelector(`[data-action="restore-chat"]`)?.addEventListener(`click`,()=>{let t=e.querySelector(`.chat__restore-input`);t instanceof HTMLInputElement&&t.click()}),e.querySelector(`.chat__restore-input`)?.addEventListener(`change`,e=>{e.target instanceof HTMLInputElement&&this.restoreChat(e.target)});let a=e.querySelector(`.chat__body`);a instanceof HTMLElement&&(a.addEventListener(`dragenter`,e=>{this.hasDroppableData(e.dataTransfer)&&(e.preventDefault(),this.#e+=1,this.setDropOverlayVisible(!0))}),a.addEventListener(`dragover`,e=>{this.hasDroppableData(e.dataTransfer)&&e.preventDefault()}),a.addEventListener(`dragleave`,e=>{this.hasDroppableData(e.dataTransfer)&&(e.preventDefault(),this.#e=Math.max(0,this.#e-1),this.#e===0&&this.setDropOverlayVisible(!1))}),a.addEventListener(`drop`,e=>{this.hasDroppableData(e.dataTransfer)&&(e.preventDefault(),this.#e=0,this.setDropOverlayVisible(!1),this.queueDroppedData(e.dataTransfer))}));let o=e.querySelector(`.chat__prompt-api-form`);o instanceof HTMLFormElement&&o.addEventListener(`submit`,e=>{e.preventDefault(),this.confirmPromptApiOnboarding()});let s=e.querySelector(`[data-action="confirm-prompt-api-onboarding"]`);s instanceof HTMLElement&&s.addEventListener(`click`,e=>{e.preventDefault(),this.confirmPromptApiOnboarding()});let c=e.querySelector(`[data-action="configure-other-provider"]`);c instanceof HTMLElement&&c.addEventListener(`click`,e=>{e.preventDefault(),this.bypassPromptApiOnboardingToSettings()})}bindInputResizeEvents(e,t){t.setAttribute(`tabindex`,`0`),t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`horizontal`),t.setAttribute(`aria-label`,`Resize chat input area`);let n=()=>{let t=parseFloat(e.style.getPropertyValue(`--chat-input-area-height`));return Number.isFinite(t)&&t>0?t:40},r=()=>{let e=this.clampInputAreaHeight(2**53-1),r=Math.round(this.clampInputAreaHeight(n()));t.setAttribute(`aria-valuemin`,`40`),t.setAttribute(`aria-valuemax`,String(Math.round(e))),t.setAttribute(`aria-valuenow`,String(r))},i=null,a=0,o=0,s=t=>{if(t.pointerId!==i)return;let n=a-t.clientY,s=o+n;this.setInputAreaHeight(e,s),r()},c=()=>{if(i===null)return;i=null,t.classList.remove(`active`),document.removeEventListener(`pointermove`,s);let n=parseFloat(e.style.getPropertyValue(`--chat-input-area-height`));Number.isFinite(n)&&n>0?this.persistInputAreaHeight(n):this.persistInputAreaHeight(0)},l=e=>{e.pointerId===i&&c()};t.addEventListener(`pointerdown`,n=>{if(n.pointerType===`mouse`&&n.button!==0&&n.button!==-1)return;let r=e.querySelector(`.chat__input-wrapper`);if(!(r instanceof HTMLElement))return;n.preventDefault(),i=n.pointerId,a=n.clientY,e.classList.add(`chat__input-area--resized`);let c=parseFloat(e.style.getPropertyValue(`--chat-input-area-height`));o=Number.isFinite(c)&&c>0?c:r.getBoundingClientRect().height||40,t.classList.add(`active`),t.setPointerCapture(n.pointerId),document.addEventListener(`pointermove`,s)}),t.addEventListener(`pointerup`,l),t.addEventListener(`pointercancel`,c),t.addEventListener(`dblclick`,()=>{this.resetInputAreaHeight(e),this.persistInputAreaHeight(0),r(),this.scrollMessagesToBottomIfNeeded()}),t.addEventListener(`keydown`,t=>{let i=t.shiftKey?32:12,a=n(),o=null;if(t.key===`ArrowUp`?o=a+i:t.key===`ArrowDown`?o=a-i:t.key===`Home`?o=40:t.key===`End`&&(o=this.clampInputAreaHeight(2**53-1)),o===null)return;t.preventDefault(),this.setInputAreaHeight(e,o),r();let s=parseFloat(e.style.getPropertyValue(`--chat-input-area-height`));this.persistInputAreaHeight(Number.isFinite(s)&&s>0?this.clampInputAreaHeight(s):0),this.scrollMessagesToBottomIfNeeded()}),r(),this.addCleanup(()=>{c(),t.removeEventListener(`pointerup`,l),t.removeEventListener(`pointercancel`,c)})}buildQueuedAttachmentsFromFiles(e){return e.map(e=>{let t=e.name||`attachment.bin`;return{id:`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,fileName:t,mimeType:k(t,e.type||``),size:e.size,source:{kind:`local-file`,file:e}}})}clampInputAreaHeight(e){let t=Math.floor(window.innerHeight*.45);return Math.max(40,Math.min(Math.max(40,t),e))}deferWorkspaceImageLoads(e){let t=document.createElement(`div`);t.innerHTML=e;let n=Array.from(t.querySelectorAll(`img[src]`));for(let e of n){let t=e.getAttribute(`src`);if(!t)continue;let n=this.resolveWorkspaceLinkPath(t);n&&(e.setAttribute(`data-inline-workspace-src`,n),e.removeAttribute(`src`))}return t.innerHTML}dispatchTerminalSlotReady(){this.dispatchEvent(new CustomEvent(`shadow-claw-terminal-slot-ready`,{bubbles:!0,composed:!0}))}formatAttachmentSize(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}formatAttachmentSubtitle(e){let t=[];return e.mimeType&&t.push(e.mimeType),typeof e.size==`number`&&t.push(this.formatAttachmentSize(e.size)),t.join(` · `)||`Attachment`}formatTokenCount(e){return typeof e==`number`?e.toLocaleString(`en-US`):`–`}getAttachmentIcon(e=``){let t=e.toLowerCase();return t.startsWith(`image/`)?`IMG`:t.startsWith(`video/`)?`VID`:t.startsWith(`audio/`)?`AUD`:t.includes(`pdf`)?`PDF`:t.startsWith(`text/`)||t.includes(`json`)?`TXT`:t.includes(`zip`)||t.includes(`tar`)?`ZIP`:`BIN`}getAttachmentTransportLabel(e,t,n){let r=A(e,t);return r===`text`?`text`:r===`image`&&(n.images||n.routerByFeatures)||r===`audio`&&(n.audio||n.routerByFeatures)||r===`document`&&(n.documents||n.routerByFeatures)?`native`:`fallback`}getContainerDistanceFromBottom(e){return Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight)}getMessagesContainer(){let e=this.shadowRoot?.querySelector(`.chat__messages`);return e instanceof HTMLElement?e:null}hasDroppableData(e){if(!e)return!1;if(e.files.length>0)return!0;let t=Array.from(e.types||[]);return t.includes(`Files`)||t.includes(`application/x-moz-file`)||t.includes(`text/plain`)}inferAttachmentModelSupport(e=[]){let t=v.orchestrator?.model?.toLowerCase()||``,n=j(t);return e.every(e=>{let t=(e.mimeType||``).toLowerCase();return this.isInlineTextMimeType(t)?!0:t.startsWith(`image/`)?n.images||n.routerByFeatures:t.startsWith(`audio/`)?n.audio||n.routerByFeatures:t.startsWith(`video/`)?n.video||n.routerByFeatures:!1})}injectCopyButtons(e){e.querySelectorAll(`pre`).forEach(e=>{if(e.querySelector(`.chat__code-copy-btn`))return;let t=document.createElement(`button`);t.className=`chat__code-copy-btn`,t.type=`button`,t.setAttribute(`aria-label`,`Copy code to clipboard`),t.textContent=`📋 Copy`,t.addEventListener(`click`,async()=>{let n=e.querySelector(`code`),r=n?n.textContent||``:e.textContent||``;try{await navigator.clipboard.writeText(r),t.textContent=`✅ Copied`,t.classList.add(`chat__code-copy-btn--copied`),setTimeout(()=>{t.textContent=`📋 Copy`,t.classList.remove(`chat__code-copy-btn--copied`)},1500)}catch{t.textContent=`⚠️ Failed`,setTimeout(()=>{t.textContent=`📋 Copy`},1500)}}),e.appendChild(t)})}injectMessageCopyButton(e,t){if(e.querySelector(`.chat__msg-copy-btn`))return;let n=e.querySelector(`.chat__message-content`);if(!n)return;let r=document.createElement(`button`);r.className=`chat__msg-copy-btn`,r.type=`button`,r.setAttribute(`aria-label`,`Copy message to clipboard`);let i=`http://www.w3.org/2000/svg`,a=document.createElementNS(i,`svg`);a.setAttribute(`fill`,`none`),a.setAttribute(`stroke-width`,`1.5`),a.setAttribute(`stroke`,`currentColor`),a.setAttribute(`viewBox`,`0 0 24 24`);let o=document.createElementNS(i,`path`);o.setAttribute(`d`,`M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75`),o.setAttribute(`stroke-linecap`,`round`),o.setAttribute(`stroke-linejoin`,`round`),a.append(o),r.append(a),r.addEventListener(`click`,async()=>{try{await navigator.clipboard.writeText(t),r.classList.add(`chat__msg-copy-btn--copied`),r.setAttribute(`aria-label`,`Copied!`),setTimeout(()=>{r.classList.remove(`chat__msg-copy-btn--copied`),r.setAttribute(`aria-label`,`Copy message to clipboard`)},1500)}catch{r.setAttribute(`aria-label`,`Copy failed`),setTimeout(()=>{r.setAttribute(`aria-label`,`Copy message to clipboard`)},1500)}}),n.appendChild(r)}injectMessageDeleteButton(e,t){if(e.querySelector(`.chat__msg-delete-btn`))return;let n=e.querySelector(`.chat__message-content`);if(!n)return;let r=document.createElement(`button`);r.className=`chat__msg-delete-btn`,r.type=`button`,r.setAttribute(`aria-label`,`Delete message`);let i=`http://www.w3.org/2000/svg`,a=document.createElementNS(i,`svg`);a.setAttribute(`fill`,`none`),a.setAttribute(`stroke-width`,`1.5`),a.setAttribute(`stroke`,`currentColor`),a.setAttribute(`viewBox`,`0 0 24 24`);let o=document.createElementNS(i,`path`);o.setAttribute(`d`,`M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0`),o.setAttribute(`stroke-linecap`,`round`),o.setAttribute(`stroke-linejoin`,`round`),a.append(o),r.append(a),r.addEventListener(`click`,async()=>{await this.showAttachmentDialog({mode:`confirm`,title:`Delete Message`,message:`Delete this message? This action cannot be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`})&&this.db&&await v.deleteMessage(this.db,t)}),n.appendChild(r)}isCollapsedInputAreaHeight(e){return e<=41}isContainerNearBottom(e){let{scrollTop:t,scrollHeight:n,clientHeight:r}=e;return n-t-r<80}isInlineTextMimeType(e){let t=e.toLowerCase();return t.startsWith(`text/`)?!0:t===`application/json`||t===`application/xml`||t===`application/javascript`}isLatestRender(e){return e===this.#n}persistGroupScrollState(e){let t=v.activeGroupId,n=this.isContainerNearBottom(e),r=n?0:this.getContainerDistanceFromBottom(e);q.setGroupScrollState(t,r,n)}removeStreamingBubble(e){e.querySelector(`.chat__message--streaming`)?.remove()}renderAttachmentCapabilitySummary(){let e=this.shadowRoot?.querySelector(`.chat__attachment-capabilities`);if(!(e instanceof HTMLElement))return;let t=v.orchestrator?.model||``;e.textContent=t?`Model attachment support: ${M(t)}`:``}renderQueuedAttachments(){let e=this.shadowRoot?.querySelector(`.chat__pending-attachments`);if(!(e instanceof HTMLElement))return;if(this.#t.length===0){e.hidden=!0,e.replaceChildren();return}let t=(v.orchestrator?.model||``).toLowerCase(),n=j(t);e.hidden=!1;let r=document.createDocumentFragment();for(let e of this.#t){let t=document.createElement(`div`);t.className=`chat__pending-attachment`;let i=document.createElement(`span`);i.className=`chat__attachment-icon`,i.setAttribute(`aria-hidden`,`true`),i.textContent=this.getAttachmentIcon(e.mimeType);let a=document.createElement(`div`);a.className=`chat__pending-attachment-meta`;let o=document.createElement(`span`);o.className=`chat__pending-attachment-name`,o.textContent=e.fileName;let s=document.createElement(`span`);s.className=`chat__pending-attachment-detail`,s.textContent=`${e.mimeType} · ${this.formatAttachmentSize(e.size)}`,a.append(o,s);let c=this.getAttachmentTransportLabel(e.mimeType,e.fileName,n),l=document.createElement(`span`);l.className=`chat__transport-badge chat__transport-badge--${c}`,l.setAttribute(`aria-label`,`Transport: ${c}`),l.textContent=c;let u=document.createElement(`button`);u.type=`button`,u.className=`chat__pending-attachment-remove`,u.setAttribute(`aria-label`,`Remove ${e.fileName}`),u.textContent=`x`,u.addEventListener(`click`,()=>{this.#t=this.#t.filter(t=>t.id!==e.id),this.renderQueuedAttachments()}),t.append(i,a,l,u),r.appendChild(t)}e.replaceChildren(r)}resetInputAreaHeight(e){e.classList.remove(`chat__input-area--resized`),e.style.removeProperty(`--chat-input-area-height`)}resolveWorkspaceLinkPath(e){let t=e.trim();if(!t||t.startsWith(`#`)||/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.split(/[?#]/,1)[0].replace(/\\/g,`/`);if(n=n.replace(/^\/+/,``),n=n.replace(/^\.\//,``),!n)return null;let r=n.split(`/`).filter(Boolean).map(e=>c(e));return r.some(e=>e===`..`)?null:r.join(`/`)}revokeAttachmentObjectUrls(){q.revokeAttachmentObjectUrls()}scheduleBottomSnap(e){let t=()=>{this.isLatestRender(e)&&this.scrollMessagesToBottomIfNeeded()};requestAnimationFrame(()=>{t(),requestAnimationFrame(t)}),setTimeout(t,120)}scrollMessagesToBottomIfNeeded(){let e=this.shadowRoot?.querySelector(`.chat__messages`);e instanceof HTMLElement&&q.isNearBottom&&(this.setMessagesScrollTop(e,e.scrollHeight),q.setNearBottom(this.isContainerNearBottom(e)),this.persistGroupScrollState(e))}setActivityLogCollapsedOverride(e){this.activityLogCollapsedOverride=e,this.applyActivityLogVisibility()}setDropOverlayVisible(e){let t=this.shadowRoot?.querySelector(`[data-drop-overlay]`);t instanceof HTMLElement&&(t.hidden=!e)}setInputAreaHeight(e,t){let n=this.clampInputAreaHeight(t);this.isCollapsedInputAreaHeight(n)?this.resetInputAreaHeight(e):(e.classList.add(`chat__input-area--resized`),e.style.setProperty(`--chat-input-area-height`,`${n}px`))}setMessagesScrollTop(e,t){this.#a=!0,e.scrollTop=t,requestAnimationFrame(()=>{this.#a=!1})}setupActivityLogVisibility(){if(this.shadowRoot){if(typeof globalThis.matchMedia==`function`){this.activityLogVisibilityMediaQuery=globalThis.matchMedia(`(min-width: 56rem) and (min-height: 401px)`);let e=()=>this.applyActivityLogVisibility();this.activityLogVisibilityMediaQuery.addEventListener(`change`,e),this.activityLogVisibilityCleanup=()=>{this.activityLogVisibilityMediaQuery?.removeEventListener(`change`,e)}}this.applyActivityLogVisibility()}}setupEffects(){let e=this.shadowRoot;e&&(this.addCleanup(z(()=>{let t=++this.#n,n=v.activeGroupId,r=v.messages,a=e.querySelector(`.chat__messages`);if(!(a instanceof HTMLElement))return;let o=q.getGroupScrollState(n);o?q.setNearBottom(o.nearBottom):q.setNearBottom(!0);let c=this.shouldAutoFollow(a),l=this.#o,u=c?0:o?.distanceFromBottom??this.getContainerDistanceFromBottom(a);this.revokeAttachmentObjectUrls(),a.replaceChildren(),(async()=>{let e=await Ue(this.db,s.MARKDOWN_FRONTMATTER_CHAT);for(let n of r){if(!this.isLatestRender(t))return!1;if(n.a2uiAction||n.content&&n.content.startsWith(`[A2UI ACTION]`))continue;let r=n.isFromMe?`assistant`:`user`,o=g(`assistantName`)||`ShadowClaw`,s=n.isFromMe?o:n.sender||`You`,l=document.createElement(`article`);l.className=`chat__message chat__message--${r}`;let u=n.timestamp?L(n.timestamp):``,d=await N(n.content,{breaks:!0,renderFrontmatter:e}),f=document.createElement(`div`);f.className=`chat__message-header`;let p=document.createElement(`div`);p.className=`chat__message-sender`,p.textContent=s;let m=document.createElement(`div`);m.className=`chat__message-timestamp`,m.textContent=u,f.append(p,m),l.append(f);let h=document.createElement(`div`);if(h.className=`chat__message-content`,n.content){let e=this.deferWorkspaceImageLoads(d);if(i(h,e),await this.resolveImagePaths(n.groupId,h),!this.isLatestRender(t))return!1}let _=await this.renderMessageAttachments(n);if(_&&h.appendChild(_),n.a2uiEnvelopes&&n.a2uiEnvelopes.length>0){let e=document.createElement(`shadow-claw-a2ui-interceptor`),t=document.createElement(`shadow-claw-a2ui`);t.groupId=n.groupId;for(let e of n.a2uiEnvelopes)t.applyEnvelope(e);e.appendChild(t),h.appendChild(e)}l.appendChild(h),a.appendChild(l),c&&(this.setMessagesScrollTop(a,a.scrollHeight),this.persistGroupScrollState(a)),n.content&&n.id&&(this.injectMessageCopyButton(l,n.content),this.injectMessageDeleteButton(l,n.id)),h instanceof HTMLElement&&n.content&&this.injectCopyButtons(h)}return!0})().then(async e=>{if(!e||!this.isLatestRender(t))return;let n=this.#o!==l;this.shouldAutoFollow(a)?(this.setMessagesScrollTop(a,a.scrollHeight),q.setNearBottom(this.isContainerNearBottom(a)),this.persistGroupScrollState(a),this.scheduleBottomSnap(t)):n?(q.setNearBottom(this.isContainerNearBottom(a)),this.persistGroupScrollState(a)):(this.setMessagesScrollTop(a,a.scrollHeight-a.clientHeight-u),q.setNearBottom(this.isContainerNearBottom(a)),this.persistGroupScrollState(a))})})),this.addCleanup(z(()=>{let e=v.streamingText;this.renderStreamingBubble(e)})),this.addCleanup(z(()=>{v.ready,v.state,this.renderAttachmentCapabilitySummary()})),this.addCleanup(z(()=>{let t=v.tokenUsageAccumulator,n=e.querySelector(`.chat__token-usage`);if(n instanceof HTMLElement){if(t&&(t.inputTokens||t.outputTokens)){n.classList.add(`chat__token-usage--visible`);let{cacheTokens:e,promptTokens:r,outputTokens:i,totalTokens:a}=ee(t),o=document.createElement(`span`);o.textContent=`⬆ ${this.formatTokenCount(r)} in`;let s=document.createElement(`span`);s.textContent=`⬇ ${this.formatTokenCount(i)} out`;let c=document.createElement(`span`);c.textContent=`Σ ${this.formatTokenCount(a)}`;let l=[o,s,c];if(e>0){let t=document.createElement(`span`);t.textContent=`⛁ ${this.formatTokenCount(e)} cached`,l.push(t)}n.replaceChildren(...l)}else n.classList.remove(`chat__token-usage--visible`),n.replaceChildren()}})),this.addCleanup(z(()=>{let t=v.contextUsage,n=e.querySelector(`.chat__context-usage`);if(n instanceof HTMLElement){if(t&&t.contextLimit>0){let e=Math.min(t.usagePercent,100),r=e>80?`high`:e>50?`medium`:`low`;n.classList.add(`chat__context-usage--visible`);let i=document.createElement(`span`);i.textContent=`${this.formatTokenCount(t.estimatedTokens)} / ${this.formatTokenCount(t.contextLimit)}`;let a=document.createElement(`div`);a.className=`chat__context-bar`;let o=document.createElement(`div`);o.className=`chat__context-bar-fill chat__context-bar-fill--${r}`,o.style.width=`${e}%`,a.append(o);let s=document.createElement(`span`);s.textContent=`${e.toFixed(0)}%`;let c=[i,a,s];if(t.truncatedCount>0){let e=document.createElement(`span`);e.textContent=`(${t.truncatedCount} msgs trimmed)`,c.push(e)}n.replaceChildren(...c)}else n.classList.remove(`chat__context-usage--visible`),n.replaceChildren()}})),this.addCleanup(z(()=>{let t=v.toolActivity,n=v.aguiEvent,r=e.querySelector(`.chat__tool-activity`);r instanceof HTMLElement&&(n?.event?.type===`TOOL_CALL_START`&&n.event.toolCallName?(r.classList.add(`chat__tool-activity--active`),r.textContent=`⚙️ Using ${n.event.toolCallName}...`):t?(r.classList.add(`chat__tool-activity--active`),r.textContent=`⚙️ Using ${t.tool}...`):(r.classList.remove(`chat__tool-activity--active`),r.textContent=`⚙️ Working...`))})),this.addCleanup(z(()=>{let t=v.modelDownloadProgress,n=e.querySelector(`.chat__model-progress`),r=e.querySelector(`.chat__model-progress-label`),i=e.querySelector(`.chat__model-progress-bar`);if(!(n instanceof HTMLElement)||!(r instanceof HTMLElement)||!(i instanceof HTMLElement))return;if(!t){n.classList.remove(`chat__model-progress--active`),r.textContent=`Initializing local model...`,i.style.width=`0%`;return}let a=typeof t.progress==`number`?Math.max(0,Math.min(1,t.progress)):0,o=Math.round(a*100);n.classList.add(`chat__model-progress--active`),r.textContent=t.message||(t.status===`done`?`Model ready.`:`Downloading local model... ${o}%`),i.style.width=`${o}%`})),this.addCleanup(z(()=>{let t=F.get(),n=e.querySelector(`.chat__transfer-progress`),r=e.querySelector(`.chat__transfer-progress-label`),i=e.querySelector(`.chat__transfer-progress-bar`);if(!(n instanceof HTMLElement)||!(r instanceof HTMLElement)||!(i instanceof HTMLElement))return;if(!t||t.total===0){n.classList.remove(`chat__transfer-progress--active`),r.textContent=``,i.style.width=`0%`;return}let a=Math.max(0,Math.min(1,t.count/t.total)),o=Math.round(a*100),s=t.direction===`send`?`Sending`:`Receiving`;n.classList.add(`chat__transfer-progress--active`),r.textContent=`${s} file… ${o}%`,i.style.width=`${o}%`})),this.addCleanup(z(()=>{let t=v.activityLog,n=e.querySelector(`.chat__activity-log`);if(n instanceof HTMLElement){if(t.length>0){n.classList.add(`chat__activity-log--active`);let e=t.map(e=>`[${e.level}] ${e.label||``}: ${e.message}`).join(`
2422
+ `,`text/html`),Re=Le.querySelector(`template`);let ze=[];ze=Re?Array.from(Re.content.children):Array.from(Le.head.children).concat(Array.from(Le.body.children));var Be=ze;const Ve=131072,He=8e4;async function Ue(e,t){if(!e||typeof e.transaction!=`function`)return!0;try{return w(await f(e,t),!0)}catch{return!0}}const We=`shadow-claw-chat`;var Ge=class extends V{static styles=Ie;static template=Be;activityLogCollapsedOverride=null;activityLogVisibilityMediaQuery=null;db=null;#e;#t;#n;#r;#i;#a;#o;constructor(){super(),q.reset(),this.db=null,this.#n=0,this.#i=0,this.#a=!1,this.#o=0,this.#r=!0,this.#e=0,this.#t=[]}async connectedCallback(){if(!this.shadowRoot)throw Error(`shadowRoot not found`);this.db=await l(),await this.restoreInputAreaHeight(),this.dispatchTerminalSlotReady(),this.setupEffects(),this.setupActivityLogVisibility(),this.bindEventListeners(),await this.checkPromptApiOnboarding()}disconnectedCallback(){this.activityLogVisibilityCleanup(),q.revokeAttachmentObjectUrls(),q.resetNearBottom(),super.disconnectedCallback()}activityLogVisibilityCleanup=()=>{};applyActivityLogVisibility(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.chat__activity-log`);if(!(t instanceof HTMLElement))return;let n=this.activityLogVisibilityMediaQuery?!this.activityLogVisibilityMediaQuery.matches:!1;(typeof this.activityLogCollapsedOverride==`boolean`?this.activityLogCollapsedOverride:n)?t.classList.add(`chat__activity-log--collapsed`):t.classList.remove(`chat__activity-log--collapsed`)}bindEventListeners(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.chat__messages`);if(t instanceof HTMLElement){t.addEventListener(`scroll`,()=>{this.#a||(this.#o+=1,this.isContainerNearBottom(t)||(this.#r=!1)),q.setNearBottom(this.isContainerNearBottom(t)),this.persistGroupScrollState(t)}),t.addEventListener(`click`,e=>{this.handleMessageLinkClick(e)}),t.addEventListener(`shadow-claw-a2ui-action`,async e=>{let{groupId:t,action:n}=e.detail;if(t.startsWith(`room:`)){await v.orchestrator?.routeRoomA2UIAction(t,n);return}if(t.startsWith(`peer:`)){let e=(v.orchestrator?.router)?.findChannel(t);e&&`sendA2UIAction`in e&&await e.sendA2UIAction(t,n)}let r=JSON.stringify(n.dataModel,null,2),i=`[A2UI ACTION]\nsurfaceId: "${n.surfaceId}"\nactionId: "${n.actionId}"\ndataModel:\n${r}\n\nInstructions: The user triggered the "${n.actionId}" action on surface "${n.surfaceId}". The dataModel above contains the current form values. Use the appropriate tool(s) to fulfill the action based on the actionId and dataModel values. After you have a result, call render_component with action "updateDataModel" on surfaceId "${n.surfaceId}" to update the surface (e.g. patch the output field with the result). Do NOT respond with plain text only — always update the surface via render_component.`;v.sendMessage(i,[],n)}),t.addEventListener(`shadow-claw-a2ui-function-response`,async e=>{let{groupId:t,response:n}=e.detail;if(!t.startsWith(`room:`)&&t.startsWith(`peer:`)){let e=(v.orchestrator?.router)?.findChannel(t);e&&`sendA2UIAction`in e&&await e.sendA2UIAction(t,n)}});let e=new ResizeObserver(()=>{this.shouldAutoFollow(t)&&(this.setMessagesScrollTop(t,t.scrollHeight),this.persistGroupScrollState(t))});e.observe(t),this.addCleanup(()=>e.disconnect())}let n=e.querySelector(`.chat__input`);n instanceof HTMLTextAreaElement&&n.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.sendMessage()),e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.sendMessage())});let r=e.querySelector(`.chat__input-area`),i=e.querySelector(`.chat__input-resize-handle`);r instanceof HTMLElement&&i instanceof HTMLElement&&this.bindInputResizeEvents(r,i),e.querySelector(`[data-action="send-message"]`)?.addEventListener(`click`,()=>this.sendMessage()),e.querySelector(`[data-action="attach-files"]`)?.addEventListener(`click`,()=>{let t=e.querySelector(`.chat__attachment-input`);t instanceof HTMLInputElement&&(t.value=``,t.click())}),e.querySelector(`.chat__attachment-input`)?.addEventListener(`change`,e=>{e.target instanceof HTMLInputElement&&this.queueSelectedFiles(e.target)}),e.querySelector(`[data-action="compact-chat"]`)?.addEventListener(`click`,()=>this.handleCompactChat()),e.querySelector(`[data-action="clear-chat"]`)?.addEventListener(`click`,()=>this.handleClearChat()),e.querySelector(`[data-action="stop-chat"]`)?.addEventListener(`click`,()=>this.handleStopChat()),e.querySelector(`[data-action="download-chat"]`)?.addEventListener(`click`,()=>this.downloadChat()),e.querySelector(`[data-action="restore-chat"]`)?.addEventListener(`click`,()=>{let t=e.querySelector(`.chat__restore-input`);t instanceof HTMLInputElement&&t.click()}),e.querySelector(`.chat__restore-input`)?.addEventListener(`change`,e=>{e.target instanceof HTMLInputElement&&this.restoreChat(e.target)});let a=e.querySelector(`.chat__body`);a instanceof HTMLElement&&(a.addEventListener(`dragenter`,e=>{this.hasDroppableData(e.dataTransfer)&&(e.preventDefault(),this.#e+=1,this.setDropOverlayVisible(!0))}),a.addEventListener(`dragover`,e=>{this.hasDroppableData(e.dataTransfer)&&e.preventDefault()}),a.addEventListener(`dragleave`,e=>{this.hasDroppableData(e.dataTransfer)&&(e.preventDefault(),this.#e=Math.max(0,this.#e-1),this.#e===0&&this.setDropOverlayVisible(!1))}),a.addEventListener(`drop`,e=>{this.hasDroppableData(e.dataTransfer)&&(e.preventDefault(),this.#e=0,this.setDropOverlayVisible(!1),this.queueDroppedData(e.dataTransfer))}));let o=e.querySelector(`.chat__prompt-api-form`);o instanceof HTMLFormElement&&o.addEventListener(`submit`,e=>{e.preventDefault(),this.confirmPromptApiOnboarding()});let s=e.querySelector(`[data-action="confirm-prompt-api-onboarding"]`);s instanceof HTMLElement&&s.addEventListener(`click`,e=>{e.preventDefault(),this.confirmPromptApiOnboarding()});let c=e.querySelector(`[data-action="configure-other-provider"]`);c instanceof HTMLElement&&c.addEventListener(`click`,e=>{e.preventDefault(),this.bypassPromptApiOnboardingToSettings()})}bindInputResizeEvents(e,t){t.setAttribute(`tabindex`,`0`),t.setAttribute(`role`,`separator`),t.setAttribute(`aria-orientation`,`horizontal`),t.setAttribute(`aria-label`,`Resize chat input area`);let n=()=>{let t=parseFloat(e.style.getPropertyValue(`--chat-input-area-height`));return Number.isFinite(t)&&t>0?t:40},r=()=>{let e=this.clampInputAreaHeight(2**53-1),r=Math.round(this.clampInputAreaHeight(n()));t.setAttribute(`aria-valuemin`,`40`),t.setAttribute(`aria-valuemax`,String(Math.round(e))),t.setAttribute(`aria-valuenow`,String(r))},i=null,a=0,o=0,s=t=>{if(t.pointerId!==i)return;let n=a-t.clientY,s=o+n;this.setInputAreaHeight(e,s),r()},c=()=>{if(i===null)return;i=null,t.classList.remove(`active`),document.removeEventListener(`pointermove`,s);let n=parseFloat(e.style.getPropertyValue(`--chat-input-area-height`));Number.isFinite(n)&&n>0?this.persistInputAreaHeight(n):this.persistInputAreaHeight(0)},l=e=>{e.pointerId===i&&c()};t.addEventListener(`pointerdown`,n=>{if(n.pointerType===`mouse`&&n.button!==0&&n.button!==-1)return;let r=e.querySelector(`.chat__input-wrapper`);if(!(r instanceof HTMLElement))return;n.preventDefault(),i=n.pointerId,a=n.clientY,e.classList.add(`chat__input-area--resized`);let c=parseFloat(e.style.getPropertyValue(`--chat-input-area-height`));o=Number.isFinite(c)&&c>0?c:r.getBoundingClientRect().height||40,t.classList.add(`active`),t.setPointerCapture(n.pointerId),document.addEventListener(`pointermove`,s)}),t.addEventListener(`pointerup`,l),t.addEventListener(`pointercancel`,c),t.addEventListener(`dblclick`,()=>{this.resetInputAreaHeight(e),this.persistInputAreaHeight(0),r(),this.scrollMessagesToBottomIfNeeded()}),t.addEventListener(`keydown`,t=>{let i=t.shiftKey?32:12,a=n(),o=null;if(t.key===`ArrowUp`?o=a+i:t.key===`ArrowDown`?o=a-i:t.key===`Home`?o=40:t.key===`End`&&(o=this.clampInputAreaHeight(2**53-1)),o===null)return;t.preventDefault(),this.setInputAreaHeight(e,o),r();let s=parseFloat(e.style.getPropertyValue(`--chat-input-area-height`));this.persistInputAreaHeight(Number.isFinite(s)&&s>0?this.clampInputAreaHeight(s):0),this.scrollMessagesToBottomIfNeeded()}),r(),this.addCleanup(()=>{c(),t.removeEventListener(`pointerup`,l),t.removeEventListener(`pointercancel`,c)})}buildQueuedAttachmentsFromFiles(e){return e.map(e=>{let t=e.name||`attachment.bin`;return{id:`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,fileName:t,mimeType:k(t,e.type||``),size:e.size,source:{kind:`local-file`,file:e}}})}clampInputAreaHeight(e){let t=Math.floor(window.innerHeight*.45);return Math.max(40,Math.min(Math.max(40,t),e))}deferWorkspaceImageLoads(e){let t=document.createElement(`div`);t.innerHTML=e;let n=Array.from(t.querySelectorAll(`img[src]`));for(let e of n){let t=e.getAttribute(`src`);if(!t)continue;let n=this.resolveWorkspaceLinkPath(t);n&&(e.setAttribute(`data-inline-workspace-src`,n),e.removeAttribute(`src`))}return t.innerHTML}dispatchTerminalSlotReady(){this.dispatchEvent(new CustomEvent(`shadow-claw-terminal-slot-ready`,{bubbles:!0,composed:!0}))}formatAttachmentSize(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}formatAttachmentSubtitle(e){let t=[];return e.mimeType&&t.push(e.mimeType),typeof e.size==`number`&&t.push(this.formatAttachmentSize(e.size)),t.join(` · `)||`Attachment`}formatTokenCount(e){return typeof e==`number`?e.toLocaleString(`en-US`):`–`}getAttachmentIcon(e=``){let t=e.toLowerCase();return t.startsWith(`image/`)?`IMG`:t.startsWith(`video/`)?`VID`:t.startsWith(`audio/`)?`AUD`:t.includes(`pdf`)?`PDF`:t.startsWith(`text/`)||t.includes(`json`)?`TXT`:t.includes(`zip`)||t.includes(`tar`)?`ZIP`:`BIN`}getAttachmentTransportLabel(e,t,n){let r=A(e,t);return r===`text`?`text`:r===`image`&&(n.images||n.routerByFeatures)||r===`audio`&&(n.audio||n.routerByFeatures)||r===`document`&&(n.documents||n.routerByFeatures)?`native`:`fallback`}getContainerDistanceFromBottom(e){return Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight)}getMessagesContainer(){let e=this.shadowRoot?.querySelector(`.chat__messages`);return e instanceof HTMLElement?e:null}hasDroppableData(e){if(!e)return!1;if(e.files.length>0)return!0;let t=Array.from(e.types||[]);return t.includes(`Files`)||t.includes(`application/x-moz-file`)||t.includes(`text/plain`)}inferAttachmentModelSupport(e=[]){let t=v.orchestrator?.model?.toLowerCase()||``,n=j(t);return e.every(e=>{let t=(e.mimeType||``).toLowerCase();return this.isInlineTextMimeType(t)?!0:t.startsWith(`image/`)?n.images||n.routerByFeatures:t.startsWith(`audio/`)?n.audio||n.routerByFeatures:t.startsWith(`video/`)?n.video||n.routerByFeatures:!1})}injectCopyButtons(e){e.querySelectorAll(`pre`).forEach(e=>{if(e.querySelector(`.chat__code-copy-btn`))return;let t=document.createElement(`button`);t.className=`chat__code-copy-btn`,t.type=`button`,t.setAttribute(`aria-label`,`Copy code to clipboard`),t.textContent=`📋 Copy`,t.addEventListener(`click`,async()=>{let n=e.querySelector(`code`),r=n?n.textContent||``:e.textContent||``;try{await navigator.clipboard.writeText(r),t.textContent=`✅ Copied`,t.classList.add(`chat__code-copy-btn--copied`),setTimeout(()=>{t.textContent=`📋 Copy`,t.classList.remove(`chat__code-copy-btn--copied`)},1500)}catch{t.textContent=`⚠️ Failed`,setTimeout(()=>{t.textContent=`📋 Copy`},1500)}}),e.appendChild(t)})}injectMessageCopyButton(e,t){if(e.querySelector(`.chat__msg-copy-btn`))return;let n=e.querySelector(`.chat__message-content`);if(!n)return;let r=document.createElement(`button`);r.className=`chat__msg-copy-btn`,r.type=`button`,r.setAttribute(`aria-label`,`Copy message to clipboard`);let i=`http://www.w3.org/2000/svg`,a=document.createElementNS(i,`svg`);a.setAttribute(`fill`,`none`),a.setAttribute(`stroke-width`,`1.5`),a.setAttribute(`stroke`,`currentColor`),a.setAttribute(`viewBox`,`0 0 24 24`);let o=document.createElementNS(i,`path`);o.setAttribute(`d`,`M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75`),o.setAttribute(`stroke-linecap`,`round`),o.setAttribute(`stroke-linejoin`,`round`),a.append(o),r.append(a),r.addEventListener(`click`,async()=>{try{await navigator.clipboard.writeText(t),r.classList.add(`chat__msg-copy-btn--copied`),r.setAttribute(`aria-label`,`Copied!`),setTimeout(()=>{r.classList.remove(`chat__msg-copy-btn--copied`),r.setAttribute(`aria-label`,`Copy message to clipboard`)},1500)}catch{r.setAttribute(`aria-label`,`Copy failed`),setTimeout(()=>{r.setAttribute(`aria-label`,`Copy message to clipboard`)},1500)}}),n.appendChild(r)}injectMessageDeleteButton(e,t){if(e.querySelector(`.chat__msg-delete-btn`))return;let n=e.querySelector(`.chat__message-content`);if(!n)return;let r=document.createElement(`button`);r.className=`chat__msg-delete-btn`,r.type=`button`,r.setAttribute(`aria-label`,`Delete message`);let i=`http://www.w3.org/2000/svg`,a=document.createElementNS(i,`svg`);a.setAttribute(`fill`,`none`),a.setAttribute(`stroke-width`,`1.5`),a.setAttribute(`stroke`,`currentColor`),a.setAttribute(`viewBox`,`0 0 24 24`);let o=document.createElementNS(i,`path`);o.setAttribute(`d`,`M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0`),o.setAttribute(`stroke-linecap`,`round`),o.setAttribute(`stroke-linejoin`,`round`),a.append(o),r.append(a),r.addEventListener(`click`,async()=>{await this.showAttachmentDialog({mode:`confirm`,title:`Delete Message`,message:`Delete this message? This action cannot be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`})&&this.db&&await v.deleteMessage(this.db,t)}),n.appendChild(r)}isCollapsedInputAreaHeight(e){return e<=41}isContainerNearBottom(e){let{scrollTop:t,scrollHeight:n,clientHeight:r}=e;return n-t-r<80}isInlineTextMimeType(e){let t=e.toLowerCase();return t.startsWith(`text/`)?!0:t===`application/json`||t===`application/xml`||t===`application/javascript`}isLatestRender(e){return e===this.#n}persistGroupScrollState(e){let t=v.activeGroupId,n=this.isContainerNearBottom(e),r=n?0:this.getContainerDistanceFromBottom(e);q.setGroupScrollState(t,r,n)}removeStreamingBubble(e){e.querySelector(`.chat__message--streaming`)?.remove()}renderAttachmentCapabilitySummary(){let e=this.shadowRoot?.querySelector(`.chat__attachment-capabilities`);if(!(e instanceof HTMLElement))return;let t=v.orchestrator?.model||``;e.textContent=t?`Model attachment support: ${M(t)}`:``}renderQueuedAttachments(){let e=this.shadowRoot?.querySelector(`.chat__pending-attachments`);if(!(e instanceof HTMLElement))return;if(this.#t.length===0){e.hidden=!0,e.replaceChildren();return}let t=(v.orchestrator?.model||``).toLowerCase(),n=j(t);e.hidden=!1;let r=document.createDocumentFragment();for(let e of this.#t){let t=document.createElement(`div`);t.className=`chat__pending-attachment`;let i=document.createElement(`span`);i.className=`chat__attachment-icon`,i.setAttribute(`aria-hidden`,`true`),i.textContent=this.getAttachmentIcon(e.mimeType);let a=document.createElement(`div`);a.className=`chat__pending-attachment-meta`;let o=document.createElement(`span`);o.className=`chat__pending-attachment-name`,o.textContent=e.fileName;let s=document.createElement(`span`);s.className=`chat__pending-attachment-detail`,s.textContent=`${e.mimeType} · ${this.formatAttachmentSize(e.size)}`,a.append(o,s);let c=this.getAttachmentTransportLabel(e.mimeType,e.fileName,n),l=document.createElement(`span`);l.className=`chat__transport-badge chat__transport-badge--${c}`,l.setAttribute(`aria-label`,`Transport: ${c}`),l.textContent=c;let u=document.createElement(`button`);u.type=`button`,u.className=`chat__pending-attachment-remove`,u.setAttribute(`aria-label`,`Remove ${e.fileName}`),u.textContent=`x`,u.addEventListener(`click`,()=>{this.#t=this.#t.filter(t=>t.id!==e.id),this.renderQueuedAttachments()}),t.append(i,a,l,u),r.appendChild(t)}e.replaceChildren(r)}resetInputAreaHeight(e){e.classList.remove(`chat__input-area--resized`),e.style.removeProperty(`--chat-input-area-height`)}resolveWorkspaceLinkPath(e){let t=e.trim();if(!t||t.startsWith(`#`)||/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(t)||t.startsWith(`//`))return null;let n=t.split(/[?#]/,1)[0].replace(/\\/g,`/`);if(n=n.replace(/^\/+/,``),n=n.replace(/^\.\//,``),!n)return null;let r=n.split(`/`).filter(Boolean).map(e=>s(e));return r.some(e=>e===`..`)?null:r.join(`/`)}revokeAttachmentObjectUrls(){q.revokeAttachmentObjectUrls()}scheduleBottomSnap(e){let t=()=>{this.isLatestRender(e)&&this.scrollMessagesToBottomIfNeeded()};requestAnimationFrame(()=>{t(),requestAnimationFrame(t)}),setTimeout(t,120)}scrollMessagesToBottomIfNeeded(){let e=this.shadowRoot?.querySelector(`.chat__messages`);e instanceof HTMLElement&&q.isNearBottom&&(this.setMessagesScrollTop(e,e.scrollHeight),q.setNearBottom(this.isContainerNearBottom(e)),this.persistGroupScrollState(e))}setActivityLogCollapsedOverride(e){this.activityLogCollapsedOverride=e,this.applyActivityLogVisibility()}setDropOverlayVisible(e){let t=this.shadowRoot?.querySelector(`[data-drop-overlay]`);t instanceof HTMLElement&&(t.hidden=!e)}setInputAreaHeight(e,t){let n=this.clampInputAreaHeight(t);this.isCollapsedInputAreaHeight(n)?this.resetInputAreaHeight(e):(e.classList.add(`chat__input-area--resized`),e.style.setProperty(`--chat-input-area-height`,`${n}px`))}setMessagesScrollTop(e,t){this.#a=!0,e.scrollTop=t,requestAnimationFrame(()=>{this.#a=!1})}setupActivityLogVisibility(){if(this.shadowRoot){if(typeof globalThis.matchMedia==`function`){this.activityLogVisibilityMediaQuery=globalThis.matchMedia(`(min-width: 56rem) and (min-height: 401px)`);let e=()=>this.applyActivityLogVisibility();this.activityLogVisibilityMediaQuery.addEventListener(`change`,e),this.activityLogVisibilityCleanup=()=>{this.activityLogVisibilityMediaQuery?.removeEventListener(`change`,e)}}this.applyActivityLogVisibility()}}setupEffects(){let e=this.shadowRoot;e&&(this.addCleanup(z(()=>{let t=++this.#n,n=v.activeGroupId,r=v.messages,a=e.querySelector(`.chat__messages`);if(!(a instanceof HTMLElement))return;let o=q.getGroupScrollState(n);o?q.setNearBottom(o.nearBottom):q.setNearBottom(!0);let s=this.shouldAutoFollow(a),l=this.#o,u=s?0:o?.distanceFromBottom??this.getContainerDistanceFromBottom(a);this.revokeAttachmentObjectUrls(),a.replaceChildren(),(async()=>{let e=await Ue(this.db,c.MARKDOWN_FRONTMATTER_CHAT);for(let n of r){if(!this.isLatestRender(t))return!1;if(n.a2uiAction||n.content&&n.content.startsWith(`[A2UI ACTION]`))continue;let r=n.isFromMe?`assistant`:`user`,o=g(`assistantName`)||`ShadowClaw`,c=n.isFromMe?o:n.sender||`You`,l=document.createElement(`article`);l.className=`chat__message chat__message--${r}`;let u=n.timestamp?L(n.timestamp):``,d=await N(n.content,{breaks:!0,renderFrontmatter:e}),f=document.createElement(`div`);f.className=`chat__message-header`;let p=document.createElement(`div`);p.className=`chat__message-sender`,p.textContent=c;let m=document.createElement(`div`);m.className=`chat__message-timestamp`,m.textContent=u,f.append(p,m),l.append(f);let h=document.createElement(`div`);if(h.className=`chat__message-content`,n.content){let e=this.deferWorkspaceImageLoads(d);if(i(h,e),await this.resolveImagePaths(n.groupId,h),!this.isLatestRender(t))return!1}let _=await this.renderMessageAttachments(n);if(_&&h.appendChild(_),n.a2uiEnvelopes&&n.a2uiEnvelopes.length>0){let e=document.createElement(`shadow-claw-a2ui-interceptor`),t=document.createElement(`shadow-claw-a2ui`);t.groupId=n.groupId;for(let e of n.a2uiEnvelopes)t.applyEnvelope(e);e.appendChild(t),h.appendChild(e)}l.appendChild(h),a.appendChild(l),s&&(this.setMessagesScrollTop(a,a.scrollHeight),this.persistGroupScrollState(a)),n.content&&n.id&&(this.injectMessageCopyButton(l,n.content),this.injectMessageDeleteButton(l,n.id)),h instanceof HTMLElement&&n.content&&this.injectCopyButtons(h)}return!0})().then(async e=>{if(!e||!this.isLatestRender(t))return;let n=this.#o!==l;this.shouldAutoFollow(a)?(this.setMessagesScrollTop(a,a.scrollHeight),q.setNearBottom(this.isContainerNearBottom(a)),this.persistGroupScrollState(a),this.scheduleBottomSnap(t)):n?(q.setNearBottom(this.isContainerNearBottom(a)),this.persistGroupScrollState(a)):(this.setMessagesScrollTop(a,a.scrollHeight-a.clientHeight-u),q.setNearBottom(this.isContainerNearBottom(a)),this.persistGroupScrollState(a))})})),this.addCleanup(z(()=>{let e=v.streamingText;this.renderStreamingBubble(e)})),this.addCleanup(z(()=>{v.ready,v.state,this.renderAttachmentCapabilitySummary()})),this.addCleanup(z(()=>{let t=v.tokenUsageAccumulator,n=e.querySelector(`.chat__token-usage`);if(n instanceof HTMLElement){if(t&&(t.inputTokens||t.outputTokens)){n.classList.add(`chat__token-usage--visible`);let{cacheTokens:e,promptTokens:r,outputTokens:i,totalTokens:a}=ee(t),o=document.createElement(`span`);o.textContent=`⬆ ${this.formatTokenCount(r)} in`;let s=document.createElement(`span`);s.textContent=`⬇ ${this.formatTokenCount(i)} out`;let c=document.createElement(`span`);c.textContent=`Σ ${this.formatTokenCount(a)}`;let l=[o,s,c];if(e>0){let t=document.createElement(`span`);t.textContent=`⛁ ${this.formatTokenCount(e)} cached`,l.push(t)}n.replaceChildren(...l)}else n.classList.remove(`chat__token-usage--visible`),n.replaceChildren()}})),this.addCleanup(z(()=>{let t=v.contextUsage,n=e.querySelector(`.chat__context-usage`);if(n instanceof HTMLElement){if(t&&t.contextLimit>0){let e=Math.min(t.usagePercent,100),r=e>80?`high`:e>50?`medium`:`low`;n.classList.add(`chat__context-usage--visible`);let i=document.createElement(`span`);i.textContent=`${this.formatTokenCount(t.estimatedTokens)} / ${this.formatTokenCount(t.contextLimit)}`;let a=document.createElement(`div`);a.className=`chat__context-bar`;let o=document.createElement(`div`);o.className=`chat__context-bar-fill chat__context-bar-fill--${r}`,o.style.width=`${e}%`,a.append(o);let s=document.createElement(`span`);s.textContent=`${e.toFixed(0)}%`;let c=[i,a,s];if(t.truncatedCount>0){let e=document.createElement(`span`);e.textContent=`(${t.truncatedCount} msgs trimmed)`,c.push(e)}n.replaceChildren(...c)}else n.classList.remove(`chat__context-usage--visible`),n.replaceChildren()}})),this.addCleanup(z(()=>{let t=v.toolActivity,n=v.aguiEvent,r=e.querySelector(`.chat__tool-activity`);r instanceof HTMLElement&&(n?.event?.type===`TOOL_CALL_START`&&n.event.toolCallName?(r.classList.add(`chat__tool-activity--active`),r.textContent=`⚙️ Using ${n.event.toolCallName}...`):t?(r.classList.add(`chat__tool-activity--active`),r.textContent=`⚙️ Using ${t.tool}...`):(r.classList.remove(`chat__tool-activity--active`),r.textContent=`⚙️ Working...`))})),this.addCleanup(z(()=>{let t=v.modelDownloadProgress,n=e.querySelector(`.chat__model-progress`),r=e.querySelector(`.chat__model-progress-label`),i=e.querySelector(`.chat__model-progress-bar`);if(!(n instanceof HTMLElement)||!(r instanceof HTMLElement)||!(i instanceof HTMLElement))return;if(!t){n.classList.remove(`chat__model-progress--active`),r.textContent=`Initializing local model...`,i.style.width=`0%`;return}let a=typeof t.progress==`number`?Math.max(0,Math.min(1,t.progress)):0,o=Math.round(a*100);n.classList.add(`chat__model-progress--active`),r.textContent=t.message||(t.status===`done`?`Model ready.`:`Downloading local model... ${o}%`),i.style.width=`${o}%`})),this.addCleanup(z(()=>{let t=F.get(),n=e.querySelector(`.chat__transfer-progress`),r=e.querySelector(`.chat__transfer-progress-label`),i=e.querySelector(`.chat__transfer-progress-bar`);if(!(n instanceof HTMLElement)||!(r instanceof HTMLElement)||!(i instanceof HTMLElement))return;if(!t||t.total===0){n.classList.remove(`chat__transfer-progress--active`),r.textContent=``,i.style.width=`0%`;return}let a=Math.max(0,Math.min(1,t.count/t.total)),o=Math.round(a*100),s=t.direction===`send`?`Sending`:`Receiving`;n.classList.add(`chat__transfer-progress--active`),r.textContent=`${s} file… ${o}%`,i.style.width=`${o}%`})),this.addCleanup(z(()=>{let t=v.activityLog,n=e.querySelector(`.chat__activity-log`);if(n instanceof HTMLElement){if(t.length>0){n.classList.add(`chat__activity-log--active`);let e=t.map(e=>`[${e.level}] ${e.label||``}: ${e.message}`).join(`
2423
2423
  `),r=document.createElement(`div`);r.className=`chat__activity-log__header`;let i=document.createElement(`span`);i.className=`chat__activity-log__label`,i.textContent=`Activity Log`;let a=document.createElement(`button`);a.className=`chat__activity-log__copy-btn`,a.type=`button`,a.setAttribute(`aria-label`,`Copy activity log to clipboard`);let o=`http://www.w3.org/2000/svg`,s=document.createElementNS(o,`svg`);s.setAttribute(`fill`,`none`),s.setAttribute(`stroke-width`,`1.5`),s.setAttribute(`stroke`,`currentColor`),s.setAttribute(`viewBox`,`0 0 24 24`);let c=document.createElementNS(o,`path`);c.setAttribute(`d`,`M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75`),c.setAttribute(`stroke-linecap`,`round`),c.setAttribute(`stroke-linejoin`,`round`),s.append(c),a.append(s),a.addEventListener(`click`,async()=>{try{await navigator.clipboard.writeText(e),a.classList.add(`chat__activity-log__copy-btn--copied`),a.setAttribute(`aria-label`,`Copied!`),setTimeout(()=>{a.classList.remove(`chat__activity-log__copy-btn--copied`),a.setAttribute(`aria-label`,`Copy activity log to clipboard`)},1500)}catch{a.setAttribute(`aria-label`,`Copy failed`),setTimeout(()=>{a.setAttribute(`aria-label`,`Copy activity log to clipboard`)},1500)}}),r.append(i,a);let l=document.createElement(`div`);l.className=`chat__activity-log__entries`,t.forEach(e=>{let t=document.createElement(`div`);t.textContent=`[${e.level}] ${e.label||``}: ${e.message}`,l.append(t)}),n.replaceChildren(r,l),l.scrollTop=l.scrollHeight}else n.classList.remove(`chat__activity-log--active`),n.replaceChildren()}})),this.addCleanup(z(()=>{let t=v.activeGroupId,n=e.querySelector(`.chat__shared-state`),r=e.querySelector(`.chat__shared-state-code`);if(!(n instanceof HTMLElement)||!(r instanceof HTMLElement))return;let i=v.getPeerState(t);i&&Object.keys(i).length>0?(n.hidden=!1,r.textContent=JSON.stringify(i,null,2)):(n.hidden=!0,r.textContent=``)})),this.addCleanup(z(()=>{let t=v.state,n=v.activeGroupId,r=e.querySelector(`.chat__status-text`),i=e.querySelector(`.chat__status-indicator`),a=e.querySelector(`.chat__typing-indicator`);if(!(r instanceof HTMLElement)||!(i instanceof HTMLElement)||!(a instanceof HTMLElement))return;let o=n.startsWith(`peer:`),s=o&&v.isRemoteAgentTyping(n),c=o?te(v.getRemoteAgentStatus(n),s):t;i.classList.remove(`chat__status-indicator--thinking`,`chat__status-indicator--responding`,`chat__status-indicator--error`),(c===`thinking`||c===`responding`)&&i.classList.add(`chat__status-indicator--${c}`),c===`error`&&i.classList.add(`chat__status-indicator--error`),r.textContent=c.charAt(0).toUpperCase()+c.slice(1),a.toggleAttribute(`hidden`,!s)})),this.addCleanup(z(()=>{let t=v.state,n=e.querySelector(`[data-action="send-message"]`),r=e.querySelector(`[data-action="stop-chat"]`),i=t===`thinking`||t===`responding`;n instanceof HTMLButtonElement&&(n.disabled=i),r instanceof HTMLButtonElement?r.disabled=!i:r?.toggleAttribute(`disabled`,!i)})),this.addCleanup(z(()=>{let e=v.error;e&&(S(e,6e3),v.clearError())})))}shouldAutoFollow(e){let t=v.state,n=t===`thinking`||t===`responding`,r=this.isContainerNearBottom(e);return n?(r&&(this.#r=!0),this.#r):(this.#r=!0,q.nearBottomSnapshot||r)}async buildMessageDraftPayload(e){let t=e.trim(),n=this.#t.map(e=>{let t=e.mimeType===`image/png`?`inline`:`file`;return{id:e.id,fileName:e.fileName,mimeType:e.mimeType,size:e.size,source:e.source,previewDisposition:t}});if(n.length===0)return{text:t,attachments:n};if(n.filter(e=>!this.isInlineTextMimeType(e.mimeType||``)).length>0&&!this.inferAttachmentModelSupport(n)&&!await this.showAttachmentDialog({mode:`confirm`,title:`Limited Attachment Support`,message:`The selected model may not natively read binary attachments (images/audio/video/docs). Files will still be attached to chat history, but responses might be limited.`,confirmLabel:`Send Anyway`,cancelLabel:`Cancel`,details:[`Try a multimodal model for best binary-file results.`,`Text files are inlined automatically when they are reasonably small.`]}))return null;let r=n.map(e=>`- ${e.fileName} (${e.mimeType||`application/octet-stream`}, ${this.formatAttachmentSize(e.size||0)})`),i=[],a=0;for(let e of this.#t){if(!this.isInlineTextMimeType(e.mimeType))continue;if(e.size>Ve){i.push(`File: ${e.fileName}\nSkipped inline content because the file is larger than ${this.formatAttachmentSize(Ve)}.`);continue}if(e.source.kind!==`local-file`)continue;let t=await e.source.file.text();if(a+=t.length,a>He)return await this.showAttachmentDialog({mode:`info`,title:`Attachment Context Too Large`,message:`The dropped text content exceeds the safe prompt budget. Remove some files or send them in smaller batches.`,details:[`Current inline text budget: ${He.toLocaleString()} characters`,`Large text blobs can degrade response quality and exhaust context.`],confirmLabel:`OK`}),null;i.push(`File: ${e.fileName}\n${t}`)}return{text:`${t?`${t}\n\n`:``}${`Attached files:\n${r.join(`
2424
2424
  `)}`}${i.length>0?`\n\nAttached text excerpts:\n\n${i.join(`
2425
2425
 
2426
2426
  ---
2427
2427
 
2428
- `)}`:``}`,attachments:n}}async bypassPromptApiOnboardingToSettings(){let e=this.shadowRoot;if(!e)return;if(this.db||=await l(),this.db)try{await y(this.db,s.TRANSFORMERS_JS_ONBOARDING_SEEN,`true`),await y(this.db,s.PROMPT_API_ONBOARDING_SEEN,`true`)}catch(e){console.warn(`Failed to persist Prompt API onboarding status:`,e)}let t=e.querySelector(`shadow-claw-dialog[dialog-class="chat__prompt-api-dialog"]`);if(t&&typeof t.close==`function`)t.close();else{let t=e.querySelector(`dialog.chat__prompt-api-dialog`);t instanceof HTMLDialogElement&&t.close()}document.dispatchEvent(new CustomEvent(`shadow-claw-navigate`,{detail:{page:`settings`},bubbles:!0,composed:!0}))}async checkPromptApiOnboarding(){if((!E()||globalThis.__SHADOWCLAW_E2E_TEST_ONBOARDING__)&&(this.db||=await l(),this.db))try{let e=await f(this.db,s.PROVIDER);if((typeof e==`string`&&e.trim()?e.trim():`transformers_js_browser`)!==`transformers_js_browser`)return;let t=await f(this.db,s.TRANSFORMERS_JS_ONBOARDING_SEEN)||await f(this.db,s.PROMPT_API_ONBOARDING_SEEN);if(w(t,!1))return;let n=this.shadowRoot;if(!n)return;this.ensureShadowDialogs();let r=n.querySelector(`.chat__prompt-api-status-card`);r&&(r.hidden=!0);let i=n.querySelector(`.chat__prompt-api-fallback-card`);i&&(i.hidden=!1);let a=n.querySelector(`[data-setting="prompt-api-onboarding-fallback-model"]`);if(a){let e=await f(this.db,s.MODEL)||await f(this.db,s.PROMPT_API_FALLBACK_MODEL),t=typeof e==`string`&&e.trim()?e.trim():o.transformers_js_browser?.defaultModel||`onnx-community/Qwen3-0.6B-ONNX`;this.populateOnboardingModelSelect(a,t);let n=o.transformers_js_browser?.modelsUrl;if(n&&typeof fetch==`function`)try{let e=fetch(n);e&&typeof e.then==`function`&&e.then(e=>e&&e.ok?e.json():null).then(e=>{if(!e)return;let n=Array.isArray(e)?e:e.models||e.data||[];if(Array.isArray(n)&&n.length>0){let e=a.value||t;this.populateOnboardingModelSelect(a,e,n)}}).catch(()=>{})}catch{}}let c=n.querySelector(`shadow-claw-dialog[dialog-class="chat__prompt-api-dialog"]`);if(c&&typeof c.showModal==`function`)c.showModal();else{let e=n.querySelector(`dialog.chat__prompt-api-dialog`);e instanceof HTMLDialogElement&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``))}}catch(e){console.warn(`Failed to check Prompt API onboarding:`,e)}}populateOnboardingModelSelect(e,t,n){let r=O(t,n);i(e,r),e.value=t}async confirmPromptApiOnboarding(){let e=this.shadowRoot;if(!e)return;this.db||=await l();let t=e.querySelector(`[data-setting="prompt-api-onboarding-fallback-model"]`)?.value?.trim()||o.transformers_js_browser?.defaultModel||`onnx-community/Qwen3-0.6B-ONNX`;if(this.db)try{await y(this.db,s.PROVIDER,`transformers_js_browser`),await y(this.db,s.MODEL,t),await y(this.db,s.PROMPT_API_FALLBACK_MODEL,t),await y(this.db,s.TRANSFORMERS_JS_ONBOARDING_SEEN,`true`),await y(this.db,s.PROMPT_API_ONBOARDING_SEEN,`true`)}catch(e){console.warn(`Failed to persist Prompt API onboarding settings:`,e)}v.orchestrator&&(v.orchestrator.provider=`transformers_js_browser`,v.orchestrator.model=t);let n=e.querySelector(`shadow-claw-dialog[dialog-class="chat__prompt-api-dialog"]`);if(n&&typeof n.close==`function`)n.close();else{let t=e.querySelector(`dialog.chat__prompt-api-dialog`);t instanceof HTMLDialogElement&&t.close()}b(`Transformers.js configured`,2500)}async downloadAttachment(e,t){if(this.db&&t.path)try{await I(this.db,e,t.path)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to download attachment: ${t}`,5e3)}}async downloadChat(){if(this.db)try{let e=v.activeGroupId,t=await W(this.db,e);if(!t){S(`Failed to export chat data`,6e3);return}let n=new H.default;n.file(`chat-data.json`,JSON.stringify(t,null,2));let r=await n.generateAsync({type:`blob`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=`chat-${R()}.zip`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i),b(`Chat backup downloaded`,3e3)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to download chat: ${t}`,6e3)}}async handleClearChat(){let e=this.shadowRoot;if(!e||!this.db)return;let t=e.querySelector(`.chat__messages`);t instanceof HTMLElement&&t.replaceChildren();try{await v.newSession(this.db)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to clear session:`,t)}}async handleCompactChat(){if(this.db&&await this.showAttachmentDialog({mode:`confirm`,title:`Compact Conversation`,message:`This will summarize the conversation to reduce token usage. The summary replaces the current history. Continue?`,confirmLabel:`Compact`,cancelLabel:`Cancel`}))try{await v.compactContext(this.db),x(`Compacting context...`,2500)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to compact chat: ${t}`,6e3)}}async handleMessageLinkClick(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`a`);if(!(n instanceof HTMLAnchorElement))return;let i=n.getAttribute(`href`)||``,a=v.activeGroupId;r(i,``,a)&&e.preventDefault()}async handleStopChat(){try{v.stopCurrentRequest(),x(`Stopped current request`,2200)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to stop request: ${t}`,6e3)}}async openAttachment(e,t){if(this.db&&t.path)try{await B.openFile(this.db,t.path,e)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to open attachment: ${t}`,5e3)}}async persistInputAreaHeight(e){if(this.db)try{await y(this.db,s.CHAT_INPUT_AREA_HEIGHT,e)}catch{}}async queueDroppedData(e){if(!e)return;let t=this.buildQueuedAttachmentsFromFiles(Array.from(e.files||[])),n=await this.readDroppedPlainText(e);if(n){let e=n.trim();if(e){let n=new Blob([e],{type:`text/plain`});t.push({id:`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,fileName:`dropped-text-${(/* @__PURE__ */ new Date()).toISOString().slice(0,19).replace(/[:T]/g,`-`)}.txt`,mimeType:`text/plain`,size:n.size,source:{kind:`local-file`,file:n}})}}t.length!==0&&(this.#t=[...this.#t,...t],this.renderQueuedAttachments(),x(`Queued ${t.length} attachment${t.length===1?``:`s`}.`,2200))}async queueSelectedFiles(e){let t=Array.from(e.files||[]);if(t.length===0){e.value=``;return}let n=this.buildQueuedAttachmentsFromFiles(t);this.#t=[...this.#t,...n],this.renderQueuedAttachments(),x(`Queued ${n.length} attachment${n.length===1?``:`s`}.`,2200),e.value=``}async readDroppedPlainText(e){let t=Array.from(e.items||[]).find(e=>e.kind===`string`&&e.type===`text/plain`);return t?await new Promise(e=>{t.getAsString(t=>{e(t||``)})}):``}async renderInlineAttachmentPreview(e,t){if(!this.db||!t.path)return null;try{let n=await D(this.db,e.groupId,t.path),r=new Uint8Array(n.byteLength);r.set(n);let i=new Blob([r],{type:t.mimeType||`image/png`}),a=URL.createObjectURL(i);q.registerAttachmentObjectUrl(a);let o=document.createElement(`button`);o.className=`chat__attachment-preview-btn`,o.type=`button`,o.setAttribute(`aria-label`,`Open ${t.fileName}`),o.addEventListener(`click`,()=>{this.openAttachment(e.groupId,t)});let s=document.createElement(`img`);return s.className=`chat__attachment-preview`,s.alt=t.fileName,s.src=a,o.appendChild(s),o}catch(e){let t=document.createElement(`div`);return t.className=`chat__attachment-preview-error`,t.textContent=e instanceof Error?e.message:`Attachment preview unavailable.`,t}}async renderMessageAttachments(e){if(!Array.isArray(e.attachments)||e.attachments.length===0)return null;let t=document.createElement(`div`);t.className=`chat__attachments`;for(let n of e.attachments){let r=document.createElement(`section`);if(r.className=`chat__attachment`,P(n)&&n.path){let t=await this.renderInlineAttachmentPreview(e,n);t&&r.appendChild(t)}let i=document.createElement(`div`);i.className=`chat__attachment-meta`;let a=document.createElement(`div`);a.className=`chat__attachment-identity`;let o=document.createElement(`span`);o.className=`chat__attachment-icon`,o.setAttribute(`aria-hidden`,`true`),o.textContent=this.getAttachmentIcon(n.mimeType||``);let s=document.createElement(`button`);s.className=`chat__attachment-title`,s.type=`button`,s.textContent=n.fileName,s.disabled=!n.path||!this.db,s.addEventListener(`click`,()=>{this.openAttachment(e.groupId,n)}),a.append(o,s),i.appendChild(a);let c=document.createElement(`div`);c.className=`chat__attachment-subtitle`,c.textContent=this.formatAttachmentSubtitle(n),i.appendChild(c);let l=document.createElement(`div`);if(l.className=`chat__attachment-actions`,n.path&&this.db){let t=document.createElement(`button`);t.className=`chat__attachment-action`,t.type=`button`,t.textContent=`Open`,t.addEventListener(`click`,()=>{this.openAttachment(e.groupId,n)}),l.appendChild(t);let r=document.createElement(`button`);r.className=`chat__attachment-action`,r.type=`button`,r.textContent=`Download`,r.addEventListener(`click`,()=>{this.downloadAttachment(e.groupId,n)}),l.appendChild(r)}i.appendChild(l),r.appendChild(i),t.appendChild(r)}return t}async renderStreamingBubble(e){let t=++this.#i,n=this.getMessagesContainer();if(!n)return;let r=this.shouldAutoFollow(n);if(!(typeof e==`string`&&e.length>0)){this.removeStreamingBubble(n);return}let a=n.querySelector(`.chat__message--streaming`),o=null;if(!a){let e=g(`assistantName`)||`ShadowClaw`;a=document.createElement(`article`),a.className=`chat__message chat__message--assistant chat__message--streaming`;let t=document.createElement(`div`);t.className=`chat__message-header`;let r=document.createElement(`div`);r.className=`chat__message-sender`,r.textContent=e;let i=document.createElement(`div`);i.className=`chat__message-timestamp`,i.textContent=`streaming…`,t.append(r,i),o=document.createElement(`div`),o.className=`chat__message-content`,a.append(t,o),n.appendChild(a)}else if(o=a.querySelector(`.chat__message-content`),!(o instanceof HTMLElement))return;let s=p(e).replace(/\n/g,`<br>`).replace(/`([^`]+?)`/g,`<code>$1</code>`).replace(/\*\*([^*]+?)\*\*/g,`<b>$1</b>`);if(t!==this.#i)return;i(o,s);let c=document.createElement(`span`);c.setAttribute(`aria-hidden`,`true`),c.className=`chat__streaming-cursor`,o.append(c),a.querySelector(`.chat__msg-copy-btn`)?.remove(),this.injectMessageCopyButton(a,e),this.injectCopyButtons(o),r&&(this.setMessagesScrollTop(n,n.scrollHeight),q.setNearBottom(this.isContainerNearBottom(n)),this.persistGroupScrollState(n))}async resolveImagePaths(e,t){if(!this.db)return;let n=Array.from(t.querySelectorAll(`img`));for(let t of n){let n=t.getAttribute(`data-inline-workspace-src`)||t.getAttribute(`src`)||``,r=this.resolveWorkspaceLinkPath(n);if(r)try{let n=await D(this.db,e,r),i=new Uint8Array(n.byteLength);i.set(n);let a=r.toLowerCase();if(a.endsWith(`.pdf`)){let e=document.createElement(`shadow-claw-pdf-viewer`);e.file={name:r.split(`/`).pop()||`document.pdf`,binaryContent:i},t.replaceWith(e)}else{let e=`image/png`;a.endsWith(`.jpg`)||a.endsWith(`.jpeg`)?e=`image/jpeg`:a.endsWith(`.gif`)?e=`image/gif`:a.endsWith(`.webp`)?e=`image/webp`:a.endsWith(`.svg`)&&(e=`image/svg+xml`);let n=new Blob([i],{type:e}),r=URL.createObjectURL(n);q.registerAttachmentObjectUrl(r),t.addEventListener(`load`,()=>this.scrollMessagesToBottomIfNeeded(),{once:!0}),t.removeAttribute(`data-inline-workspace-src`),t.src=r}}catch(e){console.warn(`Failed to load inline image: ${r}`,e)}}let r=Array.from(t.querySelectorAll(`a[href]`));for(let t of r){let n=t.getAttribute(`href`)||``,r=this.resolveWorkspaceLinkPath(n);if(r&&r.toLowerCase().endsWith(`.pdf`))try{let n=await D(this.db,e,r),i=new Uint8Array(n.byteLength);i.set(n);let a=document.createElement(`shadow-claw-pdf-viewer`);a.file={name:r.split(`/`).pop()||`document.pdf`,binaryContent:i},t.insertAdjacentElement(`afterend`,a),requestAnimationFrame(()=>this.scrollMessagesToBottomIfNeeded()),setTimeout(()=>this.scrollMessagesToBottomIfNeeded(),120)}catch(e){console.warn(`Failed to load inline PDF: ${r}`,e)}}}async restoreChat(e){if(!this.db)return;let t=e.files?.[0];if(t){if(!t.name.endsWith(`.zip`))C(`Please select a .zip file`,3500),e.value=``;else try{let n=(await H.default.loadAsync(t)).file(`chat-data.json`);if(!n){S(`Invalid chat file: missing chat-data.json`,6e3),e.value=``;return}let r=await n.async(`string`),i=JSON.parse(r);if(!i.messages||!Array.isArray(i.messages)){S(`Invalid chat file: missing messages array`,6e3),e.value=``;return}let a=v.activeGroupId;await K(this.db,a,i),await v.loadHistory(),b(`Chat restored successfully`,3500)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to restore chat: ${t}`,6e3)}finally{e.value=``}}}async restoreInputAreaHeight(){let e=this.shadowRoot?.querySelector(`.chat__input-area`);if(e instanceof HTMLElement)try{let t=this.db?await f(this.db,s.CHAT_INPUT_AREA_HEIGHT):void 0;typeof t==`number`&&Number.isFinite(t)&&t>0&&(this.isCollapsedInputAreaHeight(t)?this.resetInputAreaHeight(e):this.setInputAreaHeight(e,t))}catch{}}async sendMessage(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.chat__input`);if(!(t instanceof HTMLTextAreaElement))return;let n=t.value.trim();if(n||this.#t.length!==0){if(!v.ready)C(`ShadowClaw is still initializing. Please try again.`,3500);else try{let e=await this.buildMessageDraftPayload(n);if(!e)return;t.value=``,this.#r=!0,q.setNearBottom(!0),v.sendMessage(e.text,e.attachments),this.#t=[],this.renderQueuedAttachments()}catch(e){let t=e instanceof Error?e.message:String(e);S(`Error sending message: ${t}`,6e3)}}}async showAttachmentDialog(e){let t=document.querySelector(`shadow-claw`);return t&&typeof t.requestDialog==`function`?await t.requestDialog(e):(e.mode||`confirm`)===`info`?(C(e.message,4500),!0):(C(`${e.title}: ${e.message}`,5e3),!1)}};customElements.get(We)||customElements.define(We,Ge);export{Ge as ShadowClawChat};
2428
+ `)}`:``}`,attachments:n}}async bypassPromptApiOnboardingToSettings(){let e=this.shadowRoot;if(!e)return;if(this.db||=await l(),this.db)try{await y(this.db,c.TRANSFORMERS_JS_ONBOARDING_SEEN,`true`),await y(this.db,c.PROMPT_API_ONBOARDING_SEEN,`true`)}catch(e){console.warn(`Failed to persist Prompt API onboarding status:`,e)}let t=e.querySelector(`shadow-claw-dialog[dialog-class="chat__prompt-api-dialog"]`);if(t&&typeof t.close==`function`)t.close();else{let t=e.querySelector(`dialog.chat__prompt-api-dialog`);t instanceof HTMLDialogElement&&t.close()}document.dispatchEvent(new CustomEvent(`shadow-claw-navigate`,{detail:{page:`settings`},bubbles:!0,composed:!0}))}async checkPromptApiOnboarding(){if((!E()||globalThis.__SHADOWCLAW_E2E_TEST_ONBOARDING__)&&(this.db||=await l(),this.db))try{let e=await f(this.db,c.PROVIDER);if((typeof e==`string`&&e.trim()?e.trim():`transformers_js_browser`)!==`transformers_js_browser`)return;let t=await f(this.db,c.TRANSFORMERS_JS_ONBOARDING_SEEN)||await f(this.db,c.PROMPT_API_ONBOARDING_SEEN);if(w(t,!1))return;let n=this.shadowRoot;if(!n)return;this.ensureShadowDialogs();let r=n.querySelector(`.chat__prompt-api-status-card`);r&&(r.hidden=!0);let i=n.querySelector(`.chat__prompt-api-fallback-card`);i&&(i.hidden=!1);let a=n.querySelector(`[data-setting="prompt-api-onboarding-fallback-model"]`);if(a){let e=await f(this.db,c.MODEL)||await f(this.db,c.PROMPT_API_FALLBACK_MODEL),t=typeof e==`string`&&e.trim()?e.trim():o.transformers_js_browser?.defaultModel||`onnx-community/Qwen3-0.6B-ONNX`;this.populateOnboardingModelSelect(a,t);let n=o.transformers_js_browser?.modelsUrl;if(n&&typeof fetch==`function`)try{let e=fetch(n);e&&typeof e.then==`function`&&e.then(e=>e&&e.ok?e.json():null).then(e=>{if(!e)return;let n=Array.isArray(e)?e:e.models||e.data||[];if(Array.isArray(n)&&n.length>0){let e=a.value||t;this.populateOnboardingModelSelect(a,e,n)}}).catch(()=>{})}catch{}}let s=n.querySelector(`shadow-claw-dialog[dialog-class="chat__prompt-api-dialog"]`);if(s&&typeof s.showModal==`function`)s.showModal();else{let e=n.querySelector(`dialog.chat__prompt-api-dialog`);e instanceof HTMLDialogElement&&(typeof e.showModal==`function`?e.showModal():e.setAttribute(`open`,``))}}catch(e){console.warn(`Failed to check Prompt API onboarding:`,e)}}populateOnboardingModelSelect(e,t,n){let r=O(t,n);i(e,r),e.value=t}async confirmPromptApiOnboarding(){let e=this.shadowRoot;if(!e)return;this.db||=await l();let t=e.querySelector(`[data-setting="prompt-api-onboarding-fallback-model"]`)?.value?.trim()||o.transformers_js_browser?.defaultModel||`onnx-community/Qwen3-0.6B-ONNX`;if(this.db)try{await y(this.db,c.PROVIDER,`transformers_js_browser`),await y(this.db,c.MODEL,t),await y(this.db,c.PROMPT_API_FALLBACK_MODEL,t),await y(this.db,c.TRANSFORMERS_JS_ONBOARDING_SEEN,`true`),await y(this.db,c.PROMPT_API_ONBOARDING_SEEN,`true`)}catch(e){console.warn(`Failed to persist Prompt API onboarding settings:`,e)}v.orchestrator&&(v.orchestrator.provider=`transformers_js_browser`,v.orchestrator.model=t);let n=e.querySelector(`shadow-claw-dialog[dialog-class="chat__prompt-api-dialog"]`);if(n&&typeof n.close==`function`)n.close();else{let t=e.querySelector(`dialog.chat__prompt-api-dialog`);t instanceof HTMLDialogElement&&t.close()}b(`Transformers.js configured`,2500)}async downloadAttachment(e,t){if(this.db&&t.path)try{await I(this.db,e,t.path)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to download attachment: ${t}`,5e3)}}async downloadChat(){if(this.db)try{let e=v.activeGroupId,t=await W(this.db,e);if(!t){S(`Failed to export chat data`,6e3);return}let n=new H.default;n.file(`chat-data.json`,JSON.stringify(t,null,2));let r=await n.generateAsync({type:`blob`}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=`chat-${R()}.zip`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i),b(`Chat backup downloaded`,3e3)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to download chat: ${t}`,6e3)}}async handleClearChat(){let e=this.shadowRoot;if(!e||!this.db)return;let t=e.querySelector(`.chat__messages`);t instanceof HTMLElement&&t.replaceChildren();try{await v.newSession(this.db)}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to clear session:`,t)}}async handleCompactChat(){if(this.db&&await this.showAttachmentDialog({mode:`confirm`,title:`Compact Conversation`,message:`This will summarize the conversation to reduce token usage. The summary replaces the current history. Continue?`,confirmLabel:`Compact`,cancelLabel:`Cancel`}))try{await v.compactContext(this.db),x(`Compacting context...`,2500)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to compact chat: ${t}`,6e3)}}async handleMessageLinkClick(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`a`);if(!(n instanceof HTMLAnchorElement))return;let i=n.getAttribute(`href`)||``,a=v.activeGroupId;r(i,``,a)&&e.preventDefault()}async handleStopChat(){try{v.stopCurrentRequest(),x(`Stopped current request`,2200)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to stop request: ${t}`,6e3)}}async openAttachment(e,t){if(this.db&&t.path)try{await B.openFile(this.db,t.path,e)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to open attachment: ${t}`,5e3)}}async persistInputAreaHeight(e){if(this.db)try{await y(this.db,c.CHAT_INPUT_AREA_HEIGHT,e)}catch{}}async queueDroppedData(e){if(!e)return;let t=this.buildQueuedAttachmentsFromFiles(Array.from(e.files||[])),n=await this.readDroppedPlainText(e);if(n){let e=n.trim();if(e){let n=new Blob([e],{type:`text/plain`});t.push({id:`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,fileName:`dropped-text-${(/* @__PURE__ */ new Date()).toISOString().slice(0,19).replace(/[:T]/g,`-`)}.txt`,mimeType:`text/plain`,size:n.size,source:{kind:`local-file`,file:n}})}}t.length!==0&&(this.#t=[...this.#t,...t],this.renderQueuedAttachments(),x(`Queued ${t.length} attachment${t.length===1?``:`s`}.`,2200))}async queueSelectedFiles(e){let t=Array.from(e.files||[]);if(t.length===0){e.value=``;return}let n=this.buildQueuedAttachmentsFromFiles(t);this.#t=[...this.#t,...n],this.renderQueuedAttachments(),x(`Queued ${n.length} attachment${n.length===1?``:`s`}.`,2200),e.value=``}async readDroppedPlainText(e){let t=Array.from(e.items||[]).find(e=>e.kind===`string`&&e.type===`text/plain`);return t?await new Promise(e=>{t.getAsString(t=>{e(t||``)})}):``}async renderInlineAttachmentPreview(e,t){if(!this.db||!t.path)return null;try{let n=await D(this.db,e.groupId,t.path),r=new Uint8Array(n.byteLength);r.set(n);let i=new Blob([r],{type:t.mimeType||`image/png`}),a=URL.createObjectURL(i);q.registerAttachmentObjectUrl(a);let o=document.createElement(`button`);o.className=`chat__attachment-preview-btn`,o.type=`button`,o.setAttribute(`aria-label`,`Open ${t.fileName}`),o.addEventListener(`click`,()=>{this.openAttachment(e.groupId,t)});let s=document.createElement(`img`);return s.className=`chat__attachment-preview`,s.alt=t.fileName,s.src=a,o.appendChild(s),o}catch(e){let t=document.createElement(`div`);return t.className=`chat__attachment-preview-error`,t.textContent=e instanceof Error?e.message:`Attachment preview unavailable.`,t}}async renderMessageAttachments(e){if(!Array.isArray(e.attachments)||e.attachments.length===0)return null;let t=document.createElement(`div`);t.className=`chat__attachments`;for(let n of e.attachments){let r=document.createElement(`section`);if(r.className=`chat__attachment`,P(n)&&n.path){let t=await this.renderInlineAttachmentPreview(e,n);t&&r.appendChild(t)}let i=document.createElement(`div`);i.className=`chat__attachment-meta`;let a=document.createElement(`div`);a.className=`chat__attachment-identity`;let o=document.createElement(`span`);o.className=`chat__attachment-icon`,o.setAttribute(`aria-hidden`,`true`),o.textContent=this.getAttachmentIcon(n.mimeType||``);let s=document.createElement(`button`);s.className=`chat__attachment-title`,s.type=`button`,s.textContent=n.fileName,s.disabled=!n.path||!this.db,s.addEventListener(`click`,()=>{this.openAttachment(e.groupId,n)}),a.append(o,s),i.appendChild(a);let c=document.createElement(`div`);c.className=`chat__attachment-subtitle`,c.textContent=this.formatAttachmentSubtitle(n),i.appendChild(c);let l=document.createElement(`div`);if(l.className=`chat__attachment-actions`,n.path&&this.db){let t=document.createElement(`button`);t.className=`chat__attachment-action`,t.type=`button`,t.textContent=`Open`,t.addEventListener(`click`,()=>{this.openAttachment(e.groupId,n)}),l.appendChild(t);let r=document.createElement(`button`);r.className=`chat__attachment-action`,r.type=`button`,r.textContent=`Download`,r.addEventListener(`click`,()=>{this.downloadAttachment(e.groupId,n)}),l.appendChild(r)}i.appendChild(l),r.appendChild(i),t.appendChild(r)}return t}async renderStreamingBubble(e){let t=++this.#i,n=this.getMessagesContainer();if(!n)return;let r=this.shouldAutoFollow(n);if(!(typeof e==`string`&&e.length>0)){this.removeStreamingBubble(n);return}let a=n.querySelector(`.chat__message--streaming`),o=null;if(!a){let e=g(`assistantName`)||`ShadowClaw`;a=document.createElement(`article`),a.className=`chat__message chat__message--assistant chat__message--streaming`;let t=document.createElement(`div`);t.className=`chat__message-header`;let r=document.createElement(`div`);r.className=`chat__message-sender`,r.textContent=e;let i=document.createElement(`div`);i.className=`chat__message-timestamp`,i.textContent=`streaming…`,t.append(r,i),o=document.createElement(`div`),o.className=`chat__message-content`,a.append(t,o),n.appendChild(a)}else if(o=a.querySelector(`.chat__message-content`),!(o instanceof HTMLElement))return;let s=p(e).replace(/\n/g,`<br>`).replace(/`([^`]+?)`/g,`<code>$1</code>`).replace(/\*\*([^*]+?)\*\*/g,`<b>$1</b>`);if(t!==this.#i)return;i(o,s);let c=document.createElement(`span`);c.setAttribute(`aria-hidden`,`true`),c.className=`chat__streaming-cursor`,o.append(c),a.querySelector(`.chat__msg-copy-btn`)?.remove(),this.injectMessageCopyButton(a,e),this.injectCopyButtons(o),r&&(this.setMessagesScrollTop(n,n.scrollHeight),q.setNearBottom(this.isContainerNearBottom(n)),this.persistGroupScrollState(n))}async resolveImagePaths(e,t){if(!this.db)return;let n=Array.from(t.querySelectorAll(`img`));for(let t of n){let n=t.getAttribute(`data-inline-workspace-src`)||t.getAttribute(`src`)||``,r=this.resolveWorkspaceLinkPath(n);if(r)try{let n=await D(this.db,e,r),i=new Uint8Array(n.byteLength);i.set(n);let a=r.toLowerCase();if(a.endsWith(`.pdf`)){let e=document.createElement(`shadow-claw-pdf-viewer`);e.file={name:r.split(`/`).pop()||`document.pdf`,binaryContent:i},t.replaceWith(e)}else{let e=`image/png`;a.endsWith(`.jpg`)||a.endsWith(`.jpeg`)?e=`image/jpeg`:a.endsWith(`.gif`)?e=`image/gif`:a.endsWith(`.webp`)?e=`image/webp`:a.endsWith(`.svg`)&&(e=`image/svg+xml`);let n=new Blob([i],{type:e}),r=URL.createObjectURL(n);q.registerAttachmentObjectUrl(r),t.addEventListener(`load`,()=>this.scrollMessagesToBottomIfNeeded(),{once:!0}),t.removeAttribute(`data-inline-workspace-src`),t.src=r}}catch(e){console.warn(`Failed to load inline image: ${r}`,e)}}let r=Array.from(t.querySelectorAll(`a[href]`));for(let t of r){let n=t.getAttribute(`href`)||``,r=this.resolveWorkspaceLinkPath(n);if(r&&r.toLowerCase().endsWith(`.pdf`))try{let n=await D(this.db,e,r),i=new Uint8Array(n.byteLength);i.set(n);let a=document.createElement(`shadow-claw-pdf-viewer`);a.file={name:r.split(`/`).pop()||`document.pdf`,binaryContent:i},t.insertAdjacentElement(`afterend`,a),requestAnimationFrame(()=>this.scrollMessagesToBottomIfNeeded()),setTimeout(()=>this.scrollMessagesToBottomIfNeeded(),120)}catch(e){console.warn(`Failed to load inline PDF: ${r}`,e)}}}async restoreChat(e){if(!this.db)return;let t=e.files?.[0];if(t){if(!t.name.endsWith(`.zip`))C(`Please select a .zip file`,3500),e.value=``;else try{let n=(await H.default.loadAsync(t)).file(`chat-data.json`);if(!n){S(`Invalid chat file: missing chat-data.json`,6e3),e.value=``;return}let r=await n.async(`string`),i=JSON.parse(r);if(!i.messages||!Array.isArray(i.messages)){S(`Invalid chat file: missing messages array`,6e3),e.value=``;return}let a=v.activeGroupId;await K(this.db,a,i),await v.loadHistory(),b(`Chat restored successfully`,3500)}catch(e){let t=e instanceof Error?e.message:String(e);S(`Failed to restore chat: ${t}`,6e3)}finally{e.value=``}}}async restoreInputAreaHeight(){let e=this.shadowRoot?.querySelector(`.chat__input-area`);if(e instanceof HTMLElement)try{let t=this.db?await f(this.db,c.CHAT_INPUT_AREA_HEIGHT):void 0;typeof t==`number`&&Number.isFinite(t)&&t>0&&(this.isCollapsedInputAreaHeight(t)?this.resetInputAreaHeight(e):this.setInputAreaHeight(e,t))}catch{}}async sendMessage(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.chat__input`);if(!(t instanceof HTMLTextAreaElement))return;let n=t.value.trim();if(n||this.#t.length!==0){if(!v.ready)C(`ShadowClaw is still initializing. Please try again.`,3500);else try{let e=await this.buildMessageDraftPayload(n);if(!e)return;t.value=``,this.#r=!0,q.setNearBottom(!0),v.sendMessage(e.text,e.attachments),this.#t=[],this.renderQueuedAttachments()}catch(e){let t=e instanceof Error?e.message:String(e);S(`Error sending message: ${t}`,6e3)}}}async showAttachmentDialog(e){let t=document.querySelector(`shadow-claw`);return t&&typeof t.requestDialog==`function`?await t.requestDialog(e):(e.mode||`confirm`)===`info`?(C(e.message,4500),!0):(C(`${e.title}: ${e.message}`,5e3),!1)}};customElements.get(We)||customElements.define(We,Ge);export{Ge as ShadowClawChat};
@@ -1,4 +1,4 @@
1
- import{r as e}from"./config-C-YdSFZB.js";import{n as t}from"./db-BUuJo1Gf.js";import{t as n}from"./get-config-Bkvl__ZS.js";import{t as r}from"./orchestrator-CaUpEVkQ.js";import{t as i}from"./set-config-DSiuMe0k.js";import{a,r as o}from"./toast-CtIuHprH.js";import{a as s,o as c}from"./shadow-claw-DdgeYPg5.js";const l=new CSSStyleSheet;l.replaceSync(`*,
1
+ import{r as e}from"./config-C16fFWtP.js";import{n as t}from"./db-BUuJo1Gf.js";import{t as n}from"./get-config-Bkvl__ZS.js";import{t as r}from"./orchestrator-DBO4NZqd.js";import{t as i}from"./set-config-DSiuMe0k.js";import{a,r as o}from"./toast-CtIuHprH.js";import{a as s,o as c}from"./shadow-claw-Br8mWDUx.js";const l=new CSSStyleSheet;l.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  font-family: var(--shadow-claw-font-sans);
@@ -240,4 +240,4 @@ import{r as e}from"./config-C-YdSFZB.js";import{n as t}from"./db-BUuJo1Gf.js";im
240
240
  </div>
241
241
  </div>
242
242
  </template>
243
- `,`text/html`),d=u.querySelector(`template`);let f=[];f=d?Array.from(d.content.children):Array.from(u.head.children).concat(Array.from(u.body.children));var p=f;const m=`shadow-claw-control-plane`;function h(e){try{let t=new URL(e).hostname.toLowerCase();if(t===`localhost`||t===`127.0.0.1`||t===`::1`||t===`[::1]`)return`loopback`;if(/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(t)||!t.includes(`.`)||t.endsWith(`.local`)||t.endsWith(`.lan`)||t.endsWith(`.home`)||t.endsWith(`.internal`))return`private`}catch{}}var g=class extends c{static styles=l;static template=p;db;orchestrator;constructor(){super(),this.db=null,this.orchestrator=null}async connectedCallback(){if(!this.shadowRoot)throw Error(`shadowRoot not found`);this.db=await t(),this.orchestrator=r.orchestrator,this.bindEventListeners(),this.setupEffects(),await this.render()}bindEventListeners(){let e=this.shadowRoot;e&&(e.querySelector(`[data-action="save-control-plane-transport"]`)?.addEventListener(`click`,()=>{this.saveControlPlaneTransport()}),e.querySelector(`[data-action="save-control-plane-url"]`)?.addEventListener(`click`,()=>{this.saveControlPlaneUrl()}),e.querySelector(`[data-action="test-control-plane-connection"]`)?.addEventListener(`click`,()=>{this.testControlPlaneConnection()}),e.querySelector(`[data-setting="control-plane-enabled-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;this.saveControlPlaneEnabled(t.checked)}))}setupEffects(){s(()=>{r.ready&&(this.orchestrator=r.orchestrator,this.render())})}async probeControlPlane(e){let t;try{t=new URL(e)}catch{return{success:!1,error:`Invalid URL format: "${e}"`}}let n=h(e),r={method:`GET`,cache:`no-store`,mode:`cors`};n&&(r.targetAddressSpace=n);try{let e=new URL(`/api/control/health`,t).toString(),n=await fetch(e,r);if(n.status===404){let e=new URL(`/api/control/messages`,t).toString();n=await fetch(e,{...r,method:`OPTIONS`})}return n.ok||n.status===204||n.status===401?{success:!0}:{success:!1,error:`Server responded with HTTP ${n.status} (${n.statusText||`Error`})`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async render(){let t=this.shadowRoot;if(!t)return;let r=t.querySelector(`[data-setting="control-plane-enabled-toggle"]`);if(r&&this.db)try{let{isControlPlaneEnabled:e}=await import(`./init-control-plane-BoJijVtf.js`);r.checked=await e(this.db)}catch{r.checked=!1}let i=t.querySelector(`[data-setting="control-plane-url-input"]`);if(i&&this.db)try{i.value=await n(this.db,e.CONTROL_PLANE_URL)||``}catch{i.value=``}let a=t.querySelector(`[data-setting="control-plane-transport-select"]`);if(a&&this.db)try{a.value=await n(this.db,e.CONTROL_PLANE_TRANSPORT)||`sse`}catch{a.value=`sse`}}async requestAppDialog(e){let t=document.querySelector(`shadow-claw`);return t&&typeof t.requestDialog==`function`?await t.requestDialog(e):!1}async saveControlPlaneEnabled(t){if(this.db)try{if(t){let t=await n(this.db,e.CONTROL_PLANE_URL)||`http://127.0.0.1:8888`;this.probeControlPlane(t)}if(await i(this.db,e.CONTROL_PLANE_ENABLED,t?`true`:`false`),typeof localStorage<`u`)try{localStorage.setItem(e.CONTROL_PLANE_ENABLED,t?`true`:`false`)}catch{}let{ensureControlPlaneConnected:r,stopControlPlaneClient:o,shouldConnectControlPlane:s}=await import(`./init-control-plane-BoJijVtf.js`);t?(s()&&await r({orchestrator:this.orchestrator||void 0,db:this.db,force:!0}),a(`Control plane client enabled and connected`,3e3)):(o(),a(`Control plane client disabled`,3e3))}catch(e){let t=e instanceof Error?e.message:String(e);o(`Error saving Control Plane setting: `+t,6e3)}}async saveControlPlaneTransport(){if(!this.db)return;let t=this.shadowRoot;if(!t)return;let n=t.querySelector(`[data-setting="control-plane-transport-select"]`);if(!n)return;let r=n.value===`websocket`?`websocket`:`sse`;try{if(await i(this.db,e.CONTROL_PLANE_TRANSPORT,r),typeof localStorage<`u`)try{localStorage.setItem(e.CONTROL_PLANE_TRANSPORT,r)}catch{}let{isControlPlaneEnabled:t,ensureControlPlaneConnected:n,shouldConnectControlPlane:o}=await import(`./init-control-plane-BoJijVtf.js`);await t(this.db)&&o()&&await n({orchestrator:this.orchestrator||void 0,db:this.db,force:!0,transport:r}),a(`Control Plane transport saved: ${r.toUpperCase()}`,3e3)}catch(e){let t=e instanceof Error?e.message:String(e);o(`Error saving Control Plane transport: `+t,6e3)}}async saveControlPlaneUrl(){if(!this.db)return;let t=this.shadowRoot;if(!t)return;let n=t.querySelector(`[data-setting="control-plane-url-input"]`);if(!n)return;let r=n.value.trim();try{if(r&&this.probeControlPlane(r),await i(this.db,e.CONTROL_PLANE_URL,r),typeof localStorage<`u`)try{r?localStorage.setItem(e.CONTROL_PLANE_URL,r):localStorage.removeItem(e.CONTROL_PLANE_URL)}catch{}let{isControlPlaneEnabled:t,ensureControlPlaneConnected:n,shouldConnectControlPlane:o}=await import(`./init-control-plane-BoJijVtf.js`);await t(this.db)&&o()&&await n({orchestrator:this.orchestrator||void 0,db:this.db,force:!0}),a(r?`Control Plane URL saved: ${r}`:`Control Plane URL reset to default`,3e3)}catch(e){let t=e instanceof Error?e.message:String(e);o(`Error saving Control Plane URL: `+t,6e3)}}async testControlPlaneConnection(){let e=this.shadowRoot;if(!e)return!1;let t=e.querySelector(`[data-setting="control-plane-url-input"]`),n=e.querySelector(`[data-action="test-control-plane-connection"]`),r=t?.value.trim()||`http://127.0.0.1:8888`;n&&(n.disabled=!0,n.textContent=`⏳ Testing...`);try{let e=await this.probeControlPlane(r);if(e.success)return a(`Successfully reached Control Plane at ${r}`,4e3),!0;let t=e.error||`Unknown connection error`;return o(`Connection test failed: ${t}`,6e3),await this.requestAppDialog({title:`Control Plane Connection Failed`,message:`Unable to connect to "${r}".\n\n• TLS / Certificate: If using HTTPS with a self-signed certificate, ensure the certificate is installed and trusted in Chrome (chrome://certificate-manager/localcerts/usercerts).\n• Chrome Permissions: In Site Settings, ensure "Local network access" is allowed.\n• Server Status: Verify the ShadowClaw dev server is running and listening on this host/port.`,confirmLabel:`OK`}),!1}finally{n&&(n.disabled=!1,n.textContent=`🔌 Test Connection`)}}};customElements.get(m)||customElements.define(m,g);export{g as ShadowClawControlPlane,h as getControlPlaneTargetAddressSpace};
243
+ `,`text/html`),d=u.querySelector(`template`);let f=[];f=d?Array.from(d.content.children):Array.from(u.head.children).concat(Array.from(u.body.children));var p=f;const m=`shadow-claw-control-plane`;function h(e){try{let t=new URL(e).hostname.toLowerCase();if(t===`localhost`||t===`127.0.0.1`||t===`::1`||t===`[::1]`)return`loopback`;if(/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(t)||!t.includes(`.`)||t.endsWith(`.local`)||t.endsWith(`.lan`)||t.endsWith(`.home`)||t.endsWith(`.internal`))return`private`}catch{}}var g=class extends c{static styles=l;static template=p;db;orchestrator;constructor(){super(),this.db=null,this.orchestrator=null}async connectedCallback(){if(!this.shadowRoot)throw Error(`shadowRoot not found`);this.db=await t(),this.orchestrator=r.orchestrator,this.bindEventListeners(),this.setupEffects(),await this.render()}bindEventListeners(){let e=this.shadowRoot;e&&(e.querySelector(`[data-action="save-control-plane-transport"]`)?.addEventListener(`click`,()=>{this.saveControlPlaneTransport()}),e.querySelector(`[data-action="save-control-plane-url"]`)?.addEventListener(`click`,()=>{this.saveControlPlaneUrl()}),e.querySelector(`[data-action="test-control-plane-connection"]`)?.addEventListener(`click`,()=>{this.testControlPlaneConnection()}),e.querySelector(`[data-setting="control-plane-enabled-toggle"]`)?.addEventListener(`change`,e=>{let t=e.target;this.saveControlPlaneEnabled(t.checked)}))}setupEffects(){s(()=>{r.ready&&(this.orchestrator=r.orchestrator,this.render())})}async probeControlPlane(e){let t;try{t=new URL(e)}catch{return{success:!1,error:`Invalid URL format: "${e}"`}}let n=h(e),r={method:`GET`,cache:`no-store`,mode:`cors`};n&&(r.targetAddressSpace=n);try{let e=new URL(`/api/control/health`,t).toString(),n=await fetch(e,r);if(n.status===404){let e=new URL(`/api/control/messages`,t).toString();n=await fetch(e,{...r,method:`OPTIONS`})}return n.ok||n.status===204||n.status===401?{success:!0}:{success:!1,error:`Server responded with HTTP ${n.status} (${n.statusText||`Error`})`}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async render(){let t=this.shadowRoot;if(!t)return;let r=t.querySelector(`[data-setting="control-plane-enabled-toggle"]`);if(r&&this.db)try{let{isControlPlaneEnabled:e}=await import(`./init-control-plane-Cb31yLTY.js`);r.checked=await e(this.db)}catch{r.checked=!1}let i=t.querySelector(`[data-setting="control-plane-url-input"]`);if(i&&this.db)try{i.value=await n(this.db,e.CONTROL_PLANE_URL)||``}catch{i.value=``}let a=t.querySelector(`[data-setting="control-plane-transport-select"]`);if(a&&this.db)try{a.value=await n(this.db,e.CONTROL_PLANE_TRANSPORT)||`sse`}catch{a.value=`sse`}}async requestAppDialog(e){let t=document.querySelector(`shadow-claw`);return t&&typeof t.requestDialog==`function`?await t.requestDialog(e):!1}async saveControlPlaneEnabled(t){if(this.db)try{if(t){let t=await n(this.db,e.CONTROL_PLANE_URL)||`http://127.0.0.1:8888`;this.probeControlPlane(t)}if(await i(this.db,e.CONTROL_PLANE_ENABLED,t?`true`:`false`),typeof localStorage<`u`)try{localStorage.setItem(e.CONTROL_PLANE_ENABLED,t?`true`:`false`)}catch{}let{ensureControlPlaneConnected:r,stopControlPlaneClient:o,shouldConnectControlPlane:s}=await import(`./init-control-plane-Cb31yLTY.js`);t?(s()&&await r({orchestrator:this.orchestrator||void 0,db:this.db,force:!0}),a(`Control plane client enabled and connected`,3e3)):(o(),a(`Control plane client disabled`,3e3))}catch(e){let t=e instanceof Error?e.message:String(e);o(`Error saving Control Plane setting: `+t,6e3)}}async saveControlPlaneTransport(){if(!this.db)return;let t=this.shadowRoot;if(!t)return;let n=t.querySelector(`[data-setting="control-plane-transport-select"]`);if(!n)return;let r=n.value===`websocket`?`websocket`:`sse`;try{if(await i(this.db,e.CONTROL_PLANE_TRANSPORT,r),typeof localStorage<`u`)try{localStorage.setItem(e.CONTROL_PLANE_TRANSPORT,r)}catch{}let{isControlPlaneEnabled:t,ensureControlPlaneConnected:n,shouldConnectControlPlane:o}=await import(`./init-control-plane-Cb31yLTY.js`);await t(this.db)&&o()&&await n({orchestrator:this.orchestrator||void 0,db:this.db,force:!0,transport:r}),a(`Control Plane transport saved: ${r.toUpperCase()}`,3e3)}catch(e){let t=e instanceof Error?e.message:String(e);o(`Error saving Control Plane transport: `+t,6e3)}}async saveControlPlaneUrl(){if(!this.db)return;let t=this.shadowRoot;if(!t)return;let n=t.querySelector(`[data-setting="control-plane-url-input"]`);if(!n)return;let r=n.value.trim();try{if(r&&this.probeControlPlane(r),await i(this.db,e.CONTROL_PLANE_URL,r),typeof localStorage<`u`)try{r?localStorage.setItem(e.CONTROL_PLANE_URL,r):localStorage.removeItem(e.CONTROL_PLANE_URL)}catch{}let{isControlPlaneEnabled:t,ensureControlPlaneConnected:n,shouldConnectControlPlane:o}=await import(`./init-control-plane-Cb31yLTY.js`);await t(this.db)&&o()&&await n({orchestrator:this.orchestrator||void 0,db:this.db,force:!0}),a(r?`Control Plane URL saved: ${r}`:`Control Plane URL reset to default`,3e3)}catch(e){let t=e instanceof Error?e.message:String(e);o(`Error saving Control Plane URL: `+t,6e3)}}async testControlPlaneConnection(){let e=this.shadowRoot;if(!e)return!1;let t=e.querySelector(`[data-setting="control-plane-url-input"]`),n=e.querySelector(`[data-action="test-control-plane-connection"]`),r=t?.value.trim()||`http://127.0.0.1:8888`;n&&(n.disabled=!0,n.textContent=`⏳ Testing...`);try{let e=await this.probeControlPlane(r);if(e.success)return a(`Successfully reached Control Plane at ${r}`,4e3),!0;let t=e.error||`Unknown connection error`;return o(`Connection test failed: ${t}`,6e3),await this.requestAppDialog({title:`Control Plane Connection Failed`,message:`Unable to connect to "${r}".\n\n• TLS / Certificate: If using HTTPS with a self-signed certificate, ensure the certificate is installed and trusted in Chrome (chrome://certificate-manager/localcerts/usercerts).\n• Chrome Permissions: In Site Settings, ensure "Local network access" is allowed.\n• Server Status: Verify the ShadowClaw dev server is running and listening on this host/port.`,confirmLabel:`OK`}),!1}finally{n&&(n.disabled=!1,n.textContent=`🔌 Test Connection`)}}};customElements.get(m)||customElements.define(m,g);export{g as ShadowClawControlPlane,h as getControlPlaneTargetAddressSpace};
@@ -1,4 +1,4 @@
1
- import{p as e}from"./custom-element-security-kiDhPfb8.js";import{r as t}from"./config-C-YdSFZB.js";import{n}from"./db-BUuJo1Gf.js";import{t as r}from"./get-config-Bkvl__ZS.js";import{t as i}from"./orchestrator-CaUpEVkQ.js";import{t as a}from"./set-config-DSiuMe0k.js";import{i as o,t as s}from"./tools-DHA1dK2I.js";import{t as c}from"./tools-CHxUdGxZ.js";import"./tools-C4xNCwrc.js";import{l,o as u}from"./provider-DNIL4-Hw.js";import{r as d}from"./model-ranking-CK0iBo3Z.js";import"./shadow-claw-dialog-BVGf_c3S.js";import{a as f,o as p}from"./shadow-claw-DdgeYPg5.js";const m=new CSSStyleSheet;m.replaceSync(`:host {
1
+ import{p as e}from"./custom-element-security-B2daIE5r.js";import{r as t}from"./config-C16fFWtP.js";import{n}from"./db-BUuJo1Gf.js";import{t as r}from"./get-config-Bkvl__ZS.js";import{t as i}from"./orchestrator-DBO4NZqd.js";import{t as a}from"./set-config-DSiuMe0k.js";import{i as o,t as s}from"./tools-D-52Zmfc.js";import{t as c}from"./tools-CHxUdGxZ.js";import"./tools-C4xNCwrc.js";import{l,o as u}from"./provider-YPZmsuHR.js";import{r as d}from"./model-ranking-BgOSaNIy.js";import"./shadow-claw-dialog-BVGf_c3S.js";import{a as f,o as p}from"./shadow-claw-Br8mWDUx.js";const m=new CSSStyleSheet;m.replaceSync(`:host {
2
2
  display: block;
3
3
  }
4
4
 
@@ -1,4 +1,4 @@
1
- import{o as e}from"./shadow-claw-DdgeYPg5.js";const t=new CSSStyleSheet;t.replaceSync(`:host {
1
+ import{o as e}from"./shadow-claw-Br8mWDUx.js";const t=new CSSStyleSheet;t.replaceSync(`:host {
2
2
  display: block;
3
3
  }
4
4
 
@@ -1,4 +1,4 @@
1
- import{a as e,c as t,d as n,f as r,h as i,i as a,m as o,o as s,p as c,r as l,s as u,w as d}from"./custom-element-security-kiDhPfb8.js";import{r as f}from"./config-C-YdSFZB.js";import{c as p,i as m,n as h,p as g,s as _,u as v}from"./app-routes-V_-URXc5.js";import{n as y}from"./db-BUuJo1Gf.js";import{t as b}from"./get-config-Bkvl__ZS.js";import{t as x}from"./orchestrator-CaUpEVkQ.js";import{t as S}from"./tools-DHA1dK2I.js";import{t as C}from"./write-group-file-CmJuVQNO.js";import{a as w,r as T}from"./toast-CtIuHprH.js";import{t as ee}from"./parse-boolean-config-BigJ9U46.js";import{a as E}from"./transformers-C-DuTM2K.js";import{t as D}from"./mime-ClqNyXPc.js";import{r as O}from"./frontmatter-BH0hi8ok.js";import{renderMarkdown as k,t as A}from"./markdown-CPbU4r1U.js";import"./shadow-claw-dialog-BVGf_c3S.js";import{a as j,c as M,d as N,f as P,i as F,l as I,n as L,o as R,r as z,s as B,t as V,u as H}from"./iframe-bridge-scripts-BnqtKhE4.js";import{a as U,n as W,o as G}from"./shadow-claw-DdgeYPg5.js";const K=new CSSStyleSheet;K.replaceSync(`*,
1
+ import{a as e,c as t,d as n,f as r,h as i,i as a,m as o,o as s,p as c,r as l,s as u,w as d}from"./custom-element-security-B2daIE5r.js";import{G as f,V as p,W as m,X as h,q as g,r as _,z as v}from"./config-C16fFWtP.js";import{n as y}from"./db-BUuJo1Gf.js";import{t as b}from"./get-config-Bkvl__ZS.js";import{t as x}from"./orchestrator-DBO4NZqd.js";import{t as S}from"./tools-D-52Zmfc.js";import{t as C}from"./write-group-file-R67DjJ-q.js";import{a as w,r as T}from"./toast-CtIuHprH.js";import{t as ee}from"./parse-boolean-config-BigJ9U46.js";import{a as E}from"./transformers-CQ9ss9rD.js";import{t as D}from"./mime-ClqNyXPc.js";import{r as O}from"./frontmatter-BH0hi8ok.js";import{renderMarkdown as k,t as A}from"./markdown-CDSb5Hrl.js";import"./shadow-claw-dialog-BVGf_c3S.js";import{a as j,c as M,d as N,f as P,i as F,l as I,n as L,o as R,r as z,s as B,t as V,u as H}from"./iframe-bridge-scripts-Cibg0m6A.js";import{a as U,n as W,o as G}from"./shadow-claw-Br8mWDUx.js";const K=new CSSStyleSheet;K.replaceSync(`*,
2
2
  *::before,
3
3
  *::after {
4
4
  box-sizing: border-box;
@@ -868,8 +868,8 @@ code.hljs {
868
868
  :host-context(.light-mode) .hljs-title.class_ {
869
869
  color: #c18401;
870
870
  }
871
- `)}}disconnectedCallback(){this.broadcastProxy?.dispose(),this.broadcastProxy=null,window.removeEventListener(`message`,this.handleIframeMessage),document.removeEventListener(`fullscreenchange`,this.handleFullscreenChange),this.themeObserver&&=(this.themeObserver.disconnect(),null),this.revokeObjectUrl()}applyFullscreenMode(e){let t=e.querySelector(`.modal-content`);t instanceof HTMLElement&&t.classList.toggle(`modal-content--fullscreen`,this.isFullscreenMode);let n=e.querySelector(`.modal-fullscreen-btn`);n instanceof HTMLButtonElement&&(n.setAttribute(`aria-pressed`,String(this.isFullscreenMode)),n.setAttribute(`aria-label`,this.isFullscreenMode?`Exit fullscreen`:`Enter fullscreen`),n.title=this.isFullscreenMode?`Exit fullscreen`:`Fullscreen`)}applyHighlightStyles(e){let t=this.shadowRoot;if(!t)return;if(typeof CSSStyleSheet<`u`&&typeof CSSStyleSheet.prototype.replaceSync==`function`&&`adoptedStyleSheets`in t)try{let n=new CSSStyleSheet;n.replaceSync(e);let r=new CSSStyleSheet;r.replaceSync(Z),t.adoptedStyleSheets=[...t.adoptedStyleSheets?Array.from(t.adoptedStyleSheets):[],n,r];return}catch{}let n=document.createElement(`style`);n.setAttribute(`data-shadow-claw-highlight-theme`,`true`),n.textContent=`${e}\n${Z}`,t.appendChild(n)}bindEventListeners(){let e=this.shadowRoot;if(!e)return;e.querySelector(`.file-content`)?.addEventListener(`click`,e=>{this.handlePreviewLinkClick(e)});let t=e.querySelector(`.file-modal`);t?.addEventListener(`cancel`,e=>{e.preventDefault(),this.requestCloseViewer()}),t?.addEventListener(`close`,()=>{W.file&&W.closeFile()}),e.querySelector(`.modal-close-btn`)?.addEventListener(`click`,()=>void this.requestCloseViewer()),e.querySelector(`.modal-preview-btn`)?.addEventListener(`click`,async()=>{this.isFilePreviewMode=!this.isFilePreviewMode,this.isFileEditMode=!1,await this.updateView()}),e.querySelector(`.modal-fullscreen-btn`)?.addEventListener(`click`,()=>{t&&this.toggleFullscreenMode(t)}),e.querySelector(`.modal-share-btn`)?.addEventListener(`click`,async()=>{await this.handleShareFile()});let n=e.querySelector(`.modal-share-dropdown`),r=e.querySelector(`.modal-share-peer-btn`),i=e.querySelector(`.modal-share-device-btn`);r?.addEventListener(`click`,async()=>{n instanceof HTMLDetailsElement&&n.removeAttribute(`open`),await this.handleSendFileToPeer()}),i?.addEventListener(`click`,async()=>{n instanceof HTMLDetailsElement&&n.removeAttribute(`open`),await this.handleShareFile()}),e.addEventListener(`click`,e=>{if(n instanceof HTMLDetailsElement&&n.open){let t=e.target;n.contains(t)||n.removeAttribute(`open`)}}),e.querySelector(`.modal-edit-btn`)?.addEventListener(`click`,async()=>{this.isFileEditMode=!this.isFileEditMode,this.isFileEditMode&&(this.isFilePreviewMode=!1),await this.updateView()}),e.querySelector(`.modal-save-btn`)?.addEventListener(`click`,()=>this.handleSave()),e.querySelector(`.modal-cancel-btn`)?.addEventListener(`click`,async()=>{this.isEditorDirty=!1,this.editorDraftContent=null,this.isFileEditMode=!1,await this.updateView()});let a=e.querySelector(`.file-editor`);if(a?.addEventListener(`input`,()=>{a instanceof HTMLTextAreaElement&&(this.editorDraftContent=a.value,this.updateEditorHighlight(a.value)),this.isEditorDirty=!0,this.updateView()}),a instanceof HTMLTextAreaElement){let t=()=>{let t=e.querySelector(`.file-editor-overlay`);t&&(t.scrollTop=a.scrollTop,t.scrollLeft=a.scrollLeft)};a.addEventListener(`scroll`,t),a.addEventListener(`focus`,t),a.addEventListener(`click`,t),a.addEventListener(`keyup`,t),a.addEventListener(`mouseup`,t),e.querySelector(`.modal-body`)?.addEventListener(`scroll`,t)}}buildWebShareFile(e){if(e?.nativeFile instanceof File)return e.nativeFile;let t=e?.binaryContent;if(!(t instanceof Uint8Array)||t.length===0)return null;let n=new Uint8Array(t.byteLength);return n.set(t),new File([n],e.name||`shared-file`,{type:e?.mimeType||`application/octet-stream`})}canShareCurrentFile(e){if(!e||!this.isWebShareAvailable())return!1;if(e.kind===`text`)return!0;let t=this.buildWebShareFile(e);if(!t||typeof navigator.canShare!=`function`)return!1;try{return navigator.canShare({files:[t]})}catch{return!1}}canUseNativeFullscreen(e){return document.fullscreenEnabled===!0&&(typeof e.requestFullscreen==`function`||typeof e.webkitRequestFullscreen==`function`)&&(typeof document.exitFullscreen==`function`||typeof document.webkitExitFullscreen==`function`)}getCurrentFullscreenElement(){return document.fullscreenElement||document.webkitFullscreenElement||null}getFullscreenTarget(e){let t=e.querySelector(`.modal-content`);return t instanceof HTMLElement?t:null}getIframeBridgeScriptUrl(){return n(`/assets/file-viewer-preview-bridge.js`)}getIframeSandboxPermissions(t){return/\.svg$/i.test(t)?`allow-modals allow-popups allow-popups-to-escape-sandbox`:e()}getLanguageFromFilename(e){return{bash:`bash`,cjs:`javascript`,css:`css`,html:`xml`,java:`java`,javascript:`javascript`,js:`javascript`,json:`json`,jsx:`jsx`,markdown:`markdown`,md:`markdown`,mjs:`javascript`,php:`php`,python:`python`,py:`python`,ruby:`ruby`,rb:`ruby`,rust:`rust`,rs:`rust`,sh:`bash`,sql:`sql`,svg:`xml`,ts:`typescript`,tsx:`tsx`,xml:`xml`,yaml:`yaml`,yml:`yaml`}[e.toLowerCase().split(`.`).pop()||``]||``}getPreviewSourceFile(e,t){return this.getWorkingSourceFile(e,t)}getWorkingSourceFile(e,t){if(!this.isEditorDirty||e?.kind!==`text`)return e;if(typeof this.editorDraftContent==`string`)return{...e,content:this.editorDraftContent};let n=t.querySelector(`.file-editor`);return n instanceof HTMLTextAreaElement?{...e,content:n.value}:e}getWorkspaceRouteTarget(e,t={}){let{allowCrossGroup:n=!1}=t,r=e.split(/[?#]/,1)[0].trim();if(!r)return null;if(/^[a-zA-Z][a-zA-Z\d+.-]*:/u.test(r)||r.startsWith(`//`)){let e;try{e=new URL(r,window.location.href)}catch{return null}if(e.origin!==window.location.origin)return null;r=e.pathname}let i=r.replace(/^(?:\.\/)+/u,``),a=[];if(i.startsWith(`files/`)&&a.push(`/${i}`),r.startsWith(`/`)){let e=r.lastIndexOf(`/files/`);e>0&&a.push(r.slice(e)),a.push(r)}for(let e of a){let t=p(e);if(!t)continue;let r=this.resolveRouteGroupId(t.groupId);if(r&&(n||r===x.activeGroupId))return{groupId:r,path:t.path}}return null}handleAnchorNavigation(e){let t=this.shadowRoot;if(!t)return!1;let n=t.querySelector(`.file-content`);if(!n)return!1;n.querySelectorAll(`.code-line.highlighted`).forEach(e=>{e.classList.remove(`highlighted`)});let r=e.match(/^#?L(\d+)(?:-L?(\d+))?$/i);if(r){let e=parseInt(r[1],10),t=r[2]?parseInt(r[2],10):e,i=null;return n.querySelectorAll(`.code-line`).forEach(n=>{let r=parseInt(n.getAttribute(`data-line`)||`0`,10);r>=e&&r<=t&&(n.classList.add(`highlighted`),i||=n)}),i?(i.scrollIntoView({behavior:`smooth`,block:`center`}),!0):!1}{let t=e.replace(/^#/,``),r=n.querySelector(`[id="${t}"]`)||n.querySelector(`a[name="${t}"]`);return r?(r.scrollIntoView({behavior:`smooth`,block:`start`}),!0):!1}}handleFullscreenChange=()=>{let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.file-modal`);if(!(t instanceof HTMLElement))return;let n=this.getFullscreenTarget(t);this.isFullscreenMode=this.isTargetInFullscreen(n),this.applyFullscreenMode(t)};handleIframeMessage=e=>{if(!e.data||typeof e.data!=`object`)return;let t=e.data;if(t.type===`shadow-claw-broadcast-result`&&typeof t.channel==`string`){this.broadcastProxy?.handleResultFromIframe(e.source,t.channel,t.payload);return}if(t.type===`shadow-claw-iframe-resize`&&typeof t.height==`number`){let n=this.shadowRoot?.querySelector(`.file-content-iframe`);n instanceof HTMLIFrameElement&&(!this.previewFrameWindow||e.source===this.previewFrameWindow||n.contentWindow&&e.source===n.contentWindow)&&(this.previewFrameWindow=n.contentWindow,n.style.setProperty(`height`,`${t.height}px`,`important`));return}if(t.type===`shadow-claw-storage-proxy`){if(this.previewFrameWindow&&e.source!==this.previewFrameWindow)return;let n=t;this.handleStorageProxyRequest(e.source,String(n.requestId||``),String(n.method||``),n.args&&typeof n.args==`object`?n.args:{});return}if(!this.db||t.type!==`shadow-claw-file-viewer-link`||typeof t.href!=`string`||this.previewFrameWindow&&e.source!==this.previewFrameWindow)return;let n=W.file,r=n?.path||n?.name||``,i=h(_(x.activeGroupId,r)),a=g(t.href,i,window.location.origin);if(!a)return;if(a.searchParams.has(`gameSave`)){this.reloadPreviewWithSearchParams(a.search);return}if(a.origin!==window.location.origin||!v(a.pathname)&&!this.resolveWorkspaceLinkPath(t.href,r)){window.open(a.href,`_blank`,`noopener,noreferrer`);return}let o=`${a.pathname}${a.search}${a.hash}`,s=window.navigation;s&&typeof s.navigate==`function`?s.navigate(o):(window.history.pushState({},``,o),window.dispatchEvent(new PopStateEvent(`popstate`)))};hasUnsavedChanges(){return this.isEditorDirty}isIframePreviewFile(e){return/\.(?:html?|svg)$/i.test(e)}isMarkdownLikeFile(e){return/(?:^readme$|\.mdx?$|\.markdown$|\.mdown$)/i.test(e)}isNodeInComposedTree(e,t){let n=e;for(;n;){if(n===t)return!0;if(n.parentNode){n=n.parentNode;continue}let e=n.getRootNode?.();n=e instanceof ShadowRoot&&e.host?e.host:null}return!1}isRenderTokenCurrent(e){return this.viewRenderToken===e}isTargetInFullscreen(e){if(!e)return!1;let t=this.getCurrentFullscreenElement();return t?t===e||this.isNodeInComposedTree(e,t)||this.isNodeInComposedTree(t,e):!1}isWebShareAvailable(){return typeof navigator<`u`&&typeof navigator.share==`function`}mimeTypeForImageExt(e){return D(e)??`image/jpeg`}renderBinaryPreview(e,t){let n=t.mimeType||`application/octet-stream`;if(t.nativeFile instanceof File)this.currentObjectUrl=URL.createObjectURL(t.nativeFile);else{let r=t.binaryContent;if(!(r instanceof Uint8Array)||r.length===0){e.classList.remove(`file-content--raw`,`file-content--iframe`),e.classList.add(`file-content--preview`),e.textContent=`Binary content unavailable.`;return}let i=new Uint8Array(r.byteLength);i.set(r);let a=new Blob([i],{type:n});this.currentObjectUrl=URL.createObjectURL(a)}if(e.classList.remove(`file-content--raw`,`file-content--preview`),e.classList.add(`file-content--iframe`),n.startsWith(`image/`)){let n=document.createElement(`img`);n.className=`file-content-iframe`,n.alt=`Preview: ${t.name}`,n.src=this.currentObjectUrl,n.style.objectFit=`contain`,e.replaceChildren(n);return}if(n.startsWith(`video/`)){let t=document.createElement(`video`);t.className=`file-content-iframe`,t.controls=!0,t.src=this.currentObjectUrl,t.style.backgroundColor=`black`,e.replaceChildren(t);return}if(n.startsWith(`audio/`)){let n=document.createElement(`div`);n.className=`file-content file-content--preview`,n.style.padding=`1rem`;let r=document.createElement(`p`);r.textContent=t.name;let i=document.createElement(`audio`);i.controls=!0,i.src=this.currentObjectUrl,i.style.width=`100%`,n.replaceChildren(r,i),e.replaceChildren(n),e.classList.remove(`file-content--iframe`);return}let r=document.createElement(`iframe`);r.className=`file-content-iframe`,r.setAttribute(`title`,`Preview: ${t.name}`),r.setAttribute(`referrerpolicy`,`no-referrer`),r.src=this.currentObjectUrl,e.replaceChildren(r)}resetContent(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.file-modal`);if(!(t instanceof HTMLElement))return;let n=this.getFullscreenTarget(t);n&&this.isTargetInFullscreen(n)&&this.exitNativeFullscreen().catch(()=>{}),this.isFullscreenMode=!1,this.applyFullscreenMode(t);let r=t.querySelector(`.file-content`),i=t.querySelector(`.modal-preview-btn`);i instanceof HTMLButtonElement&&(i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`aria-label`,`Switch to preview mode`));let a=t.querySelector(`.modal-edit-btn`);a instanceof HTMLButtonElement&&(a.setAttribute(`aria-pressed`,`false`),a.setAttribute(`aria-label`,`Edit file`),a.classList.remove(`hidden`));let o=t.querySelector(`.modal-close-btn`);o instanceof HTMLButtonElement&&(o.disabled=!1,o.setAttribute(`aria-label`,`Close file viewer`),o.title=`Close`),t.querySelector(`.modal-save-btn`)?.classList.add(`hidden`),t.querySelector(`.file-editor-container`)?.classList.remove(`active`),t.querySelector(`.modal-body`)?.classList.remove(`modal-body--editing`);let s=t.querySelector(`.file-editor`);s instanceof HTMLTextAreaElement&&(s.value=``,s.removeAttribute(`language`));let c=t.querySelector(`.file-editor-overlay code`);c&&(c.innerHTML=``,c.className=`hljs`),this.isFileEditMode=!1,this.editorDraftContent=null,r instanceof HTMLElement&&(this.revokeObjectUrl(),r.classList.remove(`hidden`),r.classList.add(`file-content--raw`),r.classList.remove(`file-content--preview`,`file-content--iframe`),r.textContent=``)}resolveRouteGroupId(e){let t=x.activeGroupId;if(e===t||this.routeGroupMatches(e,t))return t;let n=Array.isArray(x.groups)?x.groups:[],r=n.find(t=>t.groupId===e);if(r)return r.groupId;let i=n.find(t=>this.routeGroupMatches(e,t.groupId));return i?i.groupId:e||null}resolveWorkspaceLinkPath(e,t=``){let n=e.trim();if(!n||n.startsWith(`#`))return null;let r=n,i=/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(n);if(i||n.startsWith(`//`)){let e;try{e=new URL(n,window.location.href)}catch{return null}if(e.protocol!==`http:`&&e.protocol!==`https:`||e.host!==window.location.host)return null;r=`${e.pathname}${e.search}${e.hash}`}let a=this.getWorkspaceRouteTarget(r);if(a)return a.path;let o=r.split(/[?#]/,1)[0].replace(/\\/g,`/`),s=o.startsWith(`/`);if(i||s||(o=o.replace(/^\/+/,``),!o))return null;let c=[];if(!s){let e=t.replace(/\\/g,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean).map(e=>m(e));e.pop(),c.push(...e)}for(let e of o.split(`/`))if(e&&e!==`.`){if(e===`..`){if(c.length===0)return null;c.pop()}else c.push(m(e))}return c.length>0?c.join(`/`):null}revokeObjectUrl(){this.previewFrameWindow=null,this.currentObjectUrl&&=(URL.revokeObjectURL(this.currentObjectUrl),null);for(let e of this.currentImageObjectUrls)URL.revokeObjectURL(e);this.currentImageObjectUrls=[]}rewriteWorkspacePreviewHtml(e,t){if(!e)return e;let n=h(_(x.activeGroupId,t)),r=new DOMParser().parseFromString(e,`text/html`),i=(e,i)=>{let a=Array.from(r.querySelectorAll(e));for(let e of a){let r=(e.getAttribute(i)||``).trim();if(!r||r.startsWith(`#`)||r.startsWith(`javascript:`))continue;let a=g(r,n,window.location.origin);a&&a.origin===window.location.origin&&(i!==`href`||v(a.pathname)||this.resolveWorkspaceLinkPath(r,t))&&e.setAttribute(i,`${a.pathname}${a.search}${a.hash}`)}};return i(`a[href]`,`href`),i(`img[src]`,`src`),i(`audio[src]`,`src`),i(`video[src]`,`src`),i(`source[src]`,`src`),r.body.innerHTML}routeGroupMatches(e,t){if(e===t||e===`main`&&t===`br:main`||e===`br:main`&&t===`main`)return!0;if(!e.includes(`:`)&&!t.includes(`:`))return!1;let n=e=>e.trim().replace(/:/g,`-`);return n(e)===n(t)}setupEffects(){U(()=>{let e=S.declarativeTools;this.broadcastProxy&&e.length>0&&this.broadcastProxy.registerChannelsFromTools(e)}),U(()=>{let e=W.file,t=++this.viewRenderToken,n=this.shadowRoot;if(!n)return;let r=n.querySelector(`shadow-claw-dialog`);r&&typeof r.ensureDialog==`function`&&r.ensureDialog();let i=n.querySelector(`.file-modal`);if(e){r&&typeof r.showModal==`function`&&!r.open?r.showModal():i instanceof HTMLDialogElement&&!i.open&&i.showModal();let a=n.querySelector(`.modal-title`);a instanceof HTMLElement&&(a.textContent=`File: ${e.name}`),this.lastOpenedFileName!==e.name&&(this.lastOpenedFileName=e.name,this.isFilePreviewMode=this.shouldAutoPreview(e),this.isFileEditMode=!1,this.isEditorDirty=!1,this.editorDraftContent=null),this.updateView(t)}else r&&typeof r.close==`function`&&r.open?r.close():i instanceof HTMLDialogElement&&i.open&&i.close(),this.lastOpenedFileName=``,this.isFilePreviewMode=!1,this.isEditorDirty=!1,this.editorDraftContent=null,this.resetContent()})}shouldAutoPreview(e){return!e||typeof e!=`object`?!1:e.kind===`pdf`||e.kind===`binary`?!0:e.kind===`text`?this.isIframePreviewFile(e.name)||this.isMarkdownLikeFile(e.name):!1}stripHtmlFrontmatter(e){if(typeof e!=`string`||!e.trimStart().startsWith(`---`))return e;let t=O(e);return Object.keys(t.data||{}).length===0?e:t.content||``}toPreviewMarkdown(e){return this.isMarkdownLikeFile(e.name)?e.content:"```"+this.getLanguageFromFilename(e.name)+`
871
+ `)}}disconnectedCallback(){this.broadcastProxy?.dispose(),this.broadcastProxy=null,window.removeEventListener(`message`,this.handleIframeMessage),document.removeEventListener(`fullscreenchange`,this.handleFullscreenChange),this.themeObserver&&=(this.themeObserver.disconnect(),null),this.revokeObjectUrl()}applyFullscreenMode(e){let t=e.querySelector(`.modal-content`);t instanceof HTMLElement&&t.classList.toggle(`modal-content--fullscreen`,this.isFullscreenMode);let n=e.querySelector(`.modal-fullscreen-btn`);n instanceof HTMLButtonElement&&(n.setAttribute(`aria-pressed`,String(this.isFullscreenMode)),n.setAttribute(`aria-label`,this.isFullscreenMode?`Exit fullscreen`:`Enter fullscreen`),n.title=this.isFullscreenMode?`Exit fullscreen`:`Fullscreen`)}applyHighlightStyles(e){let t=this.shadowRoot;if(!t)return;if(typeof CSSStyleSheet<`u`&&typeof CSSStyleSheet.prototype.replaceSync==`function`&&`adoptedStyleSheets`in t)try{let n=new CSSStyleSheet;n.replaceSync(e);let r=new CSSStyleSheet;r.replaceSync(Z),t.adoptedStyleSheets=[...t.adoptedStyleSheets?Array.from(t.adoptedStyleSheets):[],n,r];return}catch{}let n=document.createElement(`style`);n.setAttribute(`data-shadow-claw-highlight-theme`,`true`),n.textContent=`${e}\n${Z}`,t.appendChild(n)}bindEventListeners(){let e=this.shadowRoot;if(!e)return;e.querySelector(`.file-content`)?.addEventListener(`click`,e=>{this.handlePreviewLinkClick(e)});let t=e.querySelector(`.file-modal`);t?.addEventListener(`cancel`,e=>{e.preventDefault(),this.requestCloseViewer()}),t?.addEventListener(`close`,()=>{W.file&&W.closeFile()}),e.querySelector(`.modal-close-btn`)?.addEventListener(`click`,()=>void this.requestCloseViewer()),e.querySelector(`.modal-preview-btn`)?.addEventListener(`click`,async()=>{this.isFilePreviewMode=!this.isFilePreviewMode,this.isFileEditMode=!1,await this.updateView()}),e.querySelector(`.modal-fullscreen-btn`)?.addEventListener(`click`,()=>{t&&this.toggleFullscreenMode(t)}),e.querySelector(`.modal-share-btn`)?.addEventListener(`click`,async()=>{await this.handleShareFile()});let n=e.querySelector(`.modal-share-dropdown`),r=e.querySelector(`.modal-share-peer-btn`),i=e.querySelector(`.modal-share-device-btn`);r?.addEventListener(`click`,async()=>{n instanceof HTMLDetailsElement&&n.removeAttribute(`open`),await this.handleSendFileToPeer()}),i?.addEventListener(`click`,async()=>{n instanceof HTMLDetailsElement&&n.removeAttribute(`open`),await this.handleShareFile()}),e.addEventListener(`click`,e=>{if(n instanceof HTMLDetailsElement&&n.open){let t=e.target;n.contains(t)||n.removeAttribute(`open`)}}),e.querySelector(`.modal-edit-btn`)?.addEventListener(`click`,async()=>{this.isFileEditMode=!this.isFileEditMode,this.isFileEditMode&&(this.isFilePreviewMode=!1),await this.updateView()}),e.querySelector(`.modal-save-btn`)?.addEventListener(`click`,()=>this.handleSave()),e.querySelector(`.modal-cancel-btn`)?.addEventListener(`click`,async()=>{this.isEditorDirty=!1,this.editorDraftContent=null,this.isFileEditMode=!1,await this.updateView()});let a=e.querySelector(`.file-editor`);if(a?.addEventListener(`input`,()=>{a instanceof HTMLTextAreaElement&&(this.editorDraftContent=a.value,this.updateEditorHighlight(a.value)),this.isEditorDirty=!0,this.updateView()}),a instanceof HTMLTextAreaElement){let t=()=>{let t=e.querySelector(`.file-editor-overlay`);t&&(t.scrollTop=a.scrollTop,t.scrollLeft=a.scrollLeft)};a.addEventListener(`scroll`,t),a.addEventListener(`focus`,t),a.addEventListener(`click`,t),a.addEventListener(`keyup`,t),a.addEventListener(`mouseup`,t),e.querySelector(`.modal-body`)?.addEventListener(`scroll`,t)}}buildWebShareFile(e){if(e?.nativeFile instanceof File)return e.nativeFile;let t=e?.binaryContent;if(!(t instanceof Uint8Array)||t.length===0)return null;let n=new Uint8Array(t.byteLength);return n.set(t),new File([n],e.name||`shared-file`,{type:e?.mimeType||`application/octet-stream`})}canShareCurrentFile(e){if(!e||!this.isWebShareAvailable())return!1;if(e.kind===`text`)return!0;let t=this.buildWebShareFile(e);if(!t||typeof navigator.canShare!=`function`)return!1;try{return navigator.canShare({files:[t]})}catch{return!1}}canUseNativeFullscreen(e){return document.fullscreenEnabled===!0&&(typeof e.requestFullscreen==`function`||typeof e.webkitRequestFullscreen==`function`)&&(typeof document.exitFullscreen==`function`||typeof document.webkitExitFullscreen==`function`)}getCurrentFullscreenElement(){return document.fullscreenElement||document.webkitFullscreenElement||null}getFullscreenTarget(e){let t=e.querySelector(`.modal-content`);return t instanceof HTMLElement?t:null}getIframeBridgeScriptUrl(){return n(`/assets/file-viewer-preview-bridge.js`)}getIframeSandboxPermissions(t){return/\.svg$/i.test(t)?`allow-modals allow-popups allow-popups-to-escape-sandbox`:e()}getLanguageFromFilename(e){return{bash:`bash`,cjs:`javascript`,css:`css`,html:`xml`,java:`java`,javascript:`javascript`,js:`javascript`,json:`json`,jsx:`jsx`,markdown:`markdown`,md:`markdown`,mjs:`javascript`,php:`php`,python:`python`,py:`python`,ruby:`ruby`,rb:`ruby`,rust:`rust`,rs:`rust`,sh:`bash`,sql:`sql`,svg:`xml`,ts:`typescript`,tsx:`tsx`,xml:`xml`,yaml:`yaml`,yml:`yaml`}[e.toLowerCase().split(`.`).pop()||``]||``}getPreviewSourceFile(e,t){return this.getWorkingSourceFile(e,t)}getWorkingSourceFile(e,t){if(!this.isEditorDirty||e?.kind!==`text`)return e;if(typeof this.editorDraftContent==`string`)return{...e,content:this.editorDraftContent};let n=t.querySelector(`.file-editor`);return n instanceof HTMLTextAreaElement?{...e,content:n.value}:e}getWorkspaceRouteTarget(e,t={}){let{allowCrossGroup:n=!1}=t,r=e.split(/[?#]/,1)[0].trim();if(!r)return null;if(/^[a-zA-Z][a-zA-Z\d+.-]*:/u.test(r)||r.startsWith(`//`)){let e;try{e=new URL(r,window.location.href)}catch{return null}if(e.origin!==window.location.origin)return null;r=e.pathname}let i=r.replace(/^(?:\.\/)+/u,``),a=[];if(i.startsWith(`files/`)&&a.push(`/${i}`),r.startsWith(`/`)){let e=r.lastIndexOf(`/files/`);e>0&&a.push(r.slice(e)),a.push(r)}for(let e of a){let t=f(e);if(!t)continue;let r=this.resolveRouteGroupId(t.groupId);if(r&&(n||r===x.activeGroupId))return{groupId:r,path:t.path}}return null}handleAnchorNavigation(e){let t=this.shadowRoot;if(!t)return!1;let n=t.querySelector(`.file-content`);if(!n)return!1;n.querySelectorAll(`.code-line.highlighted`).forEach(e=>{e.classList.remove(`highlighted`)});let r=e.match(/^#?L(\d+)(?:-L?(\d+))?$/i);if(r){let e=parseInt(r[1],10),t=r[2]?parseInt(r[2],10):e,i=null;return n.querySelectorAll(`.code-line`).forEach(n=>{let r=parseInt(n.getAttribute(`data-line`)||`0`,10);r>=e&&r<=t&&(n.classList.add(`highlighted`),i||=n)}),i?(i.scrollIntoView({behavior:`smooth`,block:`center`}),!0):!1}{let t=e.replace(/^#/,``),r=n.querySelector(`[id="${t}"]`)||n.querySelector(`a[name="${t}"]`);return r?(r.scrollIntoView({behavior:`smooth`,block:`start`}),!0):!1}}handleFullscreenChange=()=>{let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.file-modal`);if(!(t instanceof HTMLElement))return;let n=this.getFullscreenTarget(t);this.isFullscreenMode=this.isTargetInFullscreen(n),this.applyFullscreenMode(t)};handleIframeMessage=e=>{if(!e.data||typeof e.data!=`object`)return;let t=e.data;if(t.type===`shadow-claw-broadcast-result`&&typeof t.channel==`string`){this.broadcastProxy?.handleResultFromIframe(e.source,t.channel,t.payload);return}if(t.type===`shadow-claw-iframe-resize`&&typeof t.height==`number`){let n=this.shadowRoot?.querySelector(`.file-content-iframe`);n instanceof HTMLIFrameElement&&(!this.previewFrameWindow||e.source===this.previewFrameWindow||n.contentWindow&&e.source===n.contentWindow)&&(this.previewFrameWindow=n.contentWindow,n.style.setProperty(`height`,`${t.height}px`,`important`));return}if(t.type===`shadow-claw-storage-proxy`){if(this.previewFrameWindow&&e.source!==this.previewFrameWindow)return;let n=t;this.handleStorageProxyRequest(e.source,String(n.requestId||``),String(n.method||``),n.args&&typeof n.args==`object`?n.args:{});return}if(!this.db||t.type!==`shadow-claw-file-viewer-link`||typeof t.href!=`string`||this.previewFrameWindow&&e.source!==this.previewFrameWindow)return;let n=W.file,r=n?.path||n?.name||``,i=v(m(x.activeGroupId,r)),a=h(t.href,i,window.location.origin);if(!a)return;if(a.searchParams.has(`gameSave`)){this.reloadPreviewWithSearchParams(a.search);return}if(a.origin!==window.location.origin||!g(a.pathname)&&!this.resolveWorkspaceLinkPath(t.href,r)){window.open(a.href,`_blank`,`noopener,noreferrer`);return}let o=`${a.pathname}${a.search}${a.hash}`,s=window.navigation;s&&typeof s.navigate==`function`?s.navigate(o):(window.history.pushState({},``,o),window.dispatchEvent(new PopStateEvent(`popstate`)))};hasUnsavedChanges(){return this.isEditorDirty}isIframePreviewFile(e){return/\.(?:html?|svg)$/i.test(e)}isMarkdownLikeFile(e){return/(?:^readme$|\.mdx?$|\.markdown$|\.mdown$)/i.test(e)}isNodeInComposedTree(e,t){let n=e;for(;n;){if(n===t)return!0;if(n.parentNode){n=n.parentNode;continue}let e=n.getRootNode?.();n=e instanceof ShadowRoot&&e.host?e.host:null}return!1}isRenderTokenCurrent(e){return this.viewRenderToken===e}isTargetInFullscreen(e){if(!e)return!1;let t=this.getCurrentFullscreenElement();return t?t===e||this.isNodeInComposedTree(e,t)||this.isNodeInComposedTree(t,e):!1}isWebShareAvailable(){return typeof navigator<`u`&&typeof navigator.share==`function`}mimeTypeForImageExt(e){return D(e)??`image/jpeg`}renderBinaryPreview(e,t){let n=t.mimeType||`application/octet-stream`;if(t.nativeFile instanceof File)this.currentObjectUrl=URL.createObjectURL(t.nativeFile);else{let r=t.binaryContent;if(!(r instanceof Uint8Array)||r.length===0){e.classList.remove(`file-content--raw`,`file-content--iframe`),e.classList.add(`file-content--preview`),e.textContent=`Binary content unavailable.`;return}let i=new Uint8Array(r.byteLength);i.set(r);let a=new Blob([i],{type:n});this.currentObjectUrl=URL.createObjectURL(a)}if(e.classList.remove(`file-content--raw`,`file-content--preview`),e.classList.add(`file-content--iframe`),n.startsWith(`image/`)){let n=document.createElement(`img`);n.className=`file-content-iframe`,n.alt=`Preview: ${t.name}`,n.src=this.currentObjectUrl,n.style.objectFit=`contain`,e.replaceChildren(n);return}if(n.startsWith(`video/`)){let t=document.createElement(`video`);t.className=`file-content-iframe`,t.controls=!0,t.src=this.currentObjectUrl,t.style.backgroundColor=`black`,e.replaceChildren(t);return}if(n.startsWith(`audio/`)){let n=document.createElement(`div`);n.className=`file-content file-content--preview`,n.style.padding=`1rem`;let r=document.createElement(`p`);r.textContent=t.name;let i=document.createElement(`audio`);i.controls=!0,i.src=this.currentObjectUrl,i.style.width=`100%`,n.replaceChildren(r,i),e.replaceChildren(n),e.classList.remove(`file-content--iframe`);return}let r=document.createElement(`iframe`);r.className=`file-content-iframe`,r.setAttribute(`title`,`Preview: ${t.name}`),r.setAttribute(`referrerpolicy`,`no-referrer`),r.src=this.currentObjectUrl,e.replaceChildren(r)}resetContent(){let e=this.shadowRoot;if(!e)return;let t=e.querySelector(`.file-modal`);if(!(t instanceof HTMLElement))return;let n=this.getFullscreenTarget(t);n&&this.isTargetInFullscreen(n)&&this.exitNativeFullscreen().catch(()=>{}),this.isFullscreenMode=!1,this.applyFullscreenMode(t);let r=t.querySelector(`.file-content`),i=t.querySelector(`.modal-preview-btn`);i instanceof HTMLButtonElement&&(i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`aria-label`,`Switch to preview mode`));let a=t.querySelector(`.modal-edit-btn`);a instanceof HTMLButtonElement&&(a.setAttribute(`aria-pressed`,`false`),a.setAttribute(`aria-label`,`Edit file`),a.classList.remove(`hidden`));let o=t.querySelector(`.modal-close-btn`);o instanceof HTMLButtonElement&&(o.disabled=!1,o.setAttribute(`aria-label`,`Close file viewer`),o.title=`Close`),t.querySelector(`.modal-save-btn`)?.classList.add(`hidden`),t.querySelector(`.file-editor-container`)?.classList.remove(`active`),t.querySelector(`.modal-body`)?.classList.remove(`modal-body--editing`);let s=t.querySelector(`.file-editor`);s instanceof HTMLTextAreaElement&&(s.value=``,s.removeAttribute(`language`));let c=t.querySelector(`.file-editor-overlay code`);c&&(c.innerHTML=``,c.className=`hljs`),this.isFileEditMode=!1,this.editorDraftContent=null,r instanceof HTMLElement&&(this.revokeObjectUrl(),r.classList.remove(`hidden`),r.classList.add(`file-content--raw`),r.classList.remove(`file-content--preview`,`file-content--iframe`),r.textContent=``)}resolveRouteGroupId(e){let t=x.activeGroupId;if(e===t||this.routeGroupMatches(e,t))return t;let n=Array.isArray(x.groups)?x.groups:[],r=n.find(t=>t.groupId===e);if(r)return r.groupId;let i=n.find(t=>this.routeGroupMatches(e,t.groupId));return i?i.groupId:e||null}resolveWorkspaceLinkPath(e,t=``){let n=e.trim();if(!n||n.startsWith(`#`))return null;let r=n,i=/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(n);if(i||n.startsWith(`//`)){let e;try{e=new URL(n,window.location.href)}catch{return null}if(e.protocol!==`http:`&&e.protocol!==`https:`||e.host!==window.location.host)return null;r=`${e.pathname}${e.search}${e.hash}`}let a=this.getWorkspaceRouteTarget(r);if(a)return a.path;let o=r.split(/[?#]/,1)[0].replace(/\\/g,`/`),s=o.startsWith(`/`);if(i||s||(o=o.replace(/^\/+/,``),!o))return null;let c=[];if(!s){let e=t.replace(/\\/g,`/`).replace(/^\/+/,``).split(`/`).filter(Boolean).map(e=>p(e));e.pop(),c.push(...e)}for(let e of o.split(`/`))if(e&&e!==`.`){if(e===`..`){if(c.length===0)return null;c.pop()}else c.push(p(e))}return c.length>0?c.join(`/`):null}revokeObjectUrl(){this.previewFrameWindow=null,this.currentObjectUrl&&=(URL.revokeObjectURL(this.currentObjectUrl),null);for(let e of this.currentImageObjectUrls)URL.revokeObjectURL(e);this.currentImageObjectUrls=[]}rewriteWorkspacePreviewHtml(e,t){if(!e)return e;let n=v(m(x.activeGroupId,t)),r=new DOMParser().parseFromString(e,`text/html`),i=(e,i)=>{let a=Array.from(r.querySelectorAll(e));for(let e of a){let r=(e.getAttribute(i)||``).trim();if(!r||r.startsWith(`#`)||r.startsWith(`javascript:`))continue;let a=h(r,n,window.location.origin);a&&a.origin===window.location.origin&&(i!==`href`||g(a.pathname)||this.resolveWorkspaceLinkPath(r,t))&&e.setAttribute(i,`${a.pathname}${a.search}${a.hash}`)}};return i(`a[href]`,`href`),i(`img[src]`,`src`),i(`audio[src]`,`src`),i(`video[src]`,`src`),i(`source[src]`,`src`),r.body.innerHTML}routeGroupMatches(e,t){if(e===t||e===`main`&&t===`br:main`||e===`br:main`&&t===`main`)return!0;if(!e.includes(`:`)&&!t.includes(`:`))return!1;let n=e=>e.trim().replace(/:/g,`-`);return n(e)===n(t)}setupEffects(){U(()=>{let e=S.declarativeTools;this.broadcastProxy&&e.length>0&&this.broadcastProxy.registerChannelsFromTools(e)}),U(()=>{let e=W.file,t=++this.viewRenderToken,n=this.shadowRoot;if(!n)return;let r=n.querySelector(`shadow-claw-dialog`);r&&typeof r.ensureDialog==`function`&&r.ensureDialog();let i=n.querySelector(`.file-modal`);if(e){r&&typeof r.showModal==`function`&&!r.open?r.showModal():i instanceof HTMLDialogElement&&!i.open&&i.showModal();let a=n.querySelector(`.modal-title`);a instanceof HTMLElement&&(a.textContent=`File: ${e.name}`),this.lastOpenedFileName!==e.name&&(this.lastOpenedFileName=e.name,this.isFilePreviewMode=this.shouldAutoPreview(e),this.isFileEditMode=!1,this.isEditorDirty=!1,this.editorDraftContent=null),this.updateView(t)}else r&&typeof r.close==`function`&&r.open?r.close():i instanceof HTMLDialogElement&&i.open&&i.close(),this.lastOpenedFileName=``,this.isFilePreviewMode=!1,this.isEditorDirty=!1,this.editorDraftContent=null,this.resetContent()})}shouldAutoPreview(e){return!e||typeof e!=`object`?!1:e.kind===`pdf`||e.kind===`binary`?!0:e.kind===`text`?this.isIframePreviewFile(e.name)||this.isMarkdownLikeFile(e.name):!1}stripHtmlFrontmatter(e){if(typeof e!=`string`||!e.trimStart().startsWith(`---`))return e;let t=O(e);return Object.keys(t.data||{}).length===0?e:t.content||``}toPreviewMarkdown(e){return this.isMarkdownLikeFile(e.name)?e.content:"```"+this.getLanguageFromFilename(e.name)+`
872
872
  `+e.content+"\n```"}updateEditorHighlight(e){let t=this.shadowRoot;if(!t)return;let n=t.querySelector(`.file-editor-overlay code`);if(!n)return;let r=W.file,a=this.getLanguageFromFilename(r?.name||``),o=``;try{o=a&&A.getLanguage(a)?A.highlight(e,{language:a}).value:A.highlightAuto(e).value}catch{o=e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}n.className=a?`hljs language-${a}`:`hljs`,n.innerHTML=i(o+`<br>`)}wrapCodeLines(e){e.querySelectorAll(`pre code`).forEach(e=>{let t=e.innerHTML.split(/\r?\n/u);t.length>1&&t[t.length-1]===``&&t.pop();let n=t.map((e,t)=>`<span class="code-line" data-line="${t+1}">${e||`&nbsp;`}</span>`).join(`
873
- `);c(e,n)})}async buildIframePreviewSrcdoc(e,t=``){if(/\.svg$/i.test(e.name))return e.content;let n=e.path||e.name||``,i=this.stripHtmlFrontmatter(e.content||``),o=this.rewriteWorkspacePreviewHtml(i,n),c=await this.resolveRelativeImagesInHtml(o,n),u=r(c,Q),d=crypto.randomUUID().replace(/-/g,``),f=l(),p=a(d),m=typeof document<`u`?document.getElementById(`shadow-claw-site-config`):null,g=m&&m.textContent?`<script id="shadow-claw-site-config" type="application/json">${m.textContent}<\/script>`:``,v=t?`<script nonce="${d}">(function(){try{Object.defineProperty(globalThis.location,"search",{get:function(){return ${JSON.stringify(t)};},configurable:true});}catch(e){}})();<\/script>`:``,y=f.length>0&&s(u)?f.map(({src:e,hasInit:t})=>{let n=e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`//`)?e:h(e.startsWith(`/`)?e:`/${e.replace(/^pages\/main\//,``)}`),r=[`<script type="module" src="${n}" nonce="${d}"><\/script>`];return t&&r.push(`<script type="module" nonce="${d}">import("${n}").then((m) => { try { if (typeof m?.init === "function") m.init(); } catch (e) { console.error("[ShadowClaw] Error executing init for " + ${JSON.stringify(n)}, e); } }).catch(() => {});<\/script>`),r.join(`
873
+ `);c(e,n)})}async buildIframePreviewSrcdoc(e,t=``){if(/\.svg$/i.test(e.name))return e.content;let n=e.path||e.name||``,i=this.stripHtmlFrontmatter(e.content||``),o=this.rewriteWorkspacePreviewHtml(i,n),c=await this.resolveRelativeImagesInHtml(o,n),u=r(c,Q),d=crypto.randomUUID().replace(/-/g,``),f=l(),p=a(d),h=typeof document<`u`?document.getElementById(`shadow-claw-site-config`):null,g=h&&h.textContent?`<script id="shadow-claw-site-config" type="application/json">${h.textContent}<\/script>`:``,_=t?`<script nonce="${d}">(function(){try{Object.defineProperty(globalThis.location,"search",{get:function(){return ${JSON.stringify(t)};},configurable:true});}catch(e){}})();<\/script>`:``,y=f.length>0&&s(u)?f.map(({src:e,hasInit:t})=>{let n=e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`//`)?e:v(e.startsWith(`/`)?e:`/${e.replace(/^pages\/main\//,``)}`),r=[`<script type="module" src="${n}" nonce="${d}"><\/script>`];return t&&r.push(`<script type="module" nonce="${d}">import("${n}").then((m) => { try { if (typeof m?.init === "function") m.init(); } catch (e) { console.error("[ShadowClaw] Error executing init for " + ${JSON.stringify(n)}, e); } }).catch(() => {});<\/script>`),r.join(`
874
874
  `)}).join(`
875
- `):``,b=P();return[`<!doctype html>`,`<html class="${H()}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">`,`<meta http-equiv="Content-Security-Policy" content="${p}">`,`<base href="${h(_(x.activeGroupId,n))}" target="_blank">`,v,g,`<script nonce="${d}">${z(L)}<\/script>`,`<script nonce="${d}">${z(V)}<\/script>`,N(),b,y,`</head><body class="${H()}">`,u,`</body></html>`].join(``)}async canDismissViewer(){if(!this.hasUnsavedChanges())return!0;let e=await this.requestConfirmation({title:`Discard Unsaved Changes`,message:`You have unsaved changes. Discard them and close?`,confirmLabel:`Discard`,cancelLabel:`Keep Editing`});return e&&(this.isEditorDirty=!1,this.editorDraftContent=null),e}async exitFullscreenIfActive(e){let t=this.shadowRoot,n=e||t?.querySelector(`.file-modal`);if(!n)return;let r=this.getFullscreenTarget(n);if(r&&this.isTargetInFullscreen(r))try{await this.exitNativeFullscreen()}catch{}}async exitNativeFullscreen(){let e=document.exitFullscreen||document.webkitExitFullscreen;if(typeof e!=`function`)throw Error(`Native fullscreen exit unavailable`);await Promise.resolve(e.call(document))}async handlePreviewLinkClick(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`a`);if(!(n instanceof HTMLAnchorElement)||!this.db)return;let r=W.file,i=r?.path||r?.name||``,a=n.getAttribute(`href`)||``,o=h(_(x.activeGroupId,i)),s=g(a,o,window.location.origin);if(s&&s.origin===window.location.origin&&(v(s.pathname)||this.resolveWorkspaceLinkPath(a,i))&&s){e.preventDefault();let t=`${s.pathname}${s.search}${s.hash}`,n=window.navigation;n&&typeof n.navigate==`function`?n.navigate(t):(window.history.pushState({},``,t),window.dispatchEvent(new PopStateEvent(`popstate`)));return}let c=a.trim();if(c&&!c.startsWith(`#`)&&!c.startsWith(`javascript:`)){let t=n.getAttribute(`target`)||`_blank`,r=t===`_self`||t===`_top`||t===`_parent`?`_blank`:t;try{new URL(c,window.location.href).host!==window.location.host&&(e.preventDefault(),window.open(c,r,`noopener,noreferrer`))}catch{/^[a-zA-Z][a-zA-Z\d+.-]*:/u.test(c)&&(e.preventDefault(),window.open(c,r,`noopener,noreferrer`))}}}async handleSave(){let e=W.file;if(!e||!this.db)return;let t=this.shadowRoot,n=t?.querySelector(`.modal-save-btn`),r=t?.querySelector(`.file-editor`);if(r instanceof HTMLTextAreaElement)try{n instanceof HTMLButtonElement&&(n.disabled=!0,n.textContent=`⏳ saving...`);let t=r.value,i=e.path||(x.currentPath===`.`?e.name:`${x.currentPath}/${e.name}`),a=e.groupId||x.activeGroupId;await C(this.db,a,i,t),w(`Saved ${e.name}`),document.dispatchEvent(new CustomEvent(`shadow-claw-file-saved`,{detail:{groupId:a,path:i},bubbles:!0,composed:!0})),await x.loadFiles(this.db),e.content=t,this.isFileEditMode=!1,this.isEditorDirty=!1,this.editorDraftContent=null,await this.updateView()}catch(e){let t=e instanceof Error?e.message:String(e);T(`Failed to save file: ${t}`)}finally{n instanceof HTMLButtonElement&&(n.disabled=!1,n.textContent=`💾 Save`)}}async handleSendFileToPeer(){let e=W.file;if(!e||!e.path){T(`No file is currently open.`,4500);return}let t=e.groupId||x.activeGroupId||``,n=t.startsWith(`peer:`),r=t.startsWith(`room:`);if(!n&&!r)T(`Can only send files to peers in a peer or room conversation.`,4500);else try{await x.sendFileToPeer(e.path,t,{fileName:e.name,mimeType:e.mimeType})}catch{}}async handleShareFile(){let e=W.file;if(!e||!this.canShareCurrentFile(e))T(`Sharing is not supported for this file on this device.`,4500);else try{if(e.kind===`text`)await navigator.share({title:e.name,text:e.content||``});else{let t=this.buildWebShareFile(e);if(!t||!navigator.canShare?.({files:[t]})){T(`File sharing is not supported on this device.`,4500);return}await navigator.share({title:e.name,files:[t]})}w(`Shared ${e.name}`)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;let t=e instanceof Error?e.message:String(e);T(`Failed to share file: ${t}`,5e3)}}async openFolderInFilesView(e){if(!this.db)return;let t=e.replace(/^\/+|\/+$/g,``);if(t)try{await x.setCurrentPath(this.db,t),W.closeFile();let e=window?.shadowclaw?.ui;e&&typeof e.showPage==`function`&&e.showPage(`files`)}catch(e){let t=e instanceof Error?e.message:String(e);T(`Failed to open linked folder: ${t}`,5e3)}}async openWorkspaceLink(e,t){if(!this.db)return;let n=this.resolveWorkspaceLinkPath(e,t);if(!n)return;let r=n.split(`/`).filter(Boolean).pop()||``;if(/\.[^./]+$/u.test(r))try{await W.openFile(this.db,n,x.activeGroupId)}catch(e){let t=e instanceof Error?e.message:String(e);T(`Failed to open linked file: ${t}`,5e3)}else{try{await W.openFile(this.db,n,x.activeGroupId);return}catch(e){let t=e instanceof DOMException&&e.name===`NotFoundError`,n=e instanceof DOMException&&e.name===`TypeMismatchError`;if(!t&&!n){let t=e instanceof Error?e.message:String(e);T(`Failed to open linked file: ${t}`,5e3);return}}await this.openFolderInFilesView(n)}}async renderPreview(e,n,r=this.viewRenderToken){if(!this.isRenderTokenCurrent(r))return;if(this.revokeObjectUrl(),this.previewFrameWindow=null,n.kind===`pdf`){e.classList.remove(`file-content--raw`,`file-content--preview`,`file-content--iframe`),import(`./shadow-claw-pdf-viewer-BiCEwsoY.js`).then(()=>{let t=document.createElement(`shadow-claw-pdf-viewer`);t.file=n,e.replaceChildren(t)}).catch(console.error);return}if(n.kind===`binary`){this.renderBinaryPreview(e,n);return}if(this.isIframePreviewFile(n.name)){e.classList.remove(`file-content--raw`,`file-content--preview`),e.classList.add(`file-content--iframe`);let t=document.createElement(`iframe`);t.className=`file-content-iframe`,t.setAttribute(`title`,`Preview: ${n.name}`),t.setAttribute(`sandbox`,this.getIframeSandboxPermissions(n.name)),t.setAttribute(`allow`,`fullscreen; clipboard-write`),t.setAttribute(`referrerpolicy`,`no-referrer`),o(t,await this.buildIframePreviewSrcdoc(n)),t.addEventListener(`load`,()=>{this.previewFrameWindow=t.contentWindow,this.syncIframeTheme()}),e.replaceChildren(t);return}e.classList.remove(`file-content--raw`),e.classList.add(`file-content--preview`);let i=W.file,a=i?.path||i?.name||``,s=this.toPreviewMarkdown(n),l=re(this.db,f.MARKDOWN_FRONTMATTER_FILE_VIEWER),d=typeof l==`boolean`?l:await l,p=await k(s,{renderFrontmatter:d});if(!this.isRenderTokenCurrent(r))return;let m=this.rewriteWorkspacePreviewHtml(p,a);this.isRenderTokenCurrent(r)&&(c(e,m,Q),e.querySelectorAll(`script`).forEach(e=>{let n=e.getAttribute(`src`);n&&u(n)&&t(n)}),this.wrapCodeLines(e),await this.resolveMarkdownImages(e,a))}async requestCloseViewer(){return await this.canDismissViewer()?(await this.exitFullscreenIfActive(),W.closeFile(),!0):!1}async requestConfirmation(e){let t=document.querySelector(`shadow-claw`);return t&&typeof t.requestDialog==`function`?await t.requestDialog({mode:`confirm`,...e}):!1}async requestNativeFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;if(typeof t!=`function`)throw Error(`Native fullscreen unavailable`);await Promise.resolve(t.call(e))}async resolveMarkdownImages(e,t){if(!this.db)return;let n=Array.from(e.querySelectorAll(`img`));n.length!==0&&await Promise.all(n.map(async e=>{let n=e.getAttribute(`src`)||``;if(!n||/^(?:blob:|data:|#)/u.test(n))return;let r=this.getWorkspaceRouteTarget(n,{allowCrossGroup:!0})||(()=>{let e=this.resolveWorkspaceLinkPath(n,t);return e?{groupId:x.activeGroupId,path:e}:null})();if(r)try{let t=await E(this.db,r.groupId,r.path),n=r.path.split(`.`).pop()?.toLowerCase()||``,i=this.mimeTypeForImageExt(n),a=new Uint8Array(t.byteLength);a.set(t),e.src=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(new Blob([a],{type:i}))})}catch{}}))}async resolveRelativeImagesInHtml(e,t){if(!this.db||!e)return e;let n=new DOMParser().parseFromString(e,`text/html`),r=Array.from(n.querySelectorAll(`img`));return r.length===0?e:(await Promise.all(r.map(async e=>{let n=e.getAttribute(`src`)||``;if(!n||/^(?:blob:|data:|#)/u.test(n))return;let r=this.getWorkspaceRouteTarget(n,{allowCrossGroup:!0})||(()=>{let e=this.resolveWorkspaceLinkPath(n,t);return e?{groupId:x.activeGroupId,path:e}:null})();if(r)try{let t=await E(this.db,r.groupId,r.path),n=r.path.split(`.`).pop()?.toLowerCase()||``,i=this.mimeTypeForImageExt(n),a=new Uint8Array(t.byteLength);a.set(t);let o=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(new Blob([a],{type:i}))});e.setAttribute(`src`,o)}catch{}})),n.body.innerHTML)}async toggleFullscreenMode(e){let t=this.getFullscreenTarget(e);if(t){if(this.canUseNativeFullscreen(t)){let n=this.isTargetInFullscreen(t);try{n?(await this.exitNativeFullscreen(),this.isFullscreenMode=!1):(await this.requestNativeFullscreen(t),this.isFullscreenMode=!0)}catch{this.isFullscreenMode=!this.isFullscreenMode}this.applyFullscreenMode(e)}else this.isFullscreenMode=!this.isFullscreenMode,this.applyFullscreenMode(e)}}async updateView(e=this.viewRenderToken){let t=W.file,n=this.shadowRoot;if(!n||!t)return;let r=n.querySelector(`.file-modal`);if(!(r instanceof HTMLElement))return;this.applyFullscreenMode(r);let i=r.querySelector(`.file-content`),a=r.querySelector(`.modal-preview-btn`),o=r.querySelector(`.modal-body`);if(!(i instanceof HTMLElement))return;i.classList.remove(`file-content--iframe`);let s=this.getWorkingSourceFile(t,r),c=t.kind===`text`;a instanceof HTMLButtonElement&&(a.setAttribute(`aria-pressed`,String(this.isFilePreviewMode)),a.setAttribute(`aria-label`,this.isFilePreviewMode?`Switch to raw text view`:`Switch to preview mode`));let l=r.querySelector(`.file-editor-container`),u=r.querySelector(`.modal-edit-btn`),d=r.querySelector(`.modal-save-btn`),f=r.querySelector(`.modal-share-btn`),p=r.querySelector(`.modal-close-btn`),m=r.querySelector(`.modal-cancel-btn`),h=t?.groupId||x.activeGroupId||``,g=h.startsWith(`peer:`),_=h.startsWith(`room:`),v=g||_,y=this.canShareCurrentFile(t),b=r.querySelector(`.modal-share-dropdown`),S=r.querySelector(`.modal-share-peer-label`),C=r.querySelector(`.modal-share-device-btn`);if(b instanceof HTMLElement&&(v?(b.classList.remove(`hidden`),S&&(S.textContent=_?`Send to room peers`:`Send to peer`),C instanceof HTMLButtonElement&&(C.classList.toggle(`hidden`,!y),C.disabled=!y)):b.classList.add(`hidden`)),f instanceof HTMLButtonElement&&(v?(f.classList.add(`hidden`),f.disabled=!0):(f.classList.toggle(`hidden`,!y),f.disabled=!y)),p instanceof HTMLButtonElement){let e=this.hasUnsavedChanges();p.disabled=!1,p.setAttribute(`aria-label`,e?`Close file viewer (unsaved changes)`:`Close file viewer`),p.title=e?`Close (you have unsaved changes)`:`Close`}let w=this.hasUnsavedChanges();if(d instanceof HTMLButtonElement&&d.classList.toggle(`hidden`,!w),m instanceof HTMLButtonElement&&m.classList.toggle(`hidden`,!w),this.isFilePreviewMode)o?.classList.remove(`modal-body--editing`),i.classList.remove(`hidden`),l?.classList.remove(`active`),u instanceof HTMLButtonElement&&(u.setAttribute(`aria-pressed`,`false`),u.setAttribute(`aria-label`,`Edit file`),u.classList.toggle(`hidden`,!c)),await this.renderPreview(i,s,e);else if(this.isRenderTokenCurrent(e)){if(this.isFileEditMode&&c){o?.classList.add(`modal-body--editing`),i.classList.add(`hidden`),l?.classList.add(`active`),u instanceof HTMLButtonElement&&(u.setAttribute(`aria-pressed`,`true`),u.setAttribute(`aria-label`,`Switch to raw text view`),u.classList.remove(`hidden`));let e=l?.querySelector(`.file-editor`);if(e instanceof HTMLTextAreaElement){e.setAttribute(`tab-size`,`2`);let n=this.getLanguageFromFilename(t.name);if(n?e.setAttribute(`language`,n):e.removeAttribute(`language`),this.isEditorDirty)typeof s?.content==`string`&&(e.value!==s.content&&(e.value=s.content),this.updateEditorHighlight(e.value));else{let n=t.content||``;e.value!==n&&(e.value=n),this.updateEditorHighlight(e.value)}e.dispatchEvent(new Event(`scroll`))}}else o?.classList.remove(`modal-body--editing`),i.classList.remove(`hidden`),l?.classList.remove(`active`),u instanceof HTMLButtonElement&&(u.setAttribute(`aria-pressed`,`false`),u.setAttribute(`aria-label`,`Edit file`),u.classList.toggle(`hidden`,!c)),i.classList.add(`file-content--raw`),i.classList.remove(`file-content--preview`,`file-content--iframe`),i.textContent=t.kind===`binary`?`Binary file (${t.mimeType||`application/octet-stream`}). Switch to Preview to view.`:s.content||``}}syncIframeTheme(){if(!this.previewFrameWindow)return;let e=document.documentElement.classList.contains(`dark-mode`),t=getComputedStyle(document.documentElement),n={};for(let e=0;e<t.length;e++){let r=t[e];r.startsWith(`--`)&&(n[r]=t.getPropertyValue(r))}this.previewFrameWindow.postMessage({type:`shadow-claw-theme-update`,theme:e?`dark`:`light`,customProperties:n},`*`)}async handleStorageProxyRequest(e,t,n,r){if(!t)return;let i=W.file,a=i?.path||i?.name||`__default__`;try{let i;switch(n){case`setItem`:await M(a,String(r.key||``),r.value);break;case`removeItem`:await j(a,String(r.key||``));break;case`clear`:await F(a);break;case`getAllItems`:i=await B(a);break;case`idb-get`:i=await R(`${a}::idb::${r.dbName}::${r.storeName}`,String(r.key||``));break;case`idb-getAll`:i=await B(`${a}::idb::${r.dbName}::${r.storeName}`);break;case`idb-put`:{let e=r.key==null?`__auto_${Date.now()}`:String(r.key);await M(`${a}::idb::${r.dbName}::${r.storeName}`,e,r.value),i=e;break}case`idb-delete`:await j(`${a}::idb::${r.dbName}::${r.storeName}`,String(r.key||``));break;case`idb-clear`:await F(`${a}::idb::${r.dbName}::${r.storeName}`);break;case`idb-deleteDatabase`:await F(`${a}::idb::${r.dbName}::__default__`);break;default:throw Error(`Unknown storage proxy method: ${n}`)}e.postMessage({type:`shadow-claw-storage-proxy-result`,requestId:t,result:i??null},`*`)}catch(n){e.postMessage({type:`shadow-claw-storage-proxy-result`,requestId:t,error:n instanceof Error?n.message:String(n)},`*`)}}async reloadPreviewWithSearchParams(e){let t=W.file;if(!t)return;let n=this.shadowRoot?.querySelector(`.file-viewer__iframe`);n&&(this.previewFrameWindow=null,o(n,await this.buildIframePreviewSrcdoc(t,e)))}};customElements.get(X)||customElements.define(X,$);export{$ as ShadowClawFileViewer};
875
+ `):``,b=P();return[`<!doctype html>`,`<html class="${H()}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">`,`<meta http-equiv="Content-Security-Policy" content="${p}">`,`<base href="${v(m(x.activeGroupId,n))}" target="_blank">`,_,g,`<script nonce="${d}">${z(L)}<\/script>`,`<script nonce="${d}">${z(V)}<\/script>`,N(),b,y,`</head><body class="${H()}">`,u,`</body></html>`].join(``)}async canDismissViewer(){if(!this.hasUnsavedChanges())return!0;let e=await this.requestConfirmation({title:`Discard Unsaved Changes`,message:`You have unsaved changes. Discard them and close?`,confirmLabel:`Discard`,cancelLabel:`Keep Editing`});return e&&(this.isEditorDirty=!1,this.editorDraftContent=null),e}async exitFullscreenIfActive(e){let t=this.shadowRoot,n=e||t?.querySelector(`.file-modal`);if(!n)return;let r=this.getFullscreenTarget(n);if(r&&this.isTargetInFullscreen(r))try{await this.exitNativeFullscreen()}catch{}}async exitNativeFullscreen(){let e=document.exitFullscreen||document.webkitExitFullscreen;if(typeof e!=`function`)throw Error(`Native fullscreen exit unavailable`);await Promise.resolve(e.call(document))}async handlePreviewLinkClick(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`a`);if(!(n instanceof HTMLAnchorElement)||!this.db)return;let r=W.file,i=r?.path||r?.name||``,a=n.getAttribute(`href`)||``,o=v(m(x.activeGroupId,i)),s=h(a,o,window.location.origin);if(s&&s.origin===window.location.origin&&(g(s.pathname)||this.resolveWorkspaceLinkPath(a,i))&&s){e.preventDefault();let t=`${s.pathname}${s.search}${s.hash}`,n=window.navigation;n&&typeof n.navigate==`function`?n.navigate(t):(window.history.pushState({},``,t),window.dispatchEvent(new PopStateEvent(`popstate`)));return}let c=a.trim();if(c&&!c.startsWith(`#`)&&!c.startsWith(`javascript:`)){let t=n.getAttribute(`target`)||`_blank`,r=t===`_self`||t===`_top`||t===`_parent`?`_blank`:t;try{new URL(c,window.location.href).host!==window.location.host&&(e.preventDefault(),window.open(c,r,`noopener,noreferrer`))}catch{/^[a-zA-Z][a-zA-Z\d+.-]*:/u.test(c)&&(e.preventDefault(),window.open(c,r,`noopener,noreferrer`))}}}async handleSave(){let e=W.file;if(!e||!this.db)return;let t=this.shadowRoot,n=t?.querySelector(`.modal-save-btn`),r=t?.querySelector(`.file-editor`);if(r instanceof HTMLTextAreaElement)try{n instanceof HTMLButtonElement&&(n.disabled=!0,n.textContent=`⏳ saving...`);let t=r.value,i=e.path||(x.currentPath===`.`?e.name:`${x.currentPath}/${e.name}`),a=e.groupId||x.activeGroupId;await C(this.db,a,i,t),w(`Saved ${e.name}`),document.dispatchEvent(new CustomEvent(`shadow-claw-file-saved`,{detail:{groupId:a,path:i},bubbles:!0,composed:!0})),await x.loadFiles(this.db),e.content=t,this.isFileEditMode=!1,this.isEditorDirty=!1,this.editorDraftContent=null,await this.updateView()}catch(e){let t=e instanceof Error?e.message:String(e);T(`Failed to save file: ${t}`)}finally{n instanceof HTMLButtonElement&&(n.disabled=!1,n.textContent=`💾 Save`)}}async handleSendFileToPeer(){let e=W.file;if(!e||!e.path){T(`No file is currently open.`,4500);return}let t=e.groupId||x.activeGroupId||``,n=t.startsWith(`peer:`),r=t.startsWith(`room:`);if(!n&&!r)T(`Can only send files to peers in a peer or room conversation.`,4500);else try{await x.sendFileToPeer(e.path,t,{fileName:e.name,mimeType:e.mimeType})}catch{}}async handleShareFile(){let e=W.file;if(!e||!this.canShareCurrentFile(e))T(`Sharing is not supported for this file on this device.`,4500);else try{if(e.kind===`text`)await navigator.share({title:e.name,text:e.content||``});else{let t=this.buildWebShareFile(e);if(!t||!navigator.canShare?.({files:[t]})){T(`File sharing is not supported on this device.`,4500);return}await navigator.share({title:e.name,files:[t]})}w(`Shared ${e.name}`)}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;let t=e instanceof Error?e.message:String(e);T(`Failed to share file: ${t}`,5e3)}}async openFolderInFilesView(e){if(!this.db)return;let t=e.replace(/^\/+|\/+$/g,``);if(t)try{await x.setCurrentPath(this.db,t),W.closeFile();let e=window?.shadowclaw?.ui;e&&typeof e.showPage==`function`&&e.showPage(`files`)}catch(e){let t=e instanceof Error?e.message:String(e);T(`Failed to open linked folder: ${t}`,5e3)}}async openWorkspaceLink(e,t){if(!this.db)return;let n=this.resolveWorkspaceLinkPath(e,t);if(!n)return;let r=n.split(`/`).filter(Boolean).pop()||``;if(/\.[^./]+$/u.test(r))try{await W.openFile(this.db,n,x.activeGroupId)}catch(e){let t=e instanceof Error?e.message:String(e);T(`Failed to open linked file: ${t}`,5e3)}else{try{await W.openFile(this.db,n,x.activeGroupId);return}catch(e){let t=e instanceof DOMException&&e.name===`NotFoundError`,n=e instanceof DOMException&&e.name===`TypeMismatchError`;if(!t&&!n){let t=e instanceof Error?e.message:String(e);T(`Failed to open linked file: ${t}`,5e3);return}}await this.openFolderInFilesView(n)}}async renderPreview(e,n,r=this.viewRenderToken){if(!this.isRenderTokenCurrent(r))return;if(this.revokeObjectUrl(),this.previewFrameWindow=null,n.kind===`pdf`){e.classList.remove(`file-content--raw`,`file-content--preview`,`file-content--iframe`),import(`./shadow-claw-pdf-viewer-DZ_84qJH.js`).then(()=>{let t=document.createElement(`shadow-claw-pdf-viewer`);t.file=n,e.replaceChildren(t)}).catch(console.error);return}if(n.kind===`binary`){this.renderBinaryPreview(e,n);return}if(this.isIframePreviewFile(n.name)){e.classList.remove(`file-content--raw`,`file-content--preview`),e.classList.add(`file-content--iframe`);let t=document.createElement(`iframe`);t.className=`file-content-iframe`,t.setAttribute(`title`,`Preview: ${n.name}`),t.setAttribute(`sandbox`,this.getIframeSandboxPermissions(n.name)),t.setAttribute(`allow`,`fullscreen; clipboard-write`),t.setAttribute(`referrerpolicy`,`no-referrer`),o(t,await this.buildIframePreviewSrcdoc(n)),t.addEventListener(`load`,()=>{this.previewFrameWindow=t.contentWindow,this.syncIframeTheme()}),e.replaceChildren(t);return}e.classList.remove(`file-content--raw`),e.classList.add(`file-content--preview`);let i=W.file,a=i?.path||i?.name||``,s=this.toPreviewMarkdown(n),l=re(this.db,_.MARKDOWN_FRONTMATTER_FILE_VIEWER),d=typeof l==`boolean`?l:await l,f=await k(s,{renderFrontmatter:d});if(!this.isRenderTokenCurrent(r))return;let p=this.rewriteWorkspacePreviewHtml(f,a);this.isRenderTokenCurrent(r)&&(c(e,p,Q),e.querySelectorAll(`script`).forEach(e=>{let n=e.getAttribute(`src`);n&&u(n)&&t(n)}),this.wrapCodeLines(e),await this.resolveMarkdownImages(e,a))}async requestCloseViewer(){return await this.canDismissViewer()?(await this.exitFullscreenIfActive(),W.closeFile(),!0):!1}async requestConfirmation(e){let t=document.querySelector(`shadow-claw`);return t&&typeof t.requestDialog==`function`?await t.requestDialog({mode:`confirm`,...e}):!1}async requestNativeFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;if(typeof t!=`function`)throw Error(`Native fullscreen unavailable`);await Promise.resolve(t.call(e))}async resolveMarkdownImages(e,t){if(!this.db)return;let n=Array.from(e.querySelectorAll(`img`));n.length!==0&&await Promise.all(n.map(async e=>{let n=e.getAttribute(`src`)||``;if(!n||/^(?:blob:|data:|#)/u.test(n))return;let r=this.getWorkspaceRouteTarget(n,{allowCrossGroup:!0})||(()=>{let e=this.resolveWorkspaceLinkPath(n,t);return e?{groupId:x.activeGroupId,path:e}:null})();if(r)try{let t=await E(this.db,r.groupId,r.path),n=r.path.split(`.`).pop()?.toLowerCase()||``,i=this.mimeTypeForImageExt(n),a=new Uint8Array(t.byteLength);a.set(t),e.src=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(new Blob([a],{type:i}))})}catch{}}))}async resolveRelativeImagesInHtml(e,t){if(!this.db||!e)return e;let n=new DOMParser().parseFromString(e,`text/html`),r=Array.from(n.querySelectorAll(`img`));return r.length===0?e:(await Promise.all(r.map(async e=>{let n=e.getAttribute(`src`)||``;if(!n||/^(?:blob:|data:|#)/u.test(n))return;let r=this.getWorkspaceRouteTarget(n,{allowCrossGroup:!0})||(()=>{let e=this.resolveWorkspaceLinkPath(n,t);return e?{groupId:x.activeGroupId,path:e}:null})();if(r)try{let t=await E(this.db,r.groupId,r.path),n=r.path.split(`.`).pop()?.toLowerCase()||``,i=this.mimeTypeForImageExt(n),a=new Uint8Array(t.byteLength);a.set(t);let o=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(n.result),n.onerror=t,n.readAsDataURL(new Blob([a],{type:i}))});e.setAttribute(`src`,o)}catch{}})),n.body.innerHTML)}async toggleFullscreenMode(e){let t=this.getFullscreenTarget(e);if(t){if(this.canUseNativeFullscreen(t)){let n=this.isTargetInFullscreen(t);try{n?(await this.exitNativeFullscreen(),this.isFullscreenMode=!1):(await this.requestNativeFullscreen(t),this.isFullscreenMode=!0)}catch{this.isFullscreenMode=!this.isFullscreenMode}this.applyFullscreenMode(e)}else this.isFullscreenMode=!this.isFullscreenMode,this.applyFullscreenMode(e)}}async updateView(e=this.viewRenderToken){let t=W.file,n=this.shadowRoot;if(!n||!t)return;let r=n.querySelector(`.file-modal`);if(!(r instanceof HTMLElement))return;this.applyFullscreenMode(r);let i=r.querySelector(`.file-content`),a=r.querySelector(`.modal-preview-btn`),o=r.querySelector(`.modal-body`);if(!(i instanceof HTMLElement))return;i.classList.remove(`file-content--iframe`);let s=this.getWorkingSourceFile(t,r),c=t.kind===`text`;a instanceof HTMLButtonElement&&(a.setAttribute(`aria-pressed`,String(this.isFilePreviewMode)),a.setAttribute(`aria-label`,this.isFilePreviewMode?`Switch to raw text view`:`Switch to preview mode`));let l=r.querySelector(`.file-editor-container`),u=r.querySelector(`.modal-edit-btn`),d=r.querySelector(`.modal-save-btn`),f=r.querySelector(`.modal-share-btn`),p=r.querySelector(`.modal-close-btn`),m=r.querySelector(`.modal-cancel-btn`),h=t?.groupId||x.activeGroupId||``,g=h.startsWith(`peer:`),_=h.startsWith(`room:`),v=g||_,y=this.canShareCurrentFile(t),b=r.querySelector(`.modal-share-dropdown`),S=r.querySelector(`.modal-share-peer-label`),C=r.querySelector(`.modal-share-device-btn`);if(b instanceof HTMLElement&&(v?(b.classList.remove(`hidden`),S&&(S.textContent=_?`Send to room peers`:`Send to peer`),C instanceof HTMLButtonElement&&(C.classList.toggle(`hidden`,!y),C.disabled=!y)):b.classList.add(`hidden`)),f instanceof HTMLButtonElement&&(v?(f.classList.add(`hidden`),f.disabled=!0):(f.classList.toggle(`hidden`,!y),f.disabled=!y)),p instanceof HTMLButtonElement){let e=this.hasUnsavedChanges();p.disabled=!1,p.setAttribute(`aria-label`,e?`Close file viewer (unsaved changes)`:`Close file viewer`),p.title=e?`Close (you have unsaved changes)`:`Close`}let w=this.hasUnsavedChanges();if(d instanceof HTMLButtonElement&&d.classList.toggle(`hidden`,!w),m instanceof HTMLButtonElement&&m.classList.toggle(`hidden`,!w),this.isFilePreviewMode)o?.classList.remove(`modal-body--editing`),i.classList.remove(`hidden`),l?.classList.remove(`active`),u instanceof HTMLButtonElement&&(u.setAttribute(`aria-pressed`,`false`),u.setAttribute(`aria-label`,`Edit file`),u.classList.toggle(`hidden`,!c)),await this.renderPreview(i,s,e);else if(this.isRenderTokenCurrent(e)){if(this.isFileEditMode&&c){o?.classList.add(`modal-body--editing`),i.classList.add(`hidden`),l?.classList.add(`active`),u instanceof HTMLButtonElement&&(u.setAttribute(`aria-pressed`,`true`),u.setAttribute(`aria-label`,`Switch to raw text view`),u.classList.remove(`hidden`));let e=l?.querySelector(`.file-editor`);if(e instanceof HTMLTextAreaElement){e.setAttribute(`tab-size`,`2`);let n=this.getLanguageFromFilename(t.name);if(n?e.setAttribute(`language`,n):e.removeAttribute(`language`),this.isEditorDirty)typeof s?.content==`string`&&(e.value!==s.content&&(e.value=s.content),this.updateEditorHighlight(e.value));else{let n=t.content||``;e.value!==n&&(e.value=n),this.updateEditorHighlight(e.value)}e.dispatchEvent(new Event(`scroll`))}}else o?.classList.remove(`modal-body--editing`),i.classList.remove(`hidden`),l?.classList.remove(`active`),u instanceof HTMLButtonElement&&(u.setAttribute(`aria-pressed`,`false`),u.setAttribute(`aria-label`,`Edit file`),u.classList.toggle(`hidden`,!c)),i.classList.add(`file-content--raw`),i.classList.remove(`file-content--preview`,`file-content--iframe`),i.textContent=t.kind===`binary`?`Binary file (${t.mimeType||`application/octet-stream`}). Switch to Preview to view.`:s.content||``}}syncIframeTheme(){if(!this.previewFrameWindow)return;let e=document.documentElement.classList.contains(`dark-mode`),t=getComputedStyle(document.documentElement),n={};for(let e=0;e<t.length;e++){let r=t[e];r.startsWith(`--`)&&(n[r]=t.getPropertyValue(r))}this.previewFrameWindow.postMessage({type:`shadow-claw-theme-update`,theme:e?`dark`:`light`,customProperties:n},`*`)}async handleStorageProxyRequest(e,t,n,r){if(!t)return;let i=W.file,a=i?.path||i?.name||`__default__`;try{let i;switch(n){case`setItem`:await M(a,String(r.key||``),r.value);break;case`removeItem`:await j(a,String(r.key||``));break;case`clear`:await F(a);break;case`getAllItems`:i=await B(a);break;case`idb-get`:i=await R(`${a}::idb::${r.dbName}::${r.storeName}`,String(r.key||``));break;case`idb-getAll`:i=await B(`${a}::idb::${r.dbName}::${r.storeName}`);break;case`idb-put`:{let e=r.key==null?`__auto_${Date.now()}`:String(r.key);await M(`${a}::idb::${r.dbName}::${r.storeName}`,e,r.value),i=e;break}case`idb-delete`:await j(`${a}::idb::${r.dbName}::${r.storeName}`,String(r.key||``));break;case`idb-clear`:await F(`${a}::idb::${r.dbName}::${r.storeName}`);break;case`idb-deleteDatabase`:await F(`${a}::idb::${r.dbName}::__default__`);break;default:throw Error(`Unknown storage proxy method: ${n}`)}e.postMessage({type:`shadow-claw-storage-proxy-result`,requestId:t,result:i??null},`*`)}catch(n){e.postMessage({type:`shadow-claw-storage-proxy-result`,requestId:t,error:n instanceof Error?n.message:String(n)},`*`)}}async reloadPreviewWithSearchParams(e){let t=W.file;if(!t)return;let n=this.shadowRoot?.querySelector(`.file-viewer__iframe`);n&&(this.previewFrameWindow=null,o(n,await this.buildIframePreviewSrcdoc(t,e)))}};customElements.get(X)||customElements.define(X,$);export{$ as ShadowClawFileViewer};