titan-agent 7.0.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (343) hide show
  1. package/README.md +54 -2
  2. package/dist/agent/agent.js +55 -10
  3. package/dist/agent/agent.js.map +1 -1
  4. package/dist/agent/contextManager.js +1 -1
  5. package/dist/agent/contextManager.js.map +1 -1
  6. package/dist/agent/honestyGuard.js +66 -0
  7. package/dist/agent/honestyGuard.js.map +1 -0
  8. package/dist/agent/selfCritique.js +101 -0
  9. package/dist/agent/selfCritique.js.map +1 -0
  10. package/dist/agent/toolSearch.js +9 -2
  11. package/dist/agent/toolSearch.js.map +1 -1
  12. package/dist/agent/trajectoryLogger.js +19 -2
  13. package/dist/agent/trajectoryLogger.js.map +1 -1
  14. package/dist/analytics/collector.js +1 -1
  15. package/dist/analytics/collector.js.map +1 -1
  16. package/dist/config/schema.js +32 -0
  17. package/dist/config/schema.js.map +1 -1
  18. package/dist/eval/harness.js +4 -1
  19. package/dist/eval/harness.js.map +1 -1
  20. package/dist/gateway/server.js +24 -8
  21. package/dist/gateway/server.js.map +1 -1
  22. package/dist/gateway/slashCommands.js +31 -0
  23. package/dist/gateway/slashCommands.js.map +1 -1
  24. package/dist/mcp/agentTools.js +135 -0
  25. package/dist/mcp/agentTools.js.map +1 -0
  26. package/dist/mcp/server.js +19 -2
  27. package/dist/mcp/server.js.map +1 -1
  28. package/dist/memory/graph.js +2 -0
  29. package/dist/memory/graph.js.map +1 -1
  30. package/dist/providers/errorTaxonomy.js +4 -0
  31. package/dist/providers/errorTaxonomy.js.map +1 -1
  32. package/dist/providers/moa.js +151 -0
  33. package/dist/providers/moa.js.map +1 -0
  34. package/dist/providers/modelCapabilities.js +65 -2
  35. package/dist/providers/modelCapabilities.js.map +1 -1
  36. package/dist/providers/ollama.js +1 -0
  37. package/dist/providers/ollama.js.map +1 -1
  38. package/dist/providers/openai_compat.js +14 -2
  39. package/dist/providers/openai_compat.js.map +1 -1
  40. package/dist/providers/router.js +3 -1
  41. package/dist/providers/router.js.map +1 -1
  42. package/dist/utils/benchMode.js +8 -0
  43. package/dist/utils/benchMode.js.map +1 -0
  44. package/dist/utils/constants.js +1 -1
  45. package/dist/utils/constants.js.map +1 -1
  46. package/package.json +26 -26
  47. package/ui/dist/assets/AboutYouMemory-57X5SqHQ.js +1 -0
  48. package/ui/dist/assets/AuditPanel-AyB8ciLZ.js +1 -0
  49. package/ui/dist/assets/AutonomyPanel-wmVPr-n3.js +1 -0
  50. package/ui/dist/assets/AutopilotPanel-CbLy4lJP.js +1 -0
  51. package/ui/dist/assets/AutoresearchPanel-DxRO1rBF.js +1 -0
  52. package/ui/dist/assets/BackupPanel-BUh9rQ-3.js +1 -0
  53. package/ui/dist/assets/BrowserPanel-OqKwGrIL.js +1 -0
  54. package/ui/dist/assets/CPActivity-DGfS7EY3.js +1 -0
  55. package/ui/dist/assets/CPAgentDetail-p0Kvzhhb.js +1 -0
  56. package/ui/dist/assets/CPAgents-B6wSSQZM.js +1 -0
  57. package/ui/dist/assets/CPApprovals-CYv9Do0i.js +1 -0
  58. package/ui/dist/assets/CPCosts-Dx6Q71rN.js +1 -0
  59. package/ui/dist/assets/CPDashboard-DA8-tE-l.js +1 -0
  60. package/ui/dist/assets/CPFiles-BJ49tzai.js +1 -0
  61. package/ui/dist/assets/CPGoals-h0dKL5V_.js +1 -0
  62. package/ui/dist/assets/CPInbox-CDvefgNH.js +1 -0
  63. package/ui/dist/assets/CPIssueDetail-CnmLzzDD.js +1 -0
  64. package/ui/dist/assets/CPIssues-DknAIMyl.js +1 -0
  65. package/ui/dist/assets/CPLayout-C2nqgkmY.js +2 -0
  66. package/ui/dist/assets/CPOrg-tDbHFphX.js +1 -0
  67. package/ui/dist/assets/CPRuns-UlrIURqG.js +1 -0
  68. package/ui/dist/assets/CPSocial-B-gHgvEw.js +1 -0
  69. package/ui/dist/assets/CPVoice-CJy938ZF.js +1 -0
  70. package/ui/dist/assets/ChannelsPanel-DLbxg1zO.js +1 -0
  71. package/ui/dist/assets/CheckpointsPanel-BB6TT0aE.js +1 -0
  72. package/ui/dist/assets/CommandPostHub-fIslwU_t.js +2 -0
  73. package/ui/dist/assets/ConfirmDialog-6hcNjmAh.js +9 -0
  74. package/ui/dist/assets/CronPanel-DLpw3Y25.js +1 -0
  75. package/ui/dist/assets/DataTable-KVqtDzvP.js +1 -0
  76. package/ui/dist/assets/DreamPanel-lcMXpbEb.js +5 -0
  77. package/ui/dist/assets/EmptyState-D-Dg8B8r.js +1 -0
  78. package/ui/dist/assets/EvalHarnessPanel-BKzRiiQw.js +2 -0
  79. package/ui/dist/assets/EvalPanel-Dtodacmj.js +1 -0
  80. package/ui/dist/assets/FileViewer-DjcVKkO2.js +60 -0
  81. package/ui/dist/assets/FilesPanel-BI90Pplh.js +1 -0
  82. package/ui/dist/assets/FleetPanel-tr0wjAwr.js +1 -0
  83. package/ui/dist/assets/HomelabPanel-m8vMm5rE.js +1 -0
  84. package/ui/dist/assets/InfraView-3WriJnyE.js +2 -0
  85. package/ui/dist/assets/IntegrationsPanel-BmL70fOw.js +1 -0
  86. package/ui/dist/assets/IntelligenceView-BGVxCKD3.js +2 -0
  87. package/ui/dist/assets/LearningPanel-CrYLQ6eV.js +1 -0
  88. package/ui/dist/assets/LiveStudio-CnW3eZYF.js +2 -0
  89. package/ui/dist/assets/LogsPanel-DbShr4Ic.js +1 -0
  90. package/ui/dist/assets/McpPanel-uMYEsPI4.js +1 -0
  91. package/ui/dist/assets/MemoryGraphPanel-C7-Z8f0v.js +1 -0
  92. package/ui/dist/assets/MemoryTaxonomyPanel-KrxN8U1G.js +1 -0
  93. package/ui/dist/assets/MemoryWikiPanel-DI3q6IHC.js +1 -0
  94. package/ui/dist/assets/MeshPanel-D4-g2tlu.js +1 -0
  95. package/ui/dist/assets/MissionCanvas-D8cjakJe.js +61 -0
  96. package/ui/dist/assets/MissionChat-BvqCUf1E.js +3 -0
  97. package/ui/dist/assets/MissionLibrary-CZoJQ9WD.js +1 -0
  98. package/ui/dist/assets/MissionStart-CXCq-_AD.js +1 -0
  99. package/ui/dist/assets/NvidiaPanel-BfI1K5Pg.js +1 -0
  100. package/ui/dist/assets/OrganismPanel-B7Gm9pP-.js +1 -0
  101. package/ui/dist/assets/OverviewPanel-B9tKWRK2.js +1 -0
  102. package/ui/dist/assets/PageHeader-CH85uoZG.js +1 -0
  103. package/ui/dist/assets/PersonaProfilesPanel-BPi8fl-U.js +3 -0
  104. package/ui/dist/assets/PersonasPanel-Dwr7sycT.js +1 -0
  105. package/ui/dist/assets/PhoneDeskPanel-D7qc6wUI.js +1 -0
  106. package/ui/dist/assets/RecipesPanel-DcqPWRSU.js +1 -0
  107. package/ui/dist/assets/SecurityPanel-Bv_B9Ahf.js +1 -0
  108. package/ui/dist/assets/SelfImprovePanel-Ca4rGwEG.js +1 -0
  109. package/ui/dist/assets/SelfProposalsPanel-DteMSASq.js +1 -0
  110. package/ui/dist/assets/SessionsPanel-BdbbKTbL.js +1 -0
  111. package/ui/dist/assets/SessionsTab-BJipiVJs.js +1 -0
  112. package/ui/dist/assets/SettingsPanel-mV7ykOCc.js +1 -0
  113. package/ui/dist/assets/SettingsView-Bu_wYTT5.js +2 -0
  114. package/ui/dist/assets/SkeletonLoader-9H7QWa9E.js +1 -0
  115. package/ui/dist/assets/SkillsPanel-CHwX2kDR.js +1 -0
  116. package/ui/dist/assets/SomaView-Bpsm4ZW7.js +5 -0
  117. package/ui/dist/assets/SomaView-Dghh9om4.css +1 -0
  118. package/ui/dist/assets/StatCard-wmSgMAM3.js +1 -0
  119. package/ui/dist/assets/TeamsPanel-XJiHxdDX.js +1 -0
  120. package/ui/dist/assets/TelemetryPanel-_pmGVxpO.js +1 -0
  121. package/ui/dist/assets/TitanCanvas-Cb7KG80W.css +1 -0
  122. package/ui/dist/assets/TitanCanvas-CmLy7p2N.js +883 -0
  123. package/ui/dist/assets/ToolsView-PHizHZBx.js +2 -0
  124. package/ui/dist/assets/TraceViewer-CYAzIcfB.js +1 -0
  125. package/ui/dist/assets/TracesPanel-CRSN_dzK.js +1 -0
  126. package/ui/dist/assets/TrainingPanel-B9rcuMsV.js +1 -0
  127. package/ui/dist/assets/VoiceOverlay-BL_ns1ZA.js +7 -0
  128. package/ui/dist/assets/VramPanel-BNPQ06_9.js +1 -0
  129. package/ui/dist/assets/WatchView-BgAkNnur.js +13 -0
  130. package/ui/dist/assets/WorkTab-RRpPpEOg.js +1 -0
  131. package/ui/dist/assets/WorkflowBuilderPanel-BPHIH8pf.js +1 -0
  132. package/ui/dist/assets/WorkflowsPanel-DqtmT0NB.js +1 -0
  133. package/ui/dist/assets/approvalHeadline-BRg3ReTi.js +1 -0
  134. package/ui/dist/assets/archive-DcK9HrbE.js +1 -0
  135. package/ui/dist/assets/arrow-left-4c2FnES1.js +1 -0
  136. package/ui/dist/assets/book-open-Ds_yciQm.js +1 -0
  137. package/ui/dist/assets/bot-CWDCc265.js +1 -0
  138. package/ui/dist/assets/chart-column-hhZMdCgB.js +1 -0
  139. package/ui/dist/assets/chevron-right-A_pvnRh_.js +1 -0
  140. package/ui/dist/assets/circle-check-big-C-JUM7wb.js +1 -0
  141. package/ui/dist/assets/circle-stop-yZuG9ZAE.js +1 -0
  142. package/ui/dist/assets/clipboard-list-C2HUEjZc.js +1 -0
  143. package/ui/dist/assets/clock-DSPgndSD.js +1 -0
  144. package/ui/dist/assets/clsx-CjueKrWZ.js +1 -0
  145. package/ui/dist/assets/createLucideIcon-qnlrxww7.js +1 -0
  146. package/ui/dist/assets/database-C1SgHa8T.js +1 -0
  147. package/ui/dist/assets/dollar-sign-D9siqK91.js +1 -0
  148. package/ui/dist/assets/download-CJZWQNfV.js +1 -0
  149. package/ui/dist/assets/external-link-CpQLWKKE.js +1 -0
  150. package/ui/dist/assets/file-text-BbGTi-Po.js +1 -0
  151. package/ui/dist/assets/flask-conical-B1YVft4E.js +1 -0
  152. package/ui/dist/assets/folder-EbR-w2Mq.js +1 -0
  153. package/ui/dist/assets/funnel-D2Dkn8Pf.js +1 -0
  154. package/ui/dist/assets/git-branch-CQ2yNSzU.js +1 -0
  155. package/ui/dist/assets/git-pull-request-BxL5wlGX.js +1 -0
  156. package/ui/dist/assets/index-Cz8190xO.css +2 -0
  157. package/ui/dist/assets/index-WI-E4I3h.js +243 -0
  158. package/ui/dist/assets/jsx-runtime-B15e6lOy.js +1 -0
  159. package/ui/dist/assets/layers-BPu5SRjI.js +1 -0
  160. package/ui/dist/assets/legacy-BIzifT-t.js +3 -0
  161. package/ui/dist/assets/lightbulb-BY7CpMte.js +1 -0
  162. package/ui/dist/assets/link-VDQkrGJw.js +1 -0
  163. package/ui/dist/assets/list-todo-DfnNUV_T.js +1 -0
  164. package/ui/dist/assets/message-square-BpzrINHz.js +1 -0
  165. package/ui/dist/assets/mic-De6oZFaV.js +1 -0
  166. package/ui/dist/assets/missions-y-qg_f9b.js +1 -0
  167. package/ui/dist/assets/network-CM7y1ats.js +1 -0
  168. package/ui/dist/assets/pause-C4TDJSfA.js +1 -0
  169. package/ui/dist/assets/pencil-Dd_vzHE-.js +1 -0
  170. package/ui/dist/assets/play-9WxZWVHA.js +1 -0
  171. package/ui/dist/assets/plug-Dm25Wbrc.js +1 -0
  172. package/ui/dist/assets/plus-CHryCIkk.js +1 -0
  173. package/ui/dist/assets/radio-D-XnoAVu.js +1 -0
  174. package/ui/dist/assets/refresh-cw-Disd5wRB.js +1 -0
  175. package/ui/dist/assets/rotate-ccw-Cw1T2W1T.js +1 -0
  176. package/ui/dist/assets/save-DP7oNar2.js +1 -0
  177. package/ui/dist/assets/search-aNVcX-nv.js +1 -0
  178. package/ui/dist/assets/send-D7iQD57b.js +1 -0
  179. package/ui/dist/assets/server-DFfeYjoM.js +1 -0
  180. package/ui/dist/assets/settings-5NWXzgyY.js +1 -0
  181. package/ui/dist/assets/shared-DLz_Jtg3.js +1 -0
  182. package/ui/dist/assets/shield-check-Cd50jCAn.js +1 -0
  183. package/ui/dist/assets/square-DlcoJ1ZM.js +1 -0
  184. package/ui/dist/assets/terminal-DgFz2Vsf.js +1 -0
  185. package/ui/dist/assets/test-tube-BimtS92_.js +1 -0
  186. package/ui/dist/assets/toggle-right-BMaR-sfT.js +1 -0
  187. package/ui/dist/assets/trash-2-CwUv7ww1.js +1 -0
  188. package/ui/dist/assets/trending-up-Ba9TwEow.js +1 -0
  189. package/ui/dist/assets/trophy-Gfv1QC45.js +1 -0
  190. package/ui/dist/assets/volume-2-BVlfVl2U.js +1 -0
  191. package/ui/dist/assets/wifi-off-CWLeusSV.js +1 -0
  192. package/ui/dist/assets/zoom-out-DeggJ7RM.js +1 -0
  193. package/ui/dist/index.html +4 -2
  194. package/ui/dist/sw.js +1 -1
  195. package/ui/dist/assets/AboutYouMemory-CZKEOd_O.js +0 -11
  196. package/ui/dist/assets/AuditPanel-Bu71N5Er.js +0 -1
  197. package/ui/dist/assets/AutonomyPanel-DB-39dX4.js +0 -11
  198. package/ui/dist/assets/AutopilotPanel-Cj8oKxWv.js +0 -1
  199. package/ui/dist/assets/AutoresearchPanel-3s8pjm6Z.js +0 -6
  200. package/ui/dist/assets/BackupPanel-EUQJMJE7.js +0 -1
  201. package/ui/dist/assets/BrowserPanel-Beo4F5Ar.js +0 -6
  202. package/ui/dist/assets/Button-MdXmb4_n.js +0 -1
  203. package/ui/dist/assets/CPActivity-B1Se9VVc.js +0 -1
  204. package/ui/dist/assets/CPAgentDetail-BYji6tT8.js +0 -1
  205. package/ui/dist/assets/CPAgents-BSUKucTe.js +0 -1
  206. package/ui/dist/assets/CPApprovals-B4v0em6e.js +0 -1
  207. package/ui/dist/assets/CPCosts-9ikh61Kv.js +0 -1
  208. package/ui/dist/assets/CPDashboard-sOok2T5v.js +0 -1
  209. package/ui/dist/assets/CPFiles-DB2nY5JE.js +0 -1
  210. package/ui/dist/assets/CPGoals-8Z1yOY8e.js +0 -1
  211. package/ui/dist/assets/CPInbox-Cq6-UY8F.js +0 -11
  212. package/ui/dist/assets/CPIssueDetail-NAGfmJg8.js +0 -1
  213. package/ui/dist/assets/CPIssues-BzX6Rckx.js +0 -1
  214. package/ui/dist/assets/CPLayout-BcRM6QSg.js +0 -2
  215. package/ui/dist/assets/CPOrg-B7DQ4UQP.js +0 -1
  216. package/ui/dist/assets/CPRuns-D-cpPw_M.js +0 -1
  217. package/ui/dist/assets/CPSocial-DshtmcK0.js +0 -11
  218. package/ui/dist/assets/CPVoice-DfXRnQVU.js +0 -1
  219. package/ui/dist/assets/ChannelsPanel-BnaTOeyf.js +0 -1
  220. package/ui/dist/assets/CheckpointsPanel-C62naE4U.js +0 -1
  221. package/ui/dist/assets/CommandPostHub-B_L1CAss.js +0 -24
  222. package/ui/dist/assets/ConfirmDialog-VErHWAbo.js +0 -1
  223. package/ui/dist/assets/CronPanel-BwMrrZ5d.js +0 -1
  224. package/ui/dist/assets/DataTable-BCqSUuN7.js +0 -1
  225. package/ui/dist/assets/DreamPanel-BNAcCLBB.js +0 -15
  226. package/ui/dist/assets/EmptyState-D9kQf1PX.js +0 -1
  227. package/ui/dist/assets/EvalHarnessPanel-BaMLdBNm.js +0 -2
  228. package/ui/dist/assets/EvalPanel-CW-SSjtg.js +0 -1
  229. package/ui/dist/assets/FileViewer-BL00nsd7.js +0 -61
  230. package/ui/dist/assets/FilesPanel-CeC6YUSd.js +0 -16
  231. package/ui/dist/assets/FleetPanel-EyWF7l3W.js +0 -1
  232. package/ui/dist/assets/HomelabPanel-BRfKRYe7.js +0 -6
  233. package/ui/dist/assets/InfraView-Jmqhg_Yc.js +0 -2
  234. package/ui/dist/assets/InlineEditableField-DgMrLDj1.js +0 -1
  235. package/ui/dist/assets/Input-CBTwa_Iw.js +0 -1
  236. package/ui/dist/assets/IntegrationsPanel-DQL-7Ec6.js +0 -1
  237. package/ui/dist/assets/IntelligenceView-DxD78qfP.js +0 -2
  238. package/ui/dist/assets/LearningPanel-C_JzSbJU.js +0 -1
  239. package/ui/dist/assets/LiveStudio-Db5yeaWo.js +0 -7
  240. package/ui/dist/assets/LogsPanel-CpinKwaZ.js +0 -1
  241. package/ui/dist/assets/McpPanel-D-MqN_f-.js +0 -1
  242. package/ui/dist/assets/MemoryGraphPanel-BnD5jRqf.js +0 -1
  243. package/ui/dist/assets/MemoryTaxonomyPanel-BBI202dd.js +0 -6
  244. package/ui/dist/assets/MemoryWikiPanel-Dn3XZHL0.js +0 -6
  245. package/ui/dist/assets/MeshPanel-C-mRJpr0.js +0 -11
  246. package/ui/dist/assets/MissionCanvas-CbZW83Ch.js +0 -72
  247. package/ui/dist/assets/MissionChat-Bs75jPAD.js +0 -7
  248. package/ui/dist/assets/MissionLibrary-BxQ6SxPe.js +0 -5
  249. package/ui/dist/assets/MissionStart-CBuBPasl.js +0 -1
  250. package/ui/dist/assets/Modal-ybPGvlQs.js +0 -9
  251. package/ui/dist/assets/NvidiaPanel-DdG13OX4.js +0 -1
  252. package/ui/dist/assets/OrganismPanel-xZWUJKyr.js +0 -1
  253. package/ui/dist/assets/OverviewPanel-B45ZYhJV.js +0 -1
  254. package/ui/dist/assets/PageHeader-DdrbS1aq.js +0 -1
  255. package/ui/dist/assets/PersonaProfilesPanel-CKER-EU5.js +0 -8
  256. package/ui/dist/assets/PersonasPanel-CMMQ3nh3.js +0 -1
  257. package/ui/dist/assets/PhoneDeskPanel-Bw_Y-cVE.js +0 -11
  258. package/ui/dist/assets/RecipesPanel-DzMcxpJJ.js +0 -1
  259. package/ui/dist/assets/SecurityPanel-BCq3Fzbr.js +0 -1
  260. package/ui/dist/assets/SelfImprovePanel-YE3hT8jK.js +0 -1
  261. package/ui/dist/assets/SelfProposalsPanel-DXuqBM6p.js +0 -1
  262. package/ui/dist/assets/SessionsPanel-DORz5goR.js +0 -1
  263. package/ui/dist/assets/SessionsTab-qYHDOuC8.js +0 -1
  264. package/ui/dist/assets/SettingsPanel-BbwPu1i7.js +0 -1
  265. package/ui/dist/assets/SettingsView-zgqkDDBJ.js +0 -2
  266. package/ui/dist/assets/SkeletonLoader-r6OGXaU9.js +0 -1
  267. package/ui/dist/assets/SkillsPanel-BjEOBMRo.js +0 -11
  268. package/ui/dist/assets/SomaView-BtCkeWfZ.css +0 -1
  269. package/ui/dist/assets/SomaView-DLzApZVW.js +0 -5
  270. package/ui/dist/assets/StatCard-DLq8aBps.js +0 -1
  271. package/ui/dist/assets/StatusBadge-BqlvIbdj.js +0 -1
  272. package/ui/dist/assets/Tabs-DdUThlp1.js +0 -1
  273. package/ui/dist/assets/TeamsPanel-uIIKoU7I.js +0 -1
  274. package/ui/dist/assets/TelemetryPanel-dVr3yQQr.js +0 -1
  275. package/ui/dist/assets/TitanCanvas-BfitWg9R.css +0 -1
  276. package/ui/dist/assets/TitanCanvas-xHAJqwG2.js +0 -945
  277. package/ui/dist/assets/ToolsView-CG1mZdiy.js +0 -2
  278. package/ui/dist/assets/Tooltip-C2tXJcrN.js +0 -6
  279. package/ui/dist/assets/TraceViewer-BIMD_Osr.js +0 -1
  280. package/ui/dist/assets/TracesPanel-nMUiyMj5.js +0 -1
  281. package/ui/dist/assets/TrainingPanel-CT5R4HWm.js +0 -1
  282. package/ui/dist/assets/VoiceOverlay-Br4QnCtw.js +0 -17
  283. package/ui/dist/assets/VramPanel-CdnJYytg.js +0 -1
  284. package/ui/dist/assets/WatchView-TNU6Ns1Q.js +0 -13
  285. package/ui/dist/assets/WorkTab-wTlX_UKP.js +0 -1
  286. package/ui/dist/assets/WorkflowBuilderPanel-CDpVt5ux.js +0 -6
  287. package/ui/dist/assets/WorkflowsPanel-zsFqsLdn.js +0 -11
  288. package/ui/dist/assets/approvalHeadline-DB9SgR-9.js +0 -1
  289. package/ui/dist/assets/archive-Bh689DNg.js +0 -6
  290. package/ui/dist/assets/arrow-left-WkVYLm80.js +0 -6
  291. package/ui/dist/assets/book-open-ohEXgUsS.js +0 -6
  292. package/ui/dist/assets/bot-DvEcyQcD.js +0 -6
  293. package/ui/dist/assets/chart-column-w3goFd5f.js +0 -6
  294. package/ui/dist/assets/check-CuRYh4Zh.js +0 -6
  295. package/ui/dist/assets/chevron-right-DbLSHmff.js +0 -6
  296. package/ui/dist/assets/circle-check-big-Bkba568b.js +0 -6
  297. package/ui/dist/assets/circle-stop-Bx2ohEg8.js +0 -6
  298. package/ui/dist/assets/clipboard-list-Dj9tORnu.js +0 -6
  299. package/ui/dist/assets/clock-JyQAYy6X.js +0 -6
  300. package/ui/dist/assets/clsx-B-dksMZM.js +0 -1
  301. package/ui/dist/assets/dollar-sign-XxwPAA2a.js +0 -6
  302. package/ui/dist/assets/download-D1izVEOL.js +0 -6
  303. package/ui/dist/assets/external-link-DZ_rZsIt.js +0 -6
  304. package/ui/dist/assets/file-text-Cfawu8Bs.js +0 -6
  305. package/ui/dist/assets/flask-conical-Ql8QxhgY.js +0 -6
  306. package/ui/dist/assets/folder-DAdIw-Pb.js +0 -6
  307. package/ui/dist/assets/funnel-FycfZcXo.js +0 -6
  308. package/ui/dist/assets/git-branch-C2qrhGGu.js +0 -6
  309. package/ui/dist/assets/index-Cml2x9pA.js +0 -507
  310. package/ui/dist/assets/index-yWybhcfI.css +0 -1
  311. package/ui/dist/assets/layers-yzjtGlHB.js +0 -6
  312. package/ui/dist/assets/legacy-D21WSMF1.js +0 -3
  313. package/ui/dist/assets/lightbulb-BZJNK69S.js +0 -6
  314. package/ui/dist/assets/link-CnFkBkaY.js +0 -6
  315. package/ui/dist/assets/list-todo-BlgfQHup.js +0 -6
  316. package/ui/dist/assets/message-square-CRsG9u6_.js +0 -6
  317. package/ui/dist/assets/mic-B32RHc7Y.js +0 -6
  318. package/ui/dist/assets/missions-1iw8Z2_0.js +0 -1
  319. package/ui/dist/assets/network-C9RXQGrV.js +0 -6
  320. package/ui/dist/assets/pause-BT1Bc2q3.js +0 -6
  321. package/ui/dist/assets/pencil-BK5IU6o0.js +0 -6
  322. package/ui/dist/assets/play-Cl1nC_gc.js +0 -6
  323. package/ui/dist/assets/plug-DvcpOalj.js +0 -6
  324. package/ui/dist/assets/plus-Dpo1qfrl.js +0 -6
  325. package/ui/dist/assets/radio-C5c9IyqX.js +0 -6
  326. package/ui/dist/assets/refresh-cw-C-iZkzuS.js +0 -6
  327. package/ui/dist/assets/rotate-ccw-qzrB3SNw.js +0 -6
  328. package/ui/dist/assets/save-DwR9wQVu.js +0 -6
  329. package/ui/dist/assets/search-D10l0m3-.js +0 -6
  330. package/ui/dist/assets/send-DtXGsaFW.js +0 -6
  331. package/ui/dist/assets/server-BzisF3LL.js +0 -6
  332. package/ui/dist/assets/settings-Dbwd1_-c.js +0 -6
  333. package/ui/dist/assets/shield-check-CXlDJyAW.js +0 -6
  334. package/ui/dist/assets/square-BBC-JKzY.js +0 -11
  335. package/ui/dist/assets/terminal-DaBIlWEM.js +0 -6
  336. package/ui/dist/assets/test-tube-CDATRD5t.js +0 -11
  337. package/ui/dist/assets/toggle-right-DTmrC5RD.js +0 -11
  338. package/ui/dist/assets/trash-2-CTeyjxD_.js +0 -6
  339. package/ui/dist/assets/trending-up-CXPRjRV4.js +0 -6
  340. package/ui/dist/assets/trophy-DbVdXRtU.js +0 -6
  341. package/ui/dist/assets/volume-2-DYDBmm3M.js +0 -6
  342. package/ui/dist/assets/wifi-off-BBuIGbiP.js +0 -6
  343. package/ui/dist/assets/zoom-out-D47_pRAO.js +0 -16
@@ -1,945 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SomaView-DLzApZVW.js","assets/index-Cml2x9pA.js","assets/index-yWybhcfI.css","assets/Button-MdXmb4_n.js","assets/clsx-B-dksMZM.js","assets/Input-CBTwa_Iw.js","assets/Tooltip-C2tXJcrN.js","assets/SomaView-BtCkeWfZ.css","assets/CommandPostHub-B_L1CAss.js","assets/Modal-ybPGvlQs.js","assets/InlineEditableField-DgMrLDj1.js","assets/check-CuRYh4Zh.js","assets/pencil-BK5IU6o0.js","assets/ConfirmDialog-VErHWAbo.js","assets/approvalHeadline-DB9SgR-9.js","assets/chevron-right-DbLSHmff.js","assets/bot-DvEcyQcD.js","assets/pause-BT1Bc2q3.js","assets/dollar-sign-XxwPAA2a.js","assets/git-branch-C2qrhGGu.js","assets/chart-column-w3goFd5f.js","assets/clock-JyQAYy6X.js","assets/message-square-CRsG9u6_.js","assets/file-text-Cfawu8Bs.js","assets/terminal-DaBIlWEM.js","assets/refresh-cw-C-iZkzuS.js","assets/circle-stop-Bx2ohEg8.js","assets/send-DtXGsaFW.js","assets/plus-Dpo1qfrl.js","assets/trash-2-CTeyjxD_.js","assets/IntelligenceView-DxD78qfP.js","assets/MemoryGraphPanel-BnD5jRqf.js","assets/network-C9RXQGrV.js","assets/zoom-out-D47_pRAO.js","assets/search-D10l0m3-.js","assets/InfraView-Jmqhg_Yc.js","assets/ToolsView-CG1mZdiy.js","assets/SettingsView-zgqkDDBJ.js","assets/SettingsPanel-BbwPu1i7.js","assets/PageHeader-DdrbS1aq.js","assets/circle-check-big-Bkba568b.js","assets/mic-B32RHc7Y.js","assets/wifi-off-BBuIGbiP.js","assets/download-D1izVEOL.js","assets/play-Cl1nC_gc.js","assets/save-DwR9wQVu.js","assets/SecurityPanel-BCq3Fzbr.js","assets/shield-check-CXlDJyAW.js","assets/AuditPanel-Bu71N5Er.js","assets/funnel-FycfZcXo.js","assets/clipboard-list-Dj9tORnu.js","assets/AutopilotPanel-Cj8oKxWv.js","assets/WorkflowsPanel-zsFqsLdn.js","assets/toggle-right-DTmrC5RD.js","assets/book-open-ohEXgUsS.js","assets/LearningPanel-C_JzSbJU.js","assets/lightbulb-BZJNK69S.js","assets/trending-up-CXPRjRV4.js","assets/square-BBC-JKzY.js","assets/settings-Dbwd1_-c.js","assets/server-BzisF3LL.js","assets/rotate-ccw-qzrB3SNw.js","assets/flask-conical-Ql8QxhgY.js","assets/archive-Bh689DNg.js","assets/radio-C5c9IyqX.js","assets/test-tube-CDATRD5t.js","assets/VoiceOverlay-Br4QnCtw.js","assets/volume-2-DYDBmm3M.js","assets/folder-DAdIw-Pb.js","assets/external-link-DZ_rZsIt.js","assets/link-CnFkBkaY.js","assets/SelfImprovePanel-YE3hT8jK.js","assets/trophy-DbVdXRtU.js","assets/PersonasPanel-CMMQ3nh3.js","assets/PersonaProfilesPanel-CKER-EU5.js","assets/DreamPanel-BNAcCLBB.js","assets/HomelabPanel-BRfKRYe7.js","assets/StatCard-DLq8aBps.js","assets/SkeletonLoader-r6OGXaU9.js","assets/NvidiaPanel-DdG13OX4.js","assets/FilesPanel-CeC6YUSd.js","assets/arrow-left-WkVYLm80.js","assets/LogsPanel-CpinKwaZ.js","assets/TelemetryPanel-dVr3yQQr.js","assets/SkillsPanel-BjEOBMRo.js","assets/McpPanel-D-MqN_f-.js","assets/plug-DvcpOalj.js","assets/IntegrationsPanel-DQL-7Ec6.js","assets/ChannelsPanel-BnaTOeyf.js","assets/MeshPanel-C-mRJpr0.js","assets/DataTable-BCqSUuN7.js","assets/MemoryWikiPanel-Dn3XZHL0.js","assets/AutoresearchPanel-3s8pjm6Z.js","assets/SelfProposalsPanel-DXuqBM6p.js","assets/OverviewPanel-B45ZYhJV.js","assets/layers-yzjtGlHB.js","assets/SessionsPanel-DORz5goR.js","assets/WatchView-TNU6Ns1Q.js","assets/BackupPanel-EUQJMJE7.js","assets/TrainingPanel-CT5R4HWm.js","assets/RecipesPanel-DzMcxpJJ.js","assets/EmptyState-D9kQf1PX.js","assets/VramPanel-CdnJYytg.js","assets/TeamsPanel-uIIKoU7I.js","assets/CronPanel-BwMrrZ5d.js","assets/CheckpointsPanel-C62naE4U.js","assets/OrganismPanel-xZWUJKyr.js","assets/FleetPanel-EyWF7l3W.js","assets/BrowserPanel-Beo4F5Ar.js","assets/EvalPanel-CW-SSjtg.js","assets/legacy-D21WSMF1.js"])))=>i.map(i=>d[i]);
2
- var Ll=Object.defineProperty;var Dl=(t,e,s)=>e in t?Ll(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var Fe=(t,e,s)=>Dl(t,typeof e!="symbol"?e+"":e,s);import{c as Ze,a as tt,g as Ml,r as w,j as n,b as ue,W as Rr,B as bt,H as Ol,s as da,T as ua,u as ha,d as Pl,e as Wl,X as Ts,f as Ul,h as Bl,S as qt,E as fa,A as Kt,C as Ir,U as Lr,i as Dr,G as pa,R as re,_ as ae,Z as Fl,k as bn,I as bi,l as $l,m as zl,L as ma,n as Hl,M as Vl,o as Gl,p as Yl,q as ql,t as Kl,v as Bn}from"./index-Cml2x9pA.js";import{Z as Jl,a as Xl,M as Zl}from"./zoom-out-D47_pRAO.js";import{C as xi}from"./ConfirmDialog-VErHWAbo.js";import{C as Ql,S as ec}from"./square-BBC-JKzY.js";import{P as tc}from"./plus-Dpo1qfrl.js";import{F as xn}from"./file-text-Cfawu8Bs.js";import{S as Mr}from"./settings-Dbwd1_-c.js";import{S as Or}from"./server-BzisF3LL.js";import{N as ga}from"./network-C9RXQGrV.js";import{T as ya}from"./terminal-DaBIlWEM.js";import{B as ys}from"./book-open-ohEXgUsS.js";import{S as wn}from"./save-DwR9wQVu.js";import{P as sc}from"./pencil-BK5IU6o0.js";import{R as ba}from"./rotate-ccw-qzrB3SNw.js";import{S as xa}from"./search-D10l0m3-.js";import{S as wa}from"./send-DtXGsaFW.js";import{M as vn}from"./message-square-CRsG9u6_.js";import{M as va}from"./mic-B32RHc7Y.js";import{F as _a}from"./flask-conical-Ql8QxhgY.js";import{C as bs}from"./clock-JyQAYy6X.js";import{A as ka}from"./archive-Bh689DNg.js";import{R as Sa}from"./radio-C5c9IyqX.js";import{T as ja,P as wi}from"./test-tube-CDATRD5t.js";import{VoiceOverlay as nc}from"./VoiceOverlay-Br4QnCtw.js";import{C as rc}from"./chevron-right-DbLSHmff.js";import{R as _n}from"./refresh-cw-C-iZkzuS.js";import{F as ic}from"./folder-DAdIw-Pb.js";import{C as vi}from"./check-CuRYh4Zh.js";import{S as ac}from"./shield-check-CXlDJyAW.js";import{E as _i}from"./external-link-DZ_rZsIt.js";import{B as Pr}from"./bot-DvEcyQcD.js";import{W as oc}from"./wifi-off-BBuIGbiP.js";import{C as lc}from"./chart-column-w3goFd5f.js";import{L as cc}from"./link-CnFkBkaY.js";import{T as dc}from"./trash-2-CTeyjxD_.js";/**
3
- * @license lucide-react v0.513.0 - ISC
4
- *
5
- * This source code is licensed under the ISC license.
6
- * See the LICENSE file in the root directory of this source tree.
7
- */const uc=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],hc=Ze("arrow-up",uc);/**
8
- * @license lucide-react v0.513.0 - ISC
9
- *
10
- * This source code is licensed under the ISC license.
11
- * See the LICENSE file in the root directory of this source tree.
12
- */const fc=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],pc=Ze("command",fc);/**
13
- * @license lucide-react v0.513.0 - ISC
14
- *
15
- * This source code is licensed under the ISC license.
16
- * See the LICENSE file in the root directory of this source tree.
17
- */const mc=[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],gc=Ze("compass",mc);/**
18
- * @license lucide-react v0.513.0 - ISC
19
- *
20
- * This source code is licensed under the ISC license.
21
- * See the LICENSE file in the root directory of this source tree.
22
- */const yc=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],bc=Ze("database",yc);/**
23
- * @license lucide-react v0.513.0 - ISC
24
- *
25
- * This source code is licensed under the ISC license.
26
- * See the LICENSE file in the root directory of this source tree.
27
- */const xc=[["path",{d:"M7 2h10",key:"nczekb"}],["path",{d:"M5 6h14",key:"u2x4p"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}]],wc=Ze("gallery-vertical-end",xc);/**
28
- * @license lucide-react v0.513.0 - ISC
29
- *
30
- * This source code is licensed under the ISC license.
31
- * See the LICENSE file in the root directory of this source tree.
32
- */const vc=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],_c=Ze("gauge",vc);/**
33
- * @license lucide-react v0.513.0 - ISC
34
- *
35
- * This source code is licensed under the ISC license.
36
- * See the LICENSE file in the root directory of this source tree.
37
- */const kc=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],Xs=Ze("git-pull-request",kc);/**
38
- * @license lucide-react v0.513.0 - ISC
39
- *
40
- * This source code is licensed under the ISC license.
41
- * See the LICENSE file in the root directory of this source tree.
42
- */const Sc=[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"1uw2ng"}]],jc=Ze("heart-pulse",Sc);/**
43
- * @license lucide-react v0.513.0 - ISC
44
- *
45
- * This source code is licensed under the ISC license.
46
- * See the LICENSE file in the root directory of this source tree.
47
- */const Ec=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Nc=Ze("history",Ec);/**
48
- * @license lucide-react v0.513.0 - ISC
49
- *
50
- * This source code is licensed under the ISC license.
51
- * See the LICENSE file in the root directory of this source tree.
52
- */const Cc=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],Ea=Ze("layout-grid",Cc);/**
53
- * @license lucide-react v0.513.0 - ISC
54
- *
55
- * This source code is licensed under the ISC license.
56
- * See the LICENSE file in the root directory of this source tree.
57
- */const Tc=[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]],Ac=Ze("navigation",Tc);/**
58
- * @license lucide-react v0.513.0 - ISC
59
- *
60
- * This source code is licensed under the ISC license.
61
- * See the LICENSE file in the root directory of this source tree.
62
- */const Rc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}]],Ic=Ze("panel-top",Rc),Be=()=>new Map,ur=t=>{const e=Be();return t.forEach((s,r)=>{e.set(r,s)}),e},He=(t,e,s)=>{let r=t.get(e);return r===void 0&&t.set(e,r=s()),r},Lc=(t,e)=>{const s=[];for(const[r,i]of t)s.push(e(i,r));return s},Dc=(t,e)=>{for(const[s,r]of t)if(e(r,s))return!0;return!1},xt=()=>new Set,Fn=t=>t[t.length-1],Mc=(t,e)=>{for(let s=0;s<e.length;s++)t.push(e[s])},dt=Array.from,Wr=(t,e)=>{for(let s=0;s<t.length;s++)if(!e(t[s],s,t))return!1;return!0},Na=(t,e)=>{for(let s=0;s<t.length;s++)if(e(t[s],s,t))return!0;return!1},Oc=(t,e)=>{const s=new Array(t);for(let r=0;r<t;r++)s[r]=e(r,s);return s},kn=Array.isArray;class Ca{constructor(){this._observers=Be()}on(e,s){return He(this._observers,e,xt).add(s),s}once(e,s){const r=(...i)=>{this.off(e,r),s(...i)};this.on(e,r)}off(e,s){const r=this._observers.get(e);r!==void 0&&(r.delete(s),r.size===0&&this._observers.delete(e))}emit(e,s){return dt((this._observers.get(e)||Be()).values()).forEach(r=>r(...s))}destroy(){this._observers=Be()}}class Ur{constructor(){this._observers=Be()}on(e,s){He(this._observers,e,xt).add(s)}once(e,s){const r=(...i)=>{this.off(e,r),s(...i)};this.on(e,r)}off(e,s){const r=this._observers.get(e);r!==void 0&&(r.delete(s),r.size===0&&this._observers.delete(e))}emit(e,s){return dt((this._observers.get(e)||Be()).values()).forEach(r=>r(...s))}destroy(){this._observers=Be()}}const Je=Math.floor,Ys=Math.abs,Pc=Math.log10,Br=(t,e)=>t<e?t:e,Lt=(t,e)=>t>e?t:e,Ta=t=>t!==0?t<0:1/t<0,ki=1,Si=2,$n=4,zn=8,xs=32,lt=64,ze=128,Sn=31,hr=63,jt=127,Wc=2147483647,Zs=Number.MAX_SAFE_INTEGER,ji=Number.MIN_SAFE_INTEGER,Uc=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Je(t)===t),Aa=String.fromCharCode,Bc=t=>t.toLowerCase(),Fc=/^\s*/g,$c=t=>t.replace(Fc,""),zc=/([A-Z])/g,Ei=(t,e)=>$c(t.replace(zc,s=>`${e}${Bc(s)}`)),Hc=t=>{const e=unescape(encodeURIComponent(t)),s=e.length,r=new Uint8Array(s);for(let i=0;i<s;i++)r[i]=e.codePointAt(i);return r},ws=typeof TextEncoder<"u"?new TextEncoder:null,Vc=t=>ws.encode(t),fr=ws?Vc:Hc;let fs=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});fs&&fs.decode(new Uint8Array).length===1&&(fs=null);const Gc=(t,e)=>Oc(e,()=>t).join("");class As{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Le=()=>new As,Yc=t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e},ke=t=>{const e=new Uint8Array(Yc(t));let s=0;for(let r=0;r<t.bufs.length;r++){const i=t.bufs[r];e.set(i,s),s+=i.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},qc=(t,e)=>{const s=t.cbuf.length;s-t.cpos<e&&(t.bufs.push(new Uint8Array(t.cbuf.buffer,0,t.cpos)),t.cbuf=new Uint8Array(Lt(s,e)*2),t.cpos=0)},Re=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(s*2),t.cpos=0),t.cbuf[t.cpos++]=e},vs=Re,ne=(t,e)=>{for(;e>jt;)Re(t,ze|jt&e),e=Je(e/128);Re(t,jt&e)},Fr=(t,e)=>{const s=Ta(e);for(s&&(e=-e),Re(t,(e>hr?ze:0)|(s?lt:0)|hr&e),e=Je(e/64);e>0;)Re(t,(e>jt?ze:0)|jt&e),e=Je(e/128)},pr=new Uint8Array(3e4),Kc=pr.length/3,Jc=(t,e)=>{if(e.length<Kc){const s=ws.encodeInto(e,pr).written||0;ne(t,s);for(let r=0;r<s;r++)Re(t,pr[r])}else Se(t,fr(e))},Xc=(t,e)=>{const s=unescape(encodeURIComponent(e)),r=s.length;ne(t,r);for(let i=0;i<r;i++)Re(t,s.codePointAt(i))},nt=ws&&ws.encodeInto?Jc:Xc,jn=(t,e)=>{const s=t.cbuf.length,r=t.cpos,i=Br(s-r,e.length),a=e.length-i;t.cbuf.set(e.subarray(0,i),r),t.cpos+=i,a>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(Lt(s*2,a)),t.cbuf.set(e.subarray(i)),t.cpos=a)},Se=(t,e)=>{ne(t,e.byteLength),jn(t,e)},$r=(t,e)=>{qc(t,e);const s=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,s},Zc=(t,e)=>$r(t,4).setFloat32(0,e,!1),Qc=(t,e)=>$r(t,8).setFloat64(0,e,!1),ed=(t,e)=>$r(t,8).setBigInt64(0,e,!1),Ni=new DataView(new ArrayBuffer(4)),td=t=>(Ni.setFloat32(0,t),Ni.getFloat32(0)===t),Jt=(t,e)=>{switch(typeof e){case"string":Re(t,119),nt(t,e);break;case"number":Uc(e)&&Ys(e)<=Wc?(Re(t,125),Fr(t,e)):td(e)?(Re(t,124),Zc(t,e)):(Re(t,123),Qc(t,e));break;case"bigint":Re(t,122),ed(t,e);break;case"object":if(e===null)Re(t,126);else if(kn(e)){Re(t,117),ne(t,e.length);for(let s=0;s<e.length;s++)Jt(t,e[s])}else if(e instanceof Uint8Array)Re(t,116),Se(t,e);else{Re(t,118);const s=Object.keys(e);ne(t,s.length);for(let r=0;r<s.length;r++){const i=s[r];nt(t,i),Jt(t,e[i])}}break;case"boolean":Re(t,e?120:121);break;default:Re(t,127)}};class Ci extends As{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&ne(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Ti=t=>{t.count>0&&(Fr(t.encoder,t.count===1?t.s:-t.s),t.count>1&&ne(t.encoder,t.count-2))};class qs{constructor(){this.encoder=new As,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Ti(this),this.count=1,this.s=e)}toUint8Array(){return Ti(this),ke(this.encoder)}}const Ai=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Fr(t.encoder,e),t.count>1&&ne(t.encoder,t.count-2)}};class Hn{constructor(){this.encoder=new As,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Ai(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Ai(this),ke(this.encoder)}}class sd{constructor(){this.sarr=[],this.s="",this.lensE=new qs}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new As;return this.sarr.push(this.s),this.s="",nt(e,this.sarr.join("")),jn(e,this.lensE.toUint8Array()),ke(e)}}const Ve=t=>new Error(t),Qe=()=>{throw Ve("Method unimplemented")},Xe=()=>{throw Ve("Unexpected case")},Ra=Ve("Unexpected end of array"),Ia=Ve("Integer out of Range");class En{constructor(e){this.arr=e,this.pos=0}}const at=t=>new En(t),nd=t=>t.pos!==t.arr.length,rd=(t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s},Ie=t=>rd(t,oe(t)),Nt=t=>t.arr[t.pos++],oe=t=>{let e=0,s=1;const r=t.arr.length;for(;t.pos<r;){const i=t.arr[t.pos++];if(e=e+(i&jt)*s,s*=128,i<ze)return e;if(e>Zs)throw Ia}throw Ra},zr=t=>{let e=t.arr[t.pos++],s=e&hr,r=64;const i=(e&lt)>0?-1:1;if((e&ze)===0)return i*s;const a=t.arr.length;for(;t.pos<a;){if(e=t.arr[t.pos++],s=s+(e&jt)*r,r*=128,e<ze)return i*s;if(s>Zs)throw Ia}throw Ra},id=t=>{let e=oe(t);if(e===0)return"";{let s=String.fromCodePoint(Nt(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(Nt(t));else for(;e>0;){const r=e<1e4?e:1e4,i=t.arr.subarray(t.pos,t.pos+r);t.pos+=r,s+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(s))}},ad=t=>fs.decode(Ie(t)),ct=fs?ad:id,Hr=(t,e)=>{const s=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,s},od=t=>Hr(t,4).getFloat32(0,!1),ld=t=>Hr(t,8).getFloat64(0,!1),cd=t=>Hr(t,8).getBigInt64(0,!1),dd=[t=>{},t=>null,zr,od,ld,cd,t=>!1,t=>!0,ct,t=>{const e=oe(t),s={};for(let r=0;r<e;r++){const i=ct(t);s[i]=Xt(t)}return s},t=>{const e=oe(t),s=[];for(let r=0;r<e;r++)s.push(Xt(t));return s},Ie],Xt=t=>dd[127-Nt(t)](t);class Ri extends En{constructor(e,s){super(e),this.reader=s,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),nd(this)?this.count=oe(this)+1:this.count=-1),this.count--,this.s}}class Ks extends En{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=zr(this);const e=Ta(this.s);this.count=1,e&&(this.s=-this.s,this.count=oe(this)+2)}return this.count--,this.s}}class Vn extends En{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=zr(this),s=e&1;this.diff=Je(e/2),this.count=1,s&&(this.count=oe(this)+2)}return this.s+=this.diff,this.count--,this.s}}class ud{constructor(e){this.decoder=new Ks(e),this.str=ct(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),s=this.str.slice(this.spos,e);return this.spos=e,s}}const hd=crypto.getRandomValues.bind(crypto),fd=Math.random,La=()=>hd(new Uint32Array(1))[0],pd="10000000-1000-4000-8000"+-1e11,Da=()=>pd.replace(/[018]/g,t=>(t^La()&15>>t/4).toString(16)),ut=Date.now,Zt=t=>new Promise(t);Promise.all.bind(Promise);const md=t=>Promise.reject(t),Vr=t=>Promise.resolve(t),Ii=t=>t===void 0?null:t;class gd{constructor(){this.map=new Map}setItem(e,s){this.map.set(e,s)}getItem(e){return this.map.get(e)}}let Ma=new gd,Gr=!0;try{typeof localStorage<"u"&&localStorage&&(Ma=localStorage,Gr=!1)}catch{}const Oa=Ma,yd=t=>Gr||addEventListener("storage",t),bd=t=>Gr||removeEventListener("storage",t),_s=Symbol("Equality"),Pa=(t,e)=>{var s;return t===e||!!((s=t==null?void 0:t[_s])!=null&&s.call(t,e))||!1},xd=t=>typeof t=="object",wd=Object.assign,vd=Object.keys,_d=(t,e)=>{for(const s in t)e(t[s],s)},Qs=t=>vd(t).length,kd=t=>{for(const e in t)return!1;return!0},Rs=(t,e)=>{for(const s in t)if(!e(t[s],s))return!1;return!0},Yr=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Sd=(t,e)=>t===e||Qs(t)===Qs(e)&&Rs(t,(s,r)=>(s!==void 0||Yr(e,r))&&Pa(e[r],s)),jd=Object.freeze,Wa=t=>{for(const e in t){const s=t[e];(typeof s=="object"||typeof s=="function")&&Wa(t[e])}return jd(t)},qr=(t,e,s=0)=>{try{for(;s<t.length;s++)t[s](...e)}finally{s<t.length&&qr(t,e,s+1)}},Ed=()=>{},Nd=t=>t,zt=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[_s]!=null)return t[_s](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;break}case Set:{if(t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;break}case Map:{if(t.size!==e.size)return!1;for(const s of t.keys())if(!e.has(s)||!zt(t.get(s),e.get(s)))return!1;break}case void 0:case Object:if(Qs(t)!==Qs(e))return!1;for(const s in t)if(!Yr(t,s)||!zt(t[s],e[s]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!zt(t[s],e[s]))return!1;break;default:return!1}return!0},Cd=(t,e)=>e.includes(t);var Ua={};const Qt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Ba=typeof window<"u"&&typeof document<"u"&&!Qt;let st;const Td=()=>{if(st===void 0)if(Qt){st=Be();const t=process.argv;let e=null;for(let s=0;s<t.length;s++){const r=t[s];r[0]==="-"?(e!==null&&st.set(e,""),e=r):e!==null&&(st.set(e,r),e=null)}e!==null&&st.set(e,"")}else typeof location=="object"?(st=Be(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,s]=t.split("=");st.set(`--${Ei(e,"-")}`,s),st.set(`-${Ei(e,"-")}`,s)}})):st=Be();return st},mr=t=>Td().has(t),ks=t=>Ii(Qt?Ua[t.toUpperCase().replaceAll("-","_")]:Oa.getItem(t)),Fa=t=>mr("--"+t)||ks(t)!==null,Ad=Fa("production"),Rd=Qt&&Cd(Ua.FORCE_COLOR,["true","1","2"]),Id=Rd||!mr("--no-colors")&&!Fa("no-color")&&(!Qt||process.stdout.isTTY)&&(!Qt||mr("--color")||ks("COLORTERM")!==null||(ks("TERM")||"").includes("color")),$a=t=>new Uint8Array(t),Ld=(t,e,s)=>new Uint8Array(t,e,s),Dd=t=>new Uint8Array(t),Md=t=>{let e="";for(let s=0;s<t.byteLength;s++)e+=Aa(t[s]);return btoa(e)},Od=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),Pd=t=>{const e=atob(t),s=$a(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s},Wd=t=>{const e=Buffer.from(t,"base64");return Ld(e.buffer,e.byteOffset,e.byteLength)},za=Ba?Md:Od,Ha=Ba?Pd:Wd,Ud=t=>{const e=$a(t.byteLength);return e.set(t),e};class Bd{constructor(e,s){this.left=e,this.right=s}}const ot=(t,e)=>new Bd(t,e),Li=t=>t.next()>=.5,Gn=(t,e,s)=>Je(t.next()*(s+1-e)+e),Va=(t,e,s)=>Je(t.next()*(s+1-e)+e),Kr=(t,e,s)=>Va(t,e,s),Fd=t=>Aa(Kr(t,97,122)),$d=(t,e=0,s=20)=>{const r=Kr(t,e,s);let i="";for(let a=0;a<r;a++)i+=Fd(t);return i},Yn=(t,e)=>e[Kr(t,0,e.length-1)],zd=Symbol("0schema");class Hd{constructor(){this._rerrs=[]}extend(e,s,r,i=null){this._rerrs.push({path:e,expected:s,has:r,message:i})}toString(){const e=[];for(let s=this._rerrs.length-1;s>0;s--){const r=this._rerrs[s];e.push(Gc(" ",(this._rerrs.length-s)*2)+`${r.path!=null?`[${r.path}] `:""}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(`
63
- `)}}const gr=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[_s]?Pa(t,e):kn(t)?Wr(t,s=>Na(e,r=>gr(s,r))):xd(t)?Rs(t,(s,r)=>gr(s,e[r])):!1;class Ue{extends(e){let[s,r]=[this.shape,e.shape];return this.constructor._dilutes&&([r,s]=[s,r]),gr(s,r)}equals(e){return this.constructor===e.constructor&&zt(this.shape,e.shape)}[zd](){return!0}[_s](e){return this.equals(e)}validate(e){return this.check(e)}check(e,s){Qe()}get nullable(){return rs(this,Rn)}get optional(){return new qa(this)}cast(e){return Di(e,this),e}expect(e){return Di(e,this),e}}Fe(Ue,"_dilutes",!1);class Jr extends Ue{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s=void 0){const r=(e==null?void 0:e.constructor)===this.shape&&(this._c==null||this._c(e));return!r&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name,(e==null?void 0:e.constructor)!==this.shape?"Constructor match failed":"Check failed")),r}}const Ne=(t,e=null)=>new Jr(t,e);Ne(Jr);class Xr extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=this.shape(e);return!r&&(s==null||s.extend(null,"custom prop",e==null?void 0:e.constructor.name,"failed to check custom prop")),r}}const Me=t=>new Xr(t);Ne(Xr);class Nn extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=this.shape.some(i=>i===e);return!r&&(s==null||s.extend(null,this.shape.join(" | "),e.toString())),r}}const Cn=(...t)=>new Nn(t),Ga=Ne(Nn),Vd=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Ya=t=>{if(es.check(t))return[Vd(t)];if(Ga.check(t))return t.shape.map(e=>e+"");if(no.check(t))return["[+-]?\\d+.?\\d*"];if(ro.check(t))return[".*"];if(tn.check(t))return t.shape.map(Ya).flat(1);Xe()};class Gd extends Ue{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Ya).map(s=>`(${s.join("|")})`).join("")+"$")}check(e,s){const r=this._r.exec(e)!=null;return!r&&(s==null||s.extend(null,this._r.toString(),e.toString(),"String doesn't match string template.")),r}}Ne(Gd);const Yd=Symbol("optional");class qa extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=e===void 0||this.shape.check(e);return!r&&(s==null||s.extend(null,"undefined (optional)","()")),r}get[Yd](){return!0}}const qd=Ne(qa);class Kd extends Ue{check(e,s){return s==null||s.extend(null,"never",typeof e),!1}}Ne(Kd);const yn=class yn extends Ue{constructor(e,s=!1){super(),this.shape=e,this._isPartial=s}get partial(){return new yn(this.shape,!0)}check(e,s){return e==null?(s==null||s.extend(null,"object","null"),!1):Rs(this.shape,(r,i)=>{const a=this._isPartial&&!Yr(e,i)||r.check(e[i],s);return!a&&(s==null||s.extend(i.toString(),r.toString(),typeof e[i],"Object property does not match")),a})}};Fe(yn,"_dilutes",!0);let en=yn;const Jd=t=>new en(t),Xd=Ne(en),Zd=Me(t=>t!=null&&(t.constructor===Object||t.constructor==null));class Ka extends Ue{constructor(e,s){super(),this.shape={keys:e,values:s}}check(e,s){return e!=null&&Rs(e,(r,i)=>{const a=this.shape.keys.check(i,s);return!a&&(s==null||s.extend(i+"","Record",typeof e,a?"Key doesn't match schema":"Value doesn't match value")),a&&this.shape.values.check(r,s)})}}const Ja=(t,e)=>new Ka(t,e),Qd=Ne(Ka);class Xa extends Ue{constructor(e){super(),this.shape=e}check(e,s){return e!=null&&Rs(this.shape,(r,i)=>{const a=r.check(e[i],s);return!a&&(s==null||s.extend(i.toString(),"Tuple",typeof r)),a})}}const eu=(...t)=>new Xa(t);Ne(Xa);class Za extends Ue{constructor(e){super(),this.shape=e.length===1?e[0]:new Tn(e)}check(e,s){const r=kn(e)&&Wr(e,i=>this.shape.check(i));return!r&&(s==null||s.extend(null,"Array","")),r}}const Qa=(...t)=>new Za(t),tu=Ne(Za),su=Me(t=>kn(t));class eo extends Ue{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s){const r=e instanceof this.shape&&(this._c==null||this._c(e));return!r&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name)),r}}const nu=(t,e=null)=>new eo(t,e);Ne(eo);const ru=nu(Ue);class iu extends Ue{constructor(e){super(),this.len=e.length-1,this.args=eu(...e.slice(-1)),this.res=e[this.len]}check(e,s){const r=e.constructor===Function&&e.length<=this.len;return!r&&(s==null||s.extend(null,"function",typeof e)),r}}const au=Ne(iu),ou=Me(t=>typeof t=="function");class lu extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=Wr(this.shape,i=>i.check(e,s));return!r&&(s==null||s.extend(null,"Intersectinon",typeof e)),r}}Ne(lu,t=>t.shape.length>0);class Tn extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=Na(this.shape,i=>i.check(e,s));return s==null||s.extend(null,"Union",typeof e),r}}Fe(Tn,"_dilutes",!0);const rs=(...t)=>t.findIndex(e=>tn.check(e))>=0?rs(...t.map(e=>Ss(e)).map(e=>tn.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new Tn(t),tn=Ne(Tn),to=()=>!0,sn=Me(to),cu=Ne(Xr,t=>t.shape===to),Zr=Me(t=>typeof t=="bigint"),du=Me(t=>t===Zr),so=Me(t=>typeof t=="symbol");Me(t=>t===so);const Ht=Me(t=>typeof t=="number"),no=Me(t=>t===Ht),es=Me(t=>typeof t=="string"),ro=Me(t=>t===es),An=Me(t=>typeof t=="boolean"),uu=Me(t=>t===An),io=Cn(void 0);Ne(Nn,t=>t.shape.length===1&&t.shape[0]===void 0);Cn(void 0);const Rn=Cn(null),hu=Ne(Nn,t=>t.shape.length===1&&t.shape[0]===null);Ne(Uint8Array);Ne(Jr,t=>t.shape===Uint8Array);const fu=rs(Ht,es,Rn,io,Zr,An,so);(()=>{const t=Qa(sn),e=Ja(es,sn),s=rs(Ht,es,Rn,An,t,e);return t.shape=s,e.shape.values=s,s})();const Ss=t=>{if(ru.check(t))return t;if(Zd.check(t)){const e={};for(const s in t)e[s]=Ss(t[s]);return Jd(e)}else{if(su.check(t))return rs(...t.map(Ss));if(fu.check(t))return Cn(t);if(ou.check(t))return Ne(t)}Xe()},Di=Ad?()=>{}:(t,e)=>{const s=new Hd;if(!e.check(t,s))throw Ve(`Expected value to be of type ${e.constructor.name}.
64
- ${s.toString()}`)};class pu{constructor(e){this.patterns=[],this.$state=e}if(e,s){return this.patterns.push({if:Ss(e),h:s}),this}else(e){return this.if(sn,e)}done(){return(e,s)=>{for(let r=0;r<this.patterns.length;r++){const i=this.patterns[r];if(i.if.check(e))return i.h(e,s)}throw Ve("Unhandled pattern")}}}const mu=t=>new pu(t),ao=mu(sn).if(no,(t,e)=>Gn(e,ji,Zs)).if(ro,(t,e)=>$d(e)).if(uu,(t,e)=>Li(e)).if(du,(t,e)=>BigInt(Gn(e,ji,Zs))).if(tn,(t,e)=>Ut(e,Yn(e,t.shape))).if(Xd,(t,e)=>{const s={};for(const r in t.shape){let i=t.shape[r];if(qd.check(i)){if(Li(e))continue;i=i.shape}s[r]=ao(i,e)}return s}).if(tu,(t,e)=>{const s=[],r=Va(e,0,42);for(let i=0;i<r;i++)s.push(Ut(e,t.shape));return s}).if(Ga,(t,e)=>Yn(e,t.shape)).if(hu,(t,e)=>null).if(au,(t,e)=>{const s=Ut(e,t.res);return()=>s}).if(cu,(t,e)=>Ut(e,Yn(e,[Ht,es,Rn,io,Zr,An,Qa(Ht),Ja(rs("a","b","c"),Ht)]))).if(Qd,(t,e)=>{const s={},r=Gn(e,0,3);for(let i=0;i<r;i++){const a=Ut(e,t.shape.keys),d=Ut(e,t.shape.values);s[a]=d}return s}).done(),Ut=(t,e)=>ao(Ss(e),t),In=typeof document<"u"?document:{};Me(t=>t.nodeType===wu);typeof DOMParser<"u"&&new DOMParser;Me(t=>t.nodeType===yu);Me(t=>t.nodeType===bu);const gu=t=>Lc(t,(e,s)=>`${s}:${e};`).join(""),yu=In.ELEMENT_NODE,bu=In.TEXT_NODE,xu=In.DOCUMENT_NODE,wu=In.DOCUMENT_FRAGMENT_NODE;Me(t=>t.nodeType===xu);const vu=JSON.stringify,ft=Symbol,Ke=ft(),Ct=ft(),oo=ft(),Qr=ft(),lo=ft(),co=ft(),uo=ft(),Ln=ft(),Dn=ft(),_u=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],s=[];let r=0;for(;r<t.length;r++){const a=t[r];if(a===void 0)break;if(a.constructor===String||a.constructor===Number)e.push(a);else if(a.constructor===Object)break}for(r>0&&s.push(e.join(""));r<t.length;r++){const a=t[r];a instanceof Symbol||s.push(a)}return s},Mi=[lo,uo,Ln,oo];let qn=0,Oi=ut();const ku=(t,e)=>{const s=Mi[qn],r=ks("log"),i=r!==null&&(r==="*"||r==="true"||new RegExp(r,"gi").test(e));return qn=(qn+1)%Mi.length,e+=": ",i?(...a)=>{var c;a.length===1&&((c=a[0])==null?void 0:c.constructor)===Function&&(a=a[0]());const d=ut(),l=d-Oi;Oi=d,t(s,e,Dn,...a.map(f=>{switch(f!=null&&f.constructor===Uint8Array&&(f=Array.from(f)),typeof f){case"string":case"symbol":return f;default:return vu(f)}}),s," +"+l+"ms")}:Ed},Su={[Ke]:ot("font-weight","bold"),[Ct]:ot("font-weight","normal"),[oo]:ot("color","blue"),[lo]:ot("color","green"),[Qr]:ot("color","grey"),[co]:ot("color","red"),[uo]:ot("color","purple"),[Ln]:ot("color","orange"),[Dn]:ot("color","black")},ju=t=>{var d;t.length===1&&((d=t[0])==null?void 0:d.constructor)===Function&&(t=t[0]());const e=[],s=[],r=Be();let i=[],a=0;for(;a<t.length;a++){const l=t[a],c=Su[l];if(c!==void 0)r.set(c.left,c.right);else{if(l===void 0)break;if(l.constructor===String||l.constructor===Number){const f=gu(r);a>0||f.length>0?(e.push("%c"+l),s.push(f)):e.push(l)}else break}}for(a>0&&(i=s,i.unshift(e.join("")));a<t.length;a++){const l=t[a];l instanceof Symbol||i.push(l)}return i},ho=Id?ju:_u,fo=(...t)=>{console.log(...ho(t)),po.forEach(e=>e.print(t))},Eu=(...t)=>{console.warn(...ho(t)),t.unshift(Ln),po.forEach(e=>e.print(t))},po=xt(),Nu=t=>ku(fo,t),mo=t=>({[Symbol.iterator](){return this},next:t}),Cu=(t,e)=>mo(()=>{let s;do s=t.next();while(!s.done&&!e(s.value));return s}),Kn=(t,e)=>mo(()=>{const{done:s,value:r}=t.next();return{done:s,value:s?void 0:e(r)}});class Mn{constructor(e,s){this.clock=e,this.len=s}}class Is{constructor(){this.clients=new Map}}const go=(t,e,s)=>e.clients.forEach((r,i)=>{const a=t.doc.store.clients.get(i);if(a!=null){const d=a[a.length-1],l=d.id.clock+d.length;for(let c=0,f=r[c];c<r.length&&f.clock<l;f=r[++c])Ao(t,a,f.clock,f.len,s)}}),Tu=(t,e)=>{let s=0,r=t.length-1;for(;s<=r;){const i=Je((s+r)/2),a=t[i],d=a.clock;if(d<=e){if(e<d+a.len)return i;s=i+1}else r=i-1}return null},yo=(t,e)=>{const s=t.clients.get(e.client);return s!==void 0&&Tu(s,e.clock)!==null},ei=t=>{t.clients.forEach(e=>{e.sort((i,a)=>i.clock-a.clock);let s,r;for(s=1,r=1;s<e.length;s++){const i=e[r-1],a=e[s];i.clock+i.len>=a.clock?e[r-1]=new Mn(i.clock,Lt(i.len,a.clock+a.len-i.clock)):(r<s&&(e[r]=a),r++)}e.length=r})},Au=t=>{const e=new Is;for(let s=0;s<t.length;s++)t[s].clients.forEach((r,i)=>{if(!e.clients.has(i)){const a=r.slice();for(let d=s+1;d<t.length;d++)Mc(a,t[d].clients.get(i)||[]);e.clients.set(i,a)}});return ei(e),e},nn=(t,e,s,r)=>{He(t.clients,e,()=>[]).push(new Mn(s,r))},Ru=()=>new Is,Iu=t=>{const e=Ru();return t.clients.forEach((s,r)=>{const i=[];for(let a=0;a<s.length;a++){const d=s[a];if(d.deleted){const l=d.id.clock;let c=d.length;if(a+1<s.length)for(let f=s[a+1];a+1<s.length&&f.deleted;f=s[++a+1])c+=f.length;i.push(new Mn(l,c))}}i.length>0&&e.clients.set(r,i)}),e},is=(t,e)=>{ne(t.restEncoder,e.clients.size),dt(e.clients.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{t.resetDsCurVal(),ne(t.restEncoder,s);const i=r.length;ne(t.restEncoder,i);for(let a=0;a<i;a++){const d=r[a];t.writeDsClock(d.clock),t.writeDsLen(d.len)}})},ti=t=>{const e=new Is,s=oe(t.restDecoder);for(let r=0;r<s;r++){t.resetDsCurVal();const i=oe(t.restDecoder),a=oe(t.restDecoder);if(a>0){const d=He(e.clients,i,()=>[]);for(let l=0;l<a;l++)d.push(new Mn(t.readDsClock(),t.readDsLen()))}}return e},Pi=(t,e,s)=>{const r=new Is,i=oe(t.restDecoder);for(let a=0;a<i;a++){t.resetDsCurVal();const d=oe(t.restDecoder),l=oe(t.restDecoder),c=s.clients.get(d)||[],f=De(s,d);for(let b=0;b<l;b++){const u=t.readDsClock(),p=u+t.readDsLen();if(u<f){f<p&&nn(r,d,f,p-f);let m=rt(c,u),y=c[m];for(!y.deleted&&y.id.clock<u&&(c.splice(m+1,0,un(e,y,u-y.id.clock)),m++);m<c.length&&(y=c[m++],y.id.clock<p);)y.deleted||(p<y.id.clock+y.length&&c.splice(m,0,un(e,y,p-y.id.clock)),y.delete(e))}else nn(r,d,u,p-u)}}if(r.clients.size>0){const a=new Tt;return ne(a.restEncoder,0),is(a,r),a.toUint8Array()}return null},bo=La;class as extends Ca{constructor({guid:e=Da(),collectionid:s=null,gc:r=!0,gcFilter:i=()=>!0,meta:a=null,autoLoad:d=!1,shouldLoad:l=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=bo(),this.guid=e,this.collectionid=s,this.share=new Map,this.store=new Co,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=d,this.meta=a,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Zt(f=>{this.on("load",()=>{this.isLoaded=!0,f(this)})});const c=()=>Zt(f=>{const b=u=>{(u===void 0||u===!0)&&(this.off("sync",b),f())};this.on("sync",b)});this.on("sync",f=>{f===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=f===void 0||f===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&we(e.parent.doc,s=>{s.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(dt(this.subdocs).map(e=>e.guid))}transact(e,s=null){return we(this,e,s)}get(e,s=Pe){const r=He(this.share,e,()=>{const a=new s;return a._integrate(this,null),a}),i=r.constructor;if(s!==Pe&&i!==s)if(i===Pe){const a=new s;a._map=r._map,r._map.forEach(d=>{for(;d!==null;d=d.left)d.parent=a}),a._start=r._start;for(let d=a._start;d!==null;d=d.right)d.parent=a;return a._length=r._length,this.share.set(e,a),a._integrate(this,null),a}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,Gt)}getText(e=""){return this.get(e,ss)}getMap(e=""){return this.get(e,At)}getXmlElement(e=""){return this.get(e,ns)}getXmlFragment(e=""){return this.get(e,Rt)}toJSON(){const e={};return this.share.forEach((s,r)=>{e[r]=s.toJSON()}),e}destroy(){this.isDestroyed=!0,dt(this.subdocs).forEach(s=>s.destroy());const e=this._item;if(e!==null){this._item=null;const s=e.content;s.doc=new as({guid:this.guid,...s.opts,shouldLoad:!1}),s.doc._item=e,we(e.parent.doc,r=>{const i=s.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class xo{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return oe(this.restDecoder)}readDsLen(){return oe(this.restDecoder)}}class wo extends xo{readLeftID(){return me(oe(this.restDecoder),oe(this.restDecoder))}readRightID(){return me(oe(this.restDecoder),oe(this.restDecoder))}readClient(){return oe(this.restDecoder)}readInfo(){return Nt(this.restDecoder)}readString(){return ct(this.restDecoder)}readParentInfo(){return oe(this.restDecoder)===1}readTypeRef(){return oe(this.restDecoder)}readLen(){return oe(this.restDecoder)}readAny(){return Xt(this.restDecoder)}readBuf(){return Ud(Ie(this.restDecoder))}readJSON(){return JSON.parse(ct(this.restDecoder))}readKey(){return ct(this.restDecoder)}}class Lu{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=oe(this.restDecoder),this.dsCurrVal}readDsLen(){const e=oe(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class ts extends Lu{constructor(e){super(e),this.keys=[],oe(e),this.keyClockDecoder=new Vn(Ie(e)),this.clientDecoder=new Ks(Ie(e)),this.leftClockDecoder=new Vn(Ie(e)),this.rightClockDecoder=new Vn(Ie(e)),this.infoDecoder=new Ri(Ie(e),Nt),this.stringDecoder=new ud(Ie(e)),this.parentInfoDecoder=new Ri(Ie(e),Nt),this.typeRefDecoder=new Ks(Ie(e)),this.lenDecoder=new Ks(Ie(e))}readLeftID(){return new Vt(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Vt(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Xt(this.restDecoder)}readBuf(){return Ie(this.restDecoder)}readJSON(){return Xt(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const s=this.stringDecoder.read();return this.keys.push(s),s}}}class vo{constructor(){this.restEncoder=Le()}toUint8Array(){return ke(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ne(this.restEncoder,e)}writeDsLen(e){ne(this.restEncoder,e)}}class Ls extends vo{writeLeftID(e){ne(this.restEncoder,e.client),ne(this.restEncoder,e.clock)}writeRightID(e){ne(this.restEncoder,e.client),ne(this.restEncoder,e.clock)}writeClient(e){ne(this.restEncoder,e)}writeInfo(e){vs(this.restEncoder,e)}writeString(e){nt(this.restEncoder,e)}writeParentInfo(e){ne(this.restEncoder,e?1:0)}writeTypeRef(e){ne(this.restEncoder,e)}writeLen(e){ne(this.restEncoder,e)}writeAny(e){Jt(this.restEncoder,e)}writeBuf(e){Se(this.restEncoder,e)}writeJSON(e){nt(this.restEncoder,JSON.stringify(e))}writeKey(e){nt(this.restEncoder,e)}}class _o{constructor(){this.restEncoder=Le(),this.dsCurrVal=0}toUint8Array(){return ke(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const s=e-this.dsCurrVal;this.dsCurrVal=e,ne(this.restEncoder,s)}writeDsLen(e){e===0&&Xe(),ne(this.restEncoder,e-1),this.dsCurrVal+=e}}class Tt extends _o{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Hn,this.clientEncoder=new qs,this.leftClockEncoder=new Hn,this.rightClockEncoder=new Hn,this.infoEncoder=new Ci(vs),this.stringEncoder=new sd,this.parentInfoEncoder=new Ci(vs),this.typeRefEncoder=new qs,this.lenEncoder=new qs}toUint8Array(){const e=Le();return ne(e,0),Se(e,this.keyClockEncoder.toUint8Array()),Se(e,this.clientEncoder.toUint8Array()),Se(e,this.leftClockEncoder.toUint8Array()),Se(e,this.rightClockEncoder.toUint8Array()),Se(e,ke(this.infoEncoder)),Se(e,this.stringEncoder.toUint8Array()),Se(e,ke(this.parentInfoEncoder)),Se(e,this.typeRefEncoder.toUint8Array()),Se(e,this.lenEncoder.toUint8Array()),jn(e,ke(this.restEncoder)),ke(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Jt(this.restEncoder,e)}writeBuf(e){Se(this.restEncoder,e)}writeJSON(e){Jt(this.restEncoder,e)}writeKey(e){const s=this.keyMap.get(e);s===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(s)}}const Du=(t,e,s,r)=>{r=Lt(r,e[0].id.clock);const i=rt(e,r);ne(t.restEncoder,e.length-i),t.writeClient(s),ne(t.restEncoder,r);const a=e[i];a.write(t,r-a.id.clock);for(let d=i+1;d<e.length;d++)e[d].write(t,0)},si=(t,e,s)=>{const r=new Map;s.forEach((i,a)=>{De(e,a)>i&&r.set(a,i)}),On(e).forEach((i,a)=>{s.has(a)||r.set(a,0)}),ne(t.restEncoder,r.size),dt(r.entries()).sort((i,a)=>a[0]-i[0]).forEach(([i,a])=>{Du(t,e.clients.get(i),i,a)})},Mu=(t,e)=>{const s=Be(),r=oe(t.restDecoder);for(let i=0;i<r;i++){const a=oe(t.restDecoder),d=new Array(a),l=t.readClient();let c=oe(t.restDecoder);s.set(l,{i:0,refs:d});for(let f=0;f<a;f++){const b=t.readInfo();switch(Sn&b){case 0:{const u=t.readLen();d[f]=new Ye(me(l,c),u),c+=u;break}case 10:{const u=oe(t.restDecoder);d[f]=new qe(me(l,c),u),c+=u;break}default:{const u=(b&(lt|ze))===0,p=new Ce(me(l,c),null,(b&ze)===ze?t.readLeftID():null,null,(b&lt)===lt?t.readRightID():null,u?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,u&&(b&xs)===xs?t.readString():null,Ko(t,b));d[f]=p,c+=p.length}}}}return s},Ou=(t,e,s)=>{const r=[];let i=dt(s.keys()).sort((m,y)=>m-y);if(i.length===0)return null;const a=()=>{if(i.length===0)return null;let m=s.get(i[i.length-1]);for(;m.refs.length===m.i;)if(i.pop(),i.length>0)m=s.get(i[i.length-1]);else return null;return m};let d=a();if(d===null)return null;const l=new Co,c=new Map,f=(m,y)=>{const _=c.get(m);(_==null||_>y)&&c.set(m,y)};let b=d.refs[d.i++];const u=new Map,p=()=>{for(const m of r){const y=m.id.client,_=s.get(y);_?(_.i--,l.clients.set(y,_.refs.slice(_.i)),s.delete(y),_.i=0,_.refs=[]):l.clients.set(y,[m]),i=i.filter(R=>R!==y)}r.length=0};for(;;){if(b.constructor!==qe){const y=He(u,b.id.client,()=>De(e,b.id.client))-b.id.clock;if(y<0)r.push(b),f(b.id.client,b.id.clock-1),p();else{const _=b.getMissing(t,e);if(_!==null){r.push(b);const R=s.get(_)||{refs:[],i:0};if(R.refs.length===R.i)f(_,De(e,_)),p();else{b=R.refs[R.i++];continue}}else(y===0||y<b.length)&&(b.integrate(t,y),u.set(b.id.client,b.id.clock+b.length))}}if(r.length>0)b=r.pop();else if(d!==null&&d.i<d.refs.length)b=d.refs[d.i++];else{if(d=a(),d===null)break;b=d.refs[d.i++]}}if(l.clients.size>0){const m=new Tt;return si(m,l,new Map),ne(m.restEncoder,0),{missing:c,update:m.toUint8Array()}}return null},Pu=(t,e)=>si(t,e.doc.store,e.beforeState),Wu=(t,e,s,r=new ts(t))=>we(e,i=>{i.local=!1;let a=!1;const d=i.doc,l=d.store,c=Mu(r,d),f=Ou(i,l,c),b=l.pendingStructs;if(b){for(const[p,m]of b.missing)if(m<De(l,p)){a=!0;break}if(f){for(const[p,m]of f.missing){const y=b.missing.get(p);(y==null||y>m)&&b.missing.set(p,m)}b.update=rn([b.update,f.update])}}else l.pendingStructs=f;const u=Pi(r,i,l);if(l.pendingDs){const p=new ts(at(l.pendingDs));oe(p.restDecoder);const m=Pi(p,i,l);u&&m?l.pendingDs=rn([u,m]):l.pendingDs=u||m}else l.pendingDs=u;if(a){const p=l.pendingStructs.update;l.pendingStructs=null,ko(i.doc,p)}},s,!1),ko=(t,e,s,r=ts)=>{const i=at(e);Wu(i,t,s,new r(i))},So=(t,e,s)=>ko(t,e,s,wo),Uu=(t,e,s=new Map)=>{si(t,e.store,s),is(t,Iu(e.store))},Bu=(t,e=new Uint8Array([0]),s=new Tt)=>{const r=jo(e);Uu(s,t,r);const i=[s.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(th(t.store.pendingStructs.update,e)),i.length>1){if(s.constructor===Ls)return Qu(i.map((a,d)=>d===0?a:nh(a)));if(s.constructor===Tt)return rn(i)}return i[0]},ni=(t,e)=>Bu(t,e,new Ls),Fu=t=>{const e=new Map,s=oe(t.restDecoder);for(let r=0;r<s;r++){const i=oe(t.restDecoder),a=oe(t.restDecoder);e.set(i,a)}return e},jo=t=>Fu(new xo(at(t))),Eo=(t,e)=>(ne(t.restEncoder,e.size),dt(e.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{ne(t.restEncoder,s),ne(t.restEncoder,r)}),t),$u=(t,e)=>Eo(t,On(e.store)),zu=(t,e=new _o)=>(t instanceof Map?Eo(e,t):$u(e,t),e.toUint8Array()),Hu=t=>zu(t,new vo);class Vu{constructor(){this.l=[]}}const Wi=()=>new Vu,Ui=(t,e)=>t.l.push(e),Bi=(t,e)=>{const s=t.l,r=s.length;t.l=s.filter(i=>e!==i),r===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},No=(t,e,s)=>qr(t.l,[e,s]);class Vt{constructor(e,s){this.client=e,this.clock=s}}const Os=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,me=(t,e)=>new Vt(t,e),Gu=t=>{for(const[e,s]of t.doc.share.entries())if(s===t)return e;throw Xe()},$t=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!yo(e.ds,t.id),yr=(t,e)=>{const s=He(t.meta,yr,xt),r=t.doc.store;s.has(e)||(e.sv.forEach((i,a)=>{i<De(r,a)&&wt(t,me(a,i))}),go(t,e.ds,i=>{}),s.add(e))};class Co{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const On=t=>{const e=new Map;return t.clients.forEach((s,r)=>{const i=s[s.length-1];e.set(r,i.id.clock+i.length)}),e},De=(t,e)=>{const s=t.clients.get(e);if(s===void 0)return 0;const r=s[s.length-1];return r.id.clock+r.length},To=(t,e)=>{let s=t.clients.get(e.id.client);if(s===void 0)s=[],t.clients.set(e.id.client,s);else{const r=s[s.length-1];if(r.id.clock+r.length!==e.id.clock)throw Xe()}s.push(e)},rt=(t,e)=>{let s=0,r=t.length-1,i=t[r],a=i.id.clock;if(a===e)return r;let d=Je(e/(a+i.length-1)*r);for(;s<=r;){if(i=t[d],a=i.id.clock,a<=e){if(e<a+i.length)return d;s=d+1}else r=d-1;d=Je((s+r)/2)}throw Xe()},Yu=(t,e)=>{const s=t.clients.get(e.client);return s[rt(s,e.clock)]},Jn=Yu,br=(t,e,s)=>{const r=rt(e,s),i=e[r];return i.id.clock<s&&i instanceof Ce?(e.splice(r+1,0,un(t,i,s-i.id.clock)),r+1):r},wt=(t,e)=>{const s=t.doc.store.clients.get(e.client);return s[br(t,s,e.clock)]},Fi=(t,e,s)=>{const r=e.clients.get(s.client),i=rt(r,s.clock),a=r[i];return s.clock!==a.id.clock+a.length-1&&a.constructor!==Ye&&r.splice(i+1,0,un(t,a,s.clock-a.id.clock+1)),a},qu=(t,e,s)=>{const r=t.clients.get(e.id.client);r[rt(r,e.id.clock)]=s},Ao=(t,e,s,r,i)=>{if(r===0)return;const a=s+r;let d=br(t,e,s),l;do l=e[d++],a<l.id.clock+l.length&&br(t,e,a),i(l);while(d<e.length&&e[d].id.clock<a)};class Ku{constructor(e,s,r){this.doc=e,this.deleteSet=new Is,this.beforeState=On(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=s,this.meta=new Map,this.local=r,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const $i=(t,e)=>e.deleteSet.clients.size===0&&!Dc(e.afterState,(s,r)=>e.beforeState.get(r)!==s)?!1:(ei(e.deleteSet),Pu(t,e),is(t,e.deleteSet),!0),zi=(t,e,s)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&He(t.changed,e,xt).add(s)},Js=(t,e)=>{let s=t[e],r=t[e-1],i=e;for(;i>0;s=r,r=t[--i-1]){if(r.deleted===s.deleted&&r.constructor===s.constructor&&r.mergeWith(s)){s instanceof Ce&&s.parentSub!==null&&s.parent._map.get(s.parentSub)===s&&s.parent._map.set(s.parentSub,r);continue}break}const a=e-i;return a&&t.splice(e+1-a,a),a},Ju=(t,e,s)=>{for(const[r,i]of t.clients.entries()){const a=e.clients.get(r);for(let d=i.length-1;d>=0;d--){const l=i[d],c=l.clock+l.len;for(let f=rt(a,l.clock),b=a[f];f<a.length&&b.id.clock<c;b=a[++f]){const u=a[f];if(l.clock+l.len<=u.id.clock)break;u instanceof Ce&&u.deleted&&!u.keep&&s(u)&&u.gc(e,!1)}}}},Xu=(t,e)=>{t.clients.forEach((s,r)=>{const i=e.clients.get(r);for(let a=s.length-1;a>=0;a--){const d=s[a],l=Br(i.length-1,1+rt(i,d.clock+d.len-1));for(let c=l,f=i[c];c>0&&f.id.clock>=d.clock;f=i[c])c-=1+Js(i,c)}})},Ro=(t,e)=>{if(e<t.length){const s=t[e],r=s.doc,i=r.store,a=s.deleteSet,d=s._mergeStructs;try{ei(a),s.afterState=On(s.doc.store),r.emit("beforeObserverCalls",[s,r]);const l=[];s.changed.forEach((c,f)=>l.push(()=>{(f._item===null||!f._item.deleted)&&f._callObserver(s,c)})),l.push(()=>{s.changedParentTypes.forEach((c,f)=>{f._dEH.l.length>0&&(f._item===null||!f._item.deleted)&&(c=c.filter(b=>b.target._item===null||!b.target._item.deleted),c.forEach(b=>{b.currentTarget=f,b._path=null}),c.sort((b,u)=>b.path.length-u.path.length),l.push(()=>{No(f._dEH,c,s)}))}),l.push(()=>r.emit("afterTransaction",[s,r])),l.push(()=>{s._needFormattingCleanup&&yh(s)})}),qr(l,[])}finally{r.gc&&Ju(a,i,r.gcFilter),Xu(a,i),s.afterState.forEach((b,u)=>{const p=s.beforeState.get(u)||0;if(p!==b){const m=i.clients.get(u),y=Lt(rt(m,p),1);for(let _=m.length-1;_>=y;)_-=1+Js(m,_)}});for(let b=d.length-1;b>=0;b--){const{client:u,clock:p}=d[b].id,m=i.clients.get(u),y=rt(m,p);y+1<m.length&&Js(m,y+1)>1||y>0&&Js(m,y)}if(!s.local&&s.afterState.get(r.clientID)!==s.beforeState.get(r.clientID)&&(fo(Ln,Ke,"[yjs] ",Ct,co,"Changed the client-id because another client seems to be using it."),r.clientID=bo()),r.emit("afterTransactionCleanup",[s,r]),r._observers.has("update")){const b=new Ls;$i(b,s)&&r.emit("update",[b.toUint8Array(),s.origin,r,s])}if(r._observers.has("updateV2")){const b=new Tt;$i(b,s)&&r.emit("updateV2",[b.toUint8Array(),s.origin,r,s])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:f}=s;(l.size>0||f.size>0||c.size>0)&&(l.forEach(b=>{b.clientID=r.clientID,b.collectionid==null&&(b.collectionid=r.collectionid),r.subdocs.add(b)}),f.forEach(b=>r.subdocs.delete(b)),r.emit("subdocs",[{loaded:c,added:l,removed:f},r,s]),f.forEach(b=>b.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):Ro(t,e+1)}}},we=(t,e,s=null,r=!0)=>{const i=t._transactionCleanups;let a=!1,d=null;t._transaction===null&&(a=!0,t._transaction=new Ku(t,s,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{d=e(t._transaction)}finally{if(a){const l=t._transaction===i[0];t._transaction=null,l&&Ro(i,0)}}return d};function*Zu(t){const e=oe(t.restDecoder);for(let s=0;s<e;s++){const r=oe(t.restDecoder),i=t.readClient();let a=oe(t.restDecoder);for(let d=0;d<r;d++){const l=t.readInfo();if(l===10){const c=oe(t.restDecoder);yield new qe(me(i,a),c),a+=c}else if((Sn&l)!==0){const c=(l&(lt|ze))===0,f=new Ce(me(i,a),null,(l&ze)===ze?t.readLeftID():null,null,(l&lt)===lt?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(l&xs)===xs?t.readString():null,Ko(t,l));yield f,a+=f.length}else{const c=t.readLen();yield new Ye(me(i,a),c),a+=c}}}}class ri{constructor(e,s){this.gen=Zu(e),this.curr=null,this.done=!1,this.filterSkips=s,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===qe);return this.curr}}class ii{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Qu=t=>rn(t,wo,Ls),eh=(t,e)=>{if(t.constructor===Ye){const{client:s,clock:r}=t.id;return new Ye(me(s,r+e),t.length-e)}else if(t.constructor===qe){const{client:s,clock:r}=t.id;return new qe(me(s,r+e),t.length-e)}else{const s=t,{client:r,clock:i}=s.id;return new Ce(me(r,i+e),null,me(r,i+e-1),null,s.rightOrigin,s.parent,s.parentSub,s.content.splice(e))}},rn=(t,e=ts,s=Tt)=>{if(t.length===1)return t[0];const r=t.map(b=>new e(at(b)));let i=r.map(b=>new ri(b,!0)),a=null;const d=new s,l=new ii(d);for(;i=i.filter(p=>p.curr!==null),i.sort((p,m)=>{if(p.curr.id.client===m.curr.id.client){const y=p.curr.id.clock-m.curr.id.clock;return y===0?p.curr.constructor===m.curr.constructor?0:p.curr.constructor===qe?1:-1:y}else return m.curr.id.client-p.curr.id.client}),i.length!==0;){const b=i[0],u=b.curr.id.client;if(a!==null){let p=b.curr,m=!1;for(;p!==null&&p.id.clock+p.length<=a.struct.id.clock+a.struct.length&&p.id.client>=a.struct.id.client;)p=b.next(),m=!0;if(p===null||p.id.client!==u||m&&p.id.clock>a.struct.id.clock+a.struct.length)continue;if(u!==a.struct.id.client)gt(l,a.struct,a.offset),a={struct:p,offset:0},b.next();else if(a.struct.id.clock+a.struct.length<p.id.clock)if(a.struct.constructor===qe)a.struct.length=p.id.clock+p.length-a.struct.id.clock;else{gt(l,a.struct,a.offset);const y=p.id.clock-a.struct.id.clock-a.struct.length;a={struct:new qe(me(u,a.struct.id.clock+a.struct.length),y),offset:0}}else{const y=a.struct.id.clock+a.struct.length-p.id.clock;y>0&&(a.struct.constructor===qe?a.struct.length-=y:p=eh(p,y)),a.struct.mergeWith(p)||(gt(l,a.struct,a.offset),a={struct:p,offset:0},b.next())}}else a={struct:b.curr,offset:0},b.next();for(let p=b.curr;p!==null&&p.id.client===u&&p.id.clock===a.struct.id.clock+a.struct.length&&p.constructor!==qe;p=b.next())gt(l,a.struct,a.offset),a={struct:p,offset:0}}a!==null&&(gt(l,a.struct,a.offset),a=null),ai(l);const c=r.map(b=>ti(b)),f=Au(c);return is(d,f),d.toUint8Array()},th=(t,e,s=ts,r=Tt)=>{const i=jo(e),a=new r,d=new ii(a),l=new s(at(t)),c=new ri(l,!1);for(;c.curr;){const b=c.curr,u=b.id.client,p=i.get(u)||0;if(c.curr.constructor===qe){c.next();continue}if(b.id.clock+b.length>p)for(gt(d,b,Lt(p-b.id.clock,0)),c.next();c.curr&&c.curr.id.client===u;)gt(d,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===u&&c.curr.id.clock+c.curr.length<=p;)c.next()}ai(d);const f=ti(l);return is(a,f),a.toUint8Array()},Io=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:ke(t.encoder.restEncoder)}),t.encoder.restEncoder=Le(),t.written=0)},gt=(t,e,s)=>{t.written>0&&t.currClient!==e.id.client&&Io(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),ne(t.encoder.restEncoder,e.id.clock+s)),e.write(t.encoder,s),t.written++},ai=t=>{Io(t);const e=t.encoder.restEncoder;ne(e,t.clientStructs.length);for(let s=0;s<t.clientStructs.length;s++){const r=t.clientStructs[s];ne(e,r.written),jn(e,r.restEncoder)}},sh=(t,e,s,r)=>{const i=new s(at(t)),a=new ri(i,!1),d=new r,l=new ii(d);for(let f=a.curr;f!==null;f=a.next())gt(l,e(f),0);ai(l);const c=ti(i);return is(d,c),d.toUint8Array()},nh=t=>sh(t,Nd,ts,Ls),Hi="You must not compute changes after the event-handler fired.";class Pn{constructor(e,s){this.target=e,this.currentTarget=e,this.transaction=s,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=rh(this.currentTarget,this.target))}deletes(e){return yo(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ve(Hi);const e=new Map,s=this.target;this.transaction.changed.get(s).forEach(i=>{if(i!==null){const a=s._map.get(i);let d,l;if(this.adds(a)){let c=a.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(a))if(c!==null&&this.deletes(c))d="delete",l=Fn(c.content.getContent());else return;else c!==null&&this.deletes(c)?(d="update",l=Fn(c.content.getContent())):(d="add",l=void 0)}else if(this.deletes(a))d="delete",l=Fn(a.content.getContent());else return;e.set(i,{action:d,oldValue:l})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ve(Hi);const s=this.target,r=xt(),i=xt(),a=[];if(e={added:r,deleted:i,delta:a,keys:this.keys},this.transaction.changed.get(s).has(null)){let l=null;const c=()=>{l&&a.push(l)};for(let f=s._start;f!==null;f=f.right)f.deleted?this.deletes(f)&&!this.adds(f)&&((l===null||l.delete===void 0)&&(c(),l={delete:0}),l.delete+=f.length,i.add(f)):this.adds(f)?((l===null||l.insert===void 0)&&(c(),l={insert:[]}),l.insert=l.insert.concat(f.content.getContent()),r.add(f)):((l===null||l.retain===void 0)&&(c(),l={retain:0}),l.retain+=f.length);l!==null&&l.retain===void 0&&c()}this._changes=e}return e}}const rh=(t,e)=>{const s=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)s.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;s.unshift(r)}e=e._item.parent}return s},We=()=>{Eu("Invalid access: Add Yjs type to a document before reading data.")},Lo=80;let oi=0;class ih{constructor(e,s){e.marker=!0,this.p=e,this.index=s,this.timestamp=oi++}}const ah=t=>{t.timestamp=oi++},Do=(t,e,s)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=s,t.timestamp=oi++},oh=(t,e,s)=>{if(t.length>=Lo){const r=t.reduce((i,a)=>i.timestamp<a.timestamp?i:a);return Do(r,e,s),r}else{const r=new ih(e,s);return t.push(r),r}},Wn=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const s=t._searchMarker.length===0?null:t._searchMarker.reduce((a,d)=>Ys(e-a.index)<Ys(e-d.index)?a:d);let r=t._start,i=0;for(s!==null&&(r=s.p,i=s.index,ah(s));r.right!==null&&i<e;){if(!r.deleted&&r.countable){if(e<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return s!==null&&Ys(s.index-i)<r.parent.length/Lo?(Do(s,r,i),s):oh(t._searchMarker,r,i)},js=(t,e,s)=>{for(let r=t.length-1;r>=0;r--){const i=t[r];if(s>0){let a=i.p;for(a.marker=!1;a&&(a.deleted||!a.countable);)a=a.left,a&&!a.deleted&&a.countable&&(i.index-=a.length);if(a===null||a.marker===!0){t.splice(r,1);continue}i.p=a,a.marker=!0}(e<i.index||s>0&&e===i.index)&&(i.index=Lt(e,i.index+s))}},Un=(t,e,s)=>{const r=t,i=e.changedParentTypes;for(;He(i,t,()=>[]).push(s),t._item!==null;)t=t._item.parent;No(r._eH,s,e)};class Pe{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Wi(),this._dEH=Wi(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,s){this.doc=e,this._item=s}_copy(){throw Qe()}clone(){throw Qe()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,s){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Ui(this._eH,e)}observeDeep(e){Ui(this._dEH,e)}unobserve(e){Bi(this._eH,e)}unobserveDeep(e){Bi(this._dEH,e)}toJSON(){}}const Mo=(t,e,s)=>{t.doc??We(),e<0&&(e=t._length+e),s<0&&(s=t._length+s);let r=s-e;const i=[];let a=t._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){const d=a.content.getContent();if(d.length<=e)e-=d.length;else{for(let l=e;l<d.length&&r>0;l++)i.push(d[l]),r--;e=0}}a=a.right}return i},Oo=t=>{t.doc??We();const e=[];let s=t._start;for(;s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i<r.length;i++)e.push(r[i])}s=s.right}return e},Es=(t,e)=>{let s=0,r=t._start;for(t.doc??We();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let a=0;a<i.length;a++)e(i[a],s++,t)}r=r.right}},Po=(t,e)=>{const s=[];return Es(t,(r,i)=>{s.push(e(r,i,t))}),s},lh=t=>{let e=t._start,s=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(s===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};s=e.content.getContent(),r=0,e=e.right}const i=s[r++];return s.length<=r&&(s=null),{done:!1,value:i}}}},Wo=(t,e)=>{t.doc??We();const s=Wn(t,e);let r=t._start;for(s!==null&&(r=s.p,e-=s.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e<r.length)return r.content.getContent()[e];e-=r.length}},an=(t,e,s,r)=>{let i=s;const a=t.doc,d=a.clientID,l=a.store,c=s===null?e._start:s.right;let f=[];const b=()=>{f.length>0&&(i=new Ce(me(d,De(l,d)),i,i&&i.lastId,c,c&&c.id,e,null,new It(f)),i.integrate(t,0),f=[])};r.forEach(u=>{if(u===null)f.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:f.push(u);break;default:switch(b(),u.constructor){case Uint8Array:case ArrayBuffer:i=new Ce(me(d,De(l,d)),i,i&&i.lastId,c,c&&c.id,e,null,new Ds(new Uint8Array(u))),i.integrate(t,0);break;case as:i=new Ce(me(d,De(l,d)),i,i&&i.lastId,c,c&&c.id,e,null,new Ms(u)),i.integrate(t,0);break;default:if(u instanceof Pe)i=new Ce(me(d,De(l,d)),i,i&&i.lastId,c,c&&c.id,e,null,new pt(u)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),b()},Uo=()=>Ve("Length exceeded!"),Bo=(t,e,s,r)=>{if(s>e._length)throw Uo();if(s===0)return e._searchMarker&&js(e._searchMarker,s,r.length),an(t,e,null,r);const i=s,a=Wn(e,s);let d=e._start;for(a!==null&&(d=a.p,s-=a.index,s===0&&(d=d.prev,s+=d&&d.countable&&!d.deleted?d.length:0));d!==null;d=d.right)if(!d.deleted&&d.countable){if(s<=d.length){s<d.length&&wt(t,me(d.id.client,d.id.clock+s));break}s-=d.length}return e._searchMarker&&js(e._searchMarker,i,r.length),an(t,e,d,r)},ch=(t,e,s)=>{let i=(e._searchMarker||[]).reduce((a,d)=>d.index>a.index?d:a,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return an(t,e,i,s)},Fo=(t,e,s,r)=>{if(r===0)return;const i=s,a=r,d=Wn(e,s);let l=e._start;for(d!==null&&(l=d.p,s-=d.index);l!==null&&s>0;l=l.right)!l.deleted&&l.countable&&(s<l.length&&wt(t,me(l.id.client,l.id.clock+s)),s-=l.length);for(;r>0&&l!==null;)l.deleted||(r<l.length&&wt(t,me(l.id.client,l.id.clock+r)),l.delete(t),r-=l.length),l=l.right;if(r>0)throw Uo();e._searchMarker&&js(e._searchMarker,i,-a+r)},on=(t,e,s)=>{const r=e._map.get(s);r!==void 0&&r.delete(t)},li=(t,e,s,r)=>{const i=e._map.get(s)||null,a=t.doc,d=a.clientID;let l;if(r==null)l=new It([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new It([r]);break;case Uint8Array:l=new Ds(r);break;case as:l=new Ms(r);break;default:if(r instanceof Pe)l=new pt(r);else throw new Error("Unexpected content type")}new Ce(me(d,De(a.store,d)),i,i&&i.lastId,null,null,e,s,l).integrate(t,0)},ci=(t,e)=>{t.doc??We();const s=t._map.get(e);return s!==void 0&&!s.deleted?s.content.getContent()[s.length-1]:void 0},$o=t=>{const e={};return t.doc??We(),t._map.forEach((s,r)=>{s.deleted||(e[r]=s.content.getContent()[s.length-1])}),e},zo=(t,e)=>{t.doc??We();const s=t._map.get(e);return s!==void 0&&!s.deleted},dh=(t,e)=>{const s={};return t._map.forEach((r,i)=>{let a=r;for(;a!==null&&(!e.sv.has(a.id.client)||a.id.clock>=(e.sv.get(a.id.client)||0));)a=a.left;a!==null&&$t(a,e)&&(s[i]=a.content.getContent()[a.length-1])}),s},Ps=t=>(t.doc??We(),Cu(t._map.entries(),e=>!e[1].deleted));class uh extends Pn{}class Gt extends Pe{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const s=new Gt;return s.push(e),s}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Gt}clone(){const e=new Gt;return e.insert(0,this.toArray().map(s=>s instanceof Pe?s.clone():s)),e}get length(){return this.doc??We(),this._length}_callObserver(e,s){super._callObserver(e,s),Un(this,e,new uh(this,e))}insert(e,s){this.doc!==null?we(this.doc,r=>{Bo(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}push(e){this.doc!==null?we(this.doc,s=>{ch(s,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,s=1){this.doc!==null?we(this.doc,r=>{Fo(r,this,e,s)}):this._prelimContent.splice(e,s)}get(e){return Wo(this,e)}toArray(){return Oo(this)}slice(e=0,s=this.length){return Mo(this,e,s)}toJSON(){return this.map(e=>e instanceof Pe?e.toJSON():e)}map(e){return Po(this,e)}forEach(e){Es(this,e)}[Symbol.iterator](){return lh(this)}_write(e){e.writeTypeRef(Oh)}}const hh=t=>new Gt;class fh extends Pn{constructor(e,s,r){super(e,s),this.keysChanged=r}}class At extends Pe{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,s){super._integrate(e,s),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new At}clone(){const e=new At;return this.forEach((s,r)=>{e.set(r,s instanceof Pe?s.clone():s)}),e}_callObserver(e,s){Un(this,e,new fh(this,e,s))}toJSON(){this.doc??We();const e={};return this._map.forEach((s,r)=>{if(!s.deleted){const i=s.content.getContent()[s.length-1];e[r]=i instanceof Pe?i.toJSON():i}}),e}get size(){return[...Ps(this)].length}keys(){return Kn(Ps(this),e=>e[0])}values(){return Kn(Ps(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Kn(Ps(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??We(),this._map.forEach((s,r)=>{s.deleted||e(s.content.getContent()[s.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?we(this.doc,s=>{on(s,this,e)}):this._prelimContent.delete(e)}set(e,s){return this.doc!==null?we(this.doc,r=>{li(r,this,e,s)}):this._prelimContent.set(e,s),s}get(e){return ci(this,e)}has(e){return zo(this,e)}clear(){this.doc!==null?we(this.doc,e=>{this.forEach(function(s,r,i){on(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Ph)}}const ph=t=>new At,yt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Sd(t,e);class xr{constructor(e,s,r,i){this.left=e,this.right=s,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Xe(),this.right.content.constructor){case Te:this.right.deleted||os(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const Vi=(t,e,s)=>{for(;e.right!==null&&s>0;){switch(e.right.content.constructor){case Te:e.right.deleted||os(e.currentAttributes,e.right.content);break;default:e.right.deleted||(s<e.right.length&&wt(t,me(e.right.id.client,e.right.id.clock+s)),e.index+=e.right.length,s-=e.right.length);break}e.left=e.right,e.right=e.right.right}return e},Ws=(t,e,s,r)=>{const i=new Map,a=r?Wn(e,s):null;if(a){const d=new xr(a.p.left,a.p,a.index,i);return Vi(t,d,s-a.index)}else{const d=new xr(null,e._start,0,i);return Vi(t,d,s)}},Ho=(t,e,s,r)=>{for(;s.right!==null&&(s.right.deleted===!0||s.right.content.constructor===Te&&yt(r.get(s.right.content.key),s.right.content.value));)s.right.deleted||r.delete(s.right.content.key),s.forward();const i=t.doc,a=i.clientID;r.forEach((d,l)=>{const c=s.left,f=s.right,b=new Ce(me(a,De(i.store,a)),c,c&&c.lastId,f,f&&f.id,e,null,new Te(l,d));b.integrate(t,0),s.right=b,s.forward()})},os=(t,e)=>{const{key:s,value:r}=e;r===null?t.delete(s):t.set(s,r)},Vo=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Te&&yt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Go=(t,e,s,r)=>{const i=t.doc,a=i.clientID,d=new Map;for(const l in r){const c=r[l],f=s.currentAttributes.get(l)??null;if(!yt(f,c)){d.set(l,f);const{left:b,right:u}=s;s.right=new Ce(me(a,De(i.store,a)),b,b&&b.lastId,u,u&&u.id,e,null,new Te(l,c)),s.right.integrate(t,0),s.forward()}}return d},Xn=(t,e,s,r,i)=>{s.currentAttributes.forEach((p,m)=>{i[m]===void 0&&(i[m]=null)});const a=t.doc,d=a.clientID;Vo(s,i);const l=Go(t,e,s,i),c=r.constructor===String?new it(r):r instanceof Pe?new pt(r):new Dt(r);let{left:f,right:b,index:u}=s;e._searchMarker&&js(e._searchMarker,s.index,c.getLength()),b=new Ce(me(d,De(a.store,d)),f,f&&f.lastId,b,b&&b.id,e,null,c),b.integrate(t,0),s.right=b,s.index=u,s.forward(),Ho(t,e,s,l)},Gi=(t,e,s,r,i)=>{const a=t.doc,d=a.clientID;Vo(s,i);const l=Go(t,e,s,i);e:for(;s.right!==null&&(r>0||l.size>0&&(s.right.deleted||s.right.content.constructor===Te));){if(!s.right.deleted)switch(s.right.content.constructor){case Te:{const{key:c,value:f}=s.right.content,b=i[c];if(b!==void 0){if(yt(b,f))l.delete(c);else{if(r===0)break e;l.set(c,f)}s.right.delete(t)}else s.currentAttributes.set(c,f);break}default:r<s.right.length&&wt(t,me(s.right.id.client,s.right.id.clock+r)),r-=s.right.length;break}s.forward()}if(r>0){let c="";for(;r>0;r--)c+=`
65
- `;s.right=new Ce(me(d,De(a.store,d)),s.left,s.left&&s.left.lastId,s.right,s.right&&s.right.id,e,null,new it(c)),s.right.integrate(t,0),s.forward()}Ho(t,e,s,l)},Yo=(t,e,s,r,i)=>{let a=e;const d=Be();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===Te){const f=a.content;d.set(f.key,f)}a=a.right}let l=0,c=!1;for(;e!==a;){if(s===e&&(c=!0),!e.deleted){const f=e.content;switch(f.constructor){case Te:{const{key:b,value:u}=f,p=r.get(b)??null;(d.get(b)!==f||p===u)&&(e.delete(t),l++,!c&&(i.get(b)??null)===u&&p!==u&&(p===null?i.delete(b):i.set(b,p))),!c&&!e.deleted&&os(i,f);break}}}e=e.right}return l},mh=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const s=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Te){const r=e.content.key;s.has(r)?e.delete(t):s.add(r)}e=e.left}},gh=t=>{let e=0;return we(t.doc,s=>{let r=t._start,i=t._start,a=Be();const d=ur(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Te:os(d,i.content);break;default:e+=Yo(s,r,i,a,d),a=ur(d),r=i;break}i=i.right}}),e},yh=t=>{const e=new Set,s=t.doc;for(const[r,i]of t.afterState.entries()){const a=t.beforeState.get(r)||0;i!==a&&Ao(t,s.store.clients.get(r),a,i,d=>{!d.deleted&&d.content.constructor===Te&&d.constructor!==Ye&&e.add(d.parent)})}we(s,r=>{go(t,t.deleteSet,i=>{if(i instanceof Ye||!i.parent._hasFormatting||e.has(i.parent))return;const a=i.parent;i.content.constructor===Te?e.add(a):mh(r,i)});for(const i of e)gh(i)})},Yi=(t,e,s)=>{const r=s,i=ur(e.currentAttributes),a=e.right;for(;s>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case pt:case Dt:case it:s<e.right.length&&wt(t,me(e.right.id.client,e.right.id.clock+s)),s-=e.right.length,e.right.delete(t);break}e.forward()}a&&Yo(t,a,e.right,i,e.currentAttributes);const d=(e.left||e.right).parent;return d._searchMarker&&js(d._searchMarker,e.index,-r+s),e};class bh extends Pn{constructor(e,s,r){super(e,s),this.childListChanged=!1,this.keysChanged=new Set,r.forEach(i=>{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,s=[];we(e,r=>{const i=new Map,a=new Map;let d=this.target._start,l=null;const c={};let f="",b=0,u=0;const p=()=>{if(l!==null){let m=null;switch(l){case"delete":u>0&&(m={delete:u}),u=0;break;case"insert":(typeof f=="object"||f.length>0)&&(m={insert:f},i.size>0&&(m.attributes={},i.forEach((y,_)=>{y!==null&&(m.attributes[_]=y)}))),f="";break;case"retain":b>0&&(m={retain:b},kd(c)||(m.attributes=wd({},c))),b=0;break}m&&s.push(m),l=null}};for(;d!==null;){switch(d.content.constructor){case pt:case Dt:this.adds(d)?this.deletes(d)||(p(),l="insert",f=d.content.getContent()[0],p()):this.deletes(d)?(l!=="delete"&&(p(),l="delete"),u+=1):d.deleted||(l!=="retain"&&(p(),l="retain"),b+=1);break;case it:this.adds(d)?this.deletes(d)||(l!=="insert"&&(p(),l="insert"),f+=d.content.str):this.deletes(d)?(l!=="delete"&&(p(),l="delete"),u+=d.length):d.deleted||(l!=="retain"&&(p(),l="retain"),b+=d.length);break;case Te:{const{key:m,value:y}=d.content;if(this.adds(d)){if(!this.deletes(d)){const _=i.get(m)??null;yt(_,y)?y!==null&&d.delete(r):(l==="retain"&&p(),yt(y,a.get(m)??null)?delete c[m]:c[m]=y)}}else if(this.deletes(d)){a.set(m,y);const _=i.get(m)??null;yt(_,y)||(l==="retain"&&p(),c[m]=_)}else if(!d.deleted){a.set(m,y);const _=c[m];_!==void 0&&(yt(_,y)?_!==null&&d.delete(r):(l==="retain"&&p(),y===null?delete c[m]:c[m]=y))}d.deleted||(l==="insert"&&p(),os(i,d.content));break}}d=d.right}for(p();s.length>0;){const m=s[s.length-1];if(m.retain!==void 0&&m.attributes===void 0)s.pop();else break}}),this._delta=s}return this._delta}}class ss extends Pe{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??We(),this._length}_integrate(e,s){super._integrate(e,s);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new ss}clone(){const e=new ss;return e.applyDelta(this.toDelta()),e}_callObserver(e,s){super._callObserver(e,s);const r=new bh(this,e,s);Un(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??We();let e="",s=this._start;for(;s!==null;)!s.deleted&&s.countable&&s.content.constructor===it&&(e+=s.content.str),s=s.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:s=!0}={}){this.doc!==null?we(this.doc,r=>{const i=new xr(null,this._start,0,new Map);for(let a=0;a<e.length;a++){const d=e[a];if(d.insert!==void 0){const l=!s&&typeof d.insert=="string"&&a===e.length-1&&i.right===null&&d.insert.slice(-1)===`
66
- `?d.insert.slice(0,-1):d.insert;(typeof l!="string"||l.length>0)&&Xn(r,this,i,l,d.attributes||{})}else d.retain!==void 0?Gi(r,this,i,d.retain,d.attributes||{}):d.delete!==void 0&&Yi(r,i,d.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,s,r){this.doc??We();const i=[],a=new Map,d=this.doc;let l="",c=this._start;function f(){if(l.length>0){const u={};let p=!1;a.forEach((y,_)=>{p=!0,u[_]=y});const m={insert:l};p&&(m.attributes=u),i.push(m),l=""}}const b=()=>{for(;c!==null;){if($t(c,e)||s!==void 0&&$t(c,s))switch(c.content.constructor){case it:{const u=a.get("ychange");e!==void 0&&!$t(c,e)?(u===void 0||u.user!==c.id.client||u.type!=="removed")&&(f(),a.set("ychange",r?r("removed",c.id):{type:"removed"})):s!==void 0&&!$t(c,s)?(u===void 0||u.user!==c.id.client||u.type!=="added")&&(f(),a.set("ychange",r?r("added",c.id):{type:"added"})):u!==void 0&&(f(),a.delete("ychange")),l+=c.content.str;break}case pt:case Dt:{f();const u={insert:c.content.getContent()[0]};if(a.size>0){const p={};u.attributes=p,a.forEach((m,y)=>{p[y]=m})}i.push(u);break}case Te:$t(c,e)&&(f(),os(a,c.content));break}c=c.right}f()};return e||s?we(d,u=>{e&&yr(u,e),s&&yr(u,s),b()},"cleanup"):b(),i}insert(e,s,r){if(s.length<=0)return;const i=this.doc;i!==null?we(i,a=>{const d=Ws(a,this,e,!r);r||(r={},d.currentAttributes.forEach((l,c)=>{r[c]=l})),Xn(a,this,d,s,r)}):this._pending.push(()=>this.insert(e,s,r))}insertEmbed(e,s,r){const i=this.doc;i!==null?we(i,a=>{const d=Ws(a,this,e,!r);Xn(a,this,d,s,r||{})}):this._pending.push(()=>this.insertEmbed(e,s,r||{}))}delete(e,s){if(s===0)return;const r=this.doc;r!==null?we(r,i=>{Yi(i,Ws(i,this,e,!0),s)}):this._pending.push(()=>this.delete(e,s))}format(e,s,r){if(s===0)return;const i=this.doc;i!==null?we(i,a=>{const d=Ws(a,this,e,!1);d.right!==null&&Gi(a,this,d,s,r)}):this._pending.push(()=>this.format(e,s,r))}removeAttribute(e){this.doc!==null?we(this.doc,s=>{on(s,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,s){this.doc!==null?we(this.doc,r=>{li(r,this,e,s)}):this._pending.push(()=>this.setAttribute(e,s))}getAttribute(e){return ci(this,e)}getAttributes(){return $o(this)}_write(e){e.writeTypeRef(Wh)}}const xh=t=>new ss;class Zn{constructor(e,s=()=>!0){this._filter=s,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??We()}[Symbol.iterator](){return this}next(){let e=this._currentNode,s=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(s)))do if(s=e.content.type,!e.deleted&&(s.constructor===ns||s.constructor===Rt)&&s._start!==null)e=s._start;else for(;e!==null;){const r=e.next;if(r!==null){e=r;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Rt extends Pe{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Rt}clone(){const e=new Rt;return e.insert(0,this.toArray().map(s=>s instanceof Pe?s.clone():s)),e}get length(){return this.doc??We(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Zn(this,e)}querySelector(e){e=e.toUpperCase();const r=new Zn(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),dt(new Zn(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e))}_callObserver(e,s){Un(this,e,new _h(this,s,e))}toString(){return Po(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,s={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),Es(this,a=>{i.insertBefore(a.toDOM(e,s,r),null)}),i}insert(e,s){this.doc!==null?we(this.doc,r=>{Bo(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}insertAfter(e,s){if(this.doc!==null)we(this.doc,r=>{const i=e&&e instanceof Pe?e._item:e;an(r,this,i,s)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(a=>a===e)+1;if(i===0&&e!==null)throw Ve("Reference item not found");r.splice(i,0,...s)}}delete(e,s=1){this.doc!==null?we(this.doc,r=>{Fo(r,this,e,s)}):this._prelimContent.splice(e,s)}toArray(){return Oo(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Wo(this,e)}slice(e=0,s=this.length){return Mo(this,e,s)}forEach(e){Es(this,e)}_write(e){e.writeTypeRef(Bh)}}const wh=t=>new Rt;class ns extends Rt{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,s){super._integrate(e,s),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new ns(this.nodeName)}clone(){const e=new ns(this.nodeName),s=this.getAttributes();return _d(s,(r,i)=>{e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof Pe?r.clone():r)),e}toString(){const e=this.getAttributes(),s=[],r=[];for(const l in e)r.push(l);r.sort();const i=r.length;for(let l=0;l<i;l++){const c=r[l];s.push(c+'="'+e[c]+'"')}const a=this.nodeName.toLocaleLowerCase(),d=s.length>0?" "+s.join(" "):"";return`<${a}${d}>${super.toString()}</${a}>`}removeAttribute(e){this.doc!==null?we(this.doc,s=>{on(s,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,s){this.doc!==null?we(this.doc,r=>{li(r,this,e,s)}):this._prelimAttrs.set(e,s)}getAttribute(e){return ci(this,e)}hasAttribute(e){return zo(this,e)}getAttributes(e){return e?dh(this,e):$o(this)}toDOM(e=document,s={},r){const i=e.createElement(this.nodeName),a=this.getAttributes();for(const d in a){const l=a[d];typeof l=="string"&&i.setAttribute(d,l)}return Es(this,d=>{i.appendChild(d.toDOM(e,s,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(Uh),e.writeKey(this.nodeName)}}const vh=t=>new ns(t.readKey());class _h extends Pn{constructor(e,s,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,s.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class ln extends At{constructor(e){super(),this.hookName=e}_copy(){return new ln(this.hookName)}clone(){const e=new ln(this.hookName);return this.forEach((s,r)=>{e.set(r,s)}),e}toDOM(e=document,s={},r){const i=s[this.hookName];let a;return i!==void 0?a=i.createDom(this):a=document.createElement(this.hookName),a.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(a,this),a}_write(e){e.writeTypeRef(Fh),e.writeKey(this.hookName)}}const kh=t=>new ln(t.readKey());class cn extends ss{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new cn}clone(){const e=new cn;return e.applyDelta(this.toDelta()),e}toDOM(e=document,s,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const s=[];for(const i in e.attributes){const a=[];for(const d in e.attributes[i])a.push({key:d,value:e.attributes[i][d]});a.sort((d,l)=>d.key<l.key?-1:1),s.push({nodeName:i,attrs:a})}s.sort((i,a)=>i.nodeName<a.nodeName?-1:1);let r="";for(let i=0;i<s.length;i++){const a=s[i];r+=`<${a.nodeName}`;for(let d=0;d<a.attrs.length;d++){const l=a.attrs[d];r+=` ${l.key}="${l.value}"`}r+=">"}r+=e.insert;for(let i=s.length-1;i>=0;i--)r+=`</${s[i].nodeName}>`;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef($h)}}const Sh=t=>new cn;class di{constructor(e,s){this.id=e,this.length=s}get deleted(){throw Qe()}mergeWith(e){return!1}write(e,s,r){throw Qe()}integrate(e,s){throw Qe()}}const jh=0;class Ye extends di{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,s){s>0&&(this.id.clock+=s,this.length-=s),To(e.doc.store,this)}write(e,s){e.writeInfo(jh),e.writeLen(this.length-s)}getMissing(e,s){return null}}class Ds{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ds(this.content)}splice(e){throw Qe()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeBuf(this.content)}getRef(){return 3}}const Eh=t=>new Ds(t.readBuf());class Ns{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ns(this.len)}splice(e){const s=new Ns(this.len-e);return this.len=e,s}mergeWith(e){return this.len+=e.len,!0}integrate(e,s){nn(e.deleteSet,s.id.client,s.id.clock,this.len),s.markDeleted()}delete(e){}gc(e){}write(e,s){e.writeLen(this.len-s)}getRef(){return 1}}const Nh=t=>new Ns(t.readLen()),qo=(t,e)=>new as({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Ms{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const s={};this.opts=s,e.gc||(s.gc=!1),e.autoLoad&&(s.autoLoad=!0),e.meta!==null&&(s.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Ms(qo(this.doc.guid,this.opts))}splice(e){throw Qe()}mergeWith(e){return!1}integrate(e,s){this.doc._item=s,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,s){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const Ch=t=>new Ms(qo(t.readString(),t.readAny()));class Dt{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Dt(this.embed)}splice(e){throw Qe()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeJSON(this.embed)}getRef(){return 5}}const Th=t=>new Dt(t.readJSON());class Te{constructor(e,s){this.key=e,this.value=s}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Te(this.key,this.value)}splice(e){throw Qe()}mergeWith(e){return!1}integrate(e,s){const r=s.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,s){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const Ah=t=>new Te(t.readKey(),t.readJSON());class dn{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new dn(this.arr)}splice(e){const s=new dn(this.arr.slice(e));return this.arr=this.arr.slice(0,e),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){const r=this.arr.length;e.writeLen(r-s);for(let i=s;i<r;i++){const a=this.arr[i];e.writeString(a===void 0?"undefined":JSON.stringify(a))}}getRef(){return 2}}const Rh=t=>{const e=t.readLen(),s=[];for(let r=0;r<e;r++){const i=t.readString();i==="undefined"?s.push(void 0):s.push(JSON.parse(i))}return new dn(s)},Ih=ks("node_env")==="development";class It{constructor(e){this.arr=e,Ih&&Wa(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new It(this.arr)}splice(e){const s=new It(this.arr.slice(e));return this.arr=this.arr.slice(0,e),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){const r=this.arr.length;e.writeLen(r-s);for(let i=s;i<r;i++){const a=this.arr[i];e.writeAny(a)}}getRef(){return 8}}const Lh=t=>{const e=t.readLen(),s=[];for(let r=0;r<e;r++)s.push(t.readAny());return new It(s)};class it{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new it(this.str)}splice(e){const s=new it(this.str.slice(e));this.str=this.str.slice(0,e);const r=this.str.charCodeAt(e-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",s.str="�"+s.str.slice(1)),s}mergeWith(e){return this.str+=e.str,!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeString(s===0?this.str:this.str.slice(s))}getRef(){return 4}}const Dh=t=>new it(t.readString()),Mh=[hh,ph,xh,vh,wh,kh,Sh],Oh=0,Ph=1,Wh=2,Uh=3,Bh=4,Fh=5,$h=6;class pt{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new pt(this.type._copy())}splice(e){throw Qe()}mergeWith(e){return!1}integrate(e,s){this.type._integrate(e.doc,s)}delete(e){let s=this.type._start;for(;s!==null;)s.deleted?s.id.clock<(e.beforeState.get(s.id.client)||0)&&e._mergeStructs.push(s):s.delete(e),s=s.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let s=this.type._start;for(;s!==null;)s.gc(e,!0),s=s.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,s){this.type._write(e)}getRef(){return 7}}const zh=t=>new pt(Mh[t.readTypeRef()](t)),un=(t,e,s)=>{const{client:r,clock:i}=e.id,a=new Ce(me(r,i+s),e,me(r,i+s-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(s));return e.deleted&&a.markDeleted(),e.keep&&(a.keep=!0),e.redone!==null&&(a.redone=me(e.redone.client,e.redone.clock+s)),e.right=a,a.right!==null&&(a.right.left=a),t._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),e.length=s,a};class Ce extends di{constructor(e,s,r,i,a,d,l,c){super(e,c.getLength()),this.origin=r,this.left=s,this.right=i,this.rightOrigin=a,this.parent=d,this.parentSub=l,this.redone=null,this.content=c,this.info=this.content.isCountable()?Si:0}set marker(e){(this.info&zn)>0!==e&&(this.info^=zn)}get marker(){return(this.info&zn)>0}get keep(){return(this.info&ki)>0}set keep(e){this.keep!==e&&(this.info^=ki)}get countable(){return(this.info&Si)>0}get deleted(){return(this.info&$n)>0}set deleted(e){this.deleted!==e&&(this.info^=$n)}markDeleted(){this.info|=$n}getMissing(e,s){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=De(s,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=De(s,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Vt&&this.id.client!==this.parent.client&&this.parent.clock>=De(s,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Fi(e,s,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=wt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ye||this.right&&this.right.constructor===Ye)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Ce?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Ce&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Vt){const r=Jn(s,this.parent);r.constructor===Ye?this.parent=null:this.parent=r.content.type}return null}integrate(e,s){if(s>0&&(this.id.clock+=s,this.left=Fi(e,e.doc.store,me(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(s),this.length-=s),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const a=new Set,d=new Set;for(;i!==null&&i!==this.right;){if(d.add(i),a.add(i),Os(this.origin,i.origin)){if(i.id.client<this.id.client)r=i,a.clear();else if(Os(this.rightOrigin,i.rightOrigin))break}else if(i.origin!==null&&d.has(Jn(e.doc.store,i.origin)))a.has(Jn(e.doc.store,i.origin))||(r=i,a.clear());else break;i=i.right}this.left=r}if(this.left!==null){const r=this.left.right;this.right=r,this.left.right=this}else{let r;if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start,this.parent._start=this;this.right=r}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),To(e.doc.store,this),this.content.integrate(e,this),zi(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Ye(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:me(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Os(e.origin,this.lastId)&&this.right===e&&Os(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const s=this.parent._searchMarker;return s&&s.forEach(r=>{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const s=this.parent;this.countable&&this.parentSub===null&&(s._length-=this.length),this.markDeleted(),nn(e.deleteSet,this.id.client,this.id.clock,this.length),zi(e,s,this.parentSub),this.content.delete(e)}}gc(e,s){if(!this.deleted)throw Xe();this.content.gc(e),s?qu(e,this,new Ye(this.id,this.length)):this.content=new Ns(this.length)}write(e,s){const r=s>0?me(this.id.client,this.id.clock+s-1):this.origin,i=this.rightOrigin,a=this.parentSub,d=this.content.getRef()&Sn|(r===null?0:ze)|(i===null?0:lt)|(a===null?0:xs);if(e.writeInfo(d),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const l=this.parent;if(l._item!==void 0){const c=l._item;if(c===null){const f=Gu(l);e.writeParentInfo(!0),e.writeString(f)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else l.constructor===String?(e.writeParentInfo(!0),e.writeString(l)):l.constructor===Vt?(e.writeParentInfo(!1),e.writeLeftID(l)):Xe();a!==null&&e.writeString(a)}this.content.write(e,s)}}const Ko=(t,e)=>Hh[e&Sn](t),Hh=[()=>{Xe()},Nh,Rh,Eh,Dh,Th,Ah,zh,Lh,Ch,()=>{Xe()}],Vh=10;class qe extends di{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,s){Xe()}write(e,s){e.writeInfo(Vh),ne(e.restEncoder,this.length-s)}getMissing(e,s){return null}}const Jo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Xo="__ $YJS$ __";Jo[Xo]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Jo[Xo]=!0;const Mt=t=>Zt((e,s)=>{t.onerror=r=>s(new Error(r.target.error)),t.onsuccess=r=>e(r.target.result)}),Gh=(t,e)=>Zt((s,r)=>{const i=indexedDB.open(t);i.onupgradeneeded=a=>e(a.target.result),i.onerror=a=>r(Ve(a.target.error)),i.onsuccess=a=>{const d=a.target.result;d.onversionchange=()=>{d.close()},s(d)}}),Yh=t=>Mt(indexedDB.deleteDatabase(t)),qh=(t,e)=>e.forEach(s=>t.createObjectStore.apply(t,s)),hs=(t,e,s="readwrite")=>{const r=t.transaction(e,s);return e.map(i=>sf(r,i))},Zo=(t,e)=>Mt(t.count(e)),Kh=(t,e)=>Mt(t.get(e)),Qo=(t,e)=>Mt(t.delete(e)),Jh=(t,e,s)=>Mt(t.put(e,s)),wr=(t,e)=>Mt(t.add(e)),Xh=(t,e,s)=>Mt(t.getAll(e,s)),Zh=(t,e,s)=>{let r=null;return tf(t,e,i=>(r=i,!1),s).then(()=>r)},Qh=(t,e=null)=>Zh(t,e,"prev"),ef=(t,e)=>Zt((s,r)=>{t.onerror=r,t.onsuccess=async i=>{const a=i.target.result;if(a===null||await e(a)===!1)return s();a.continue()}}),tf=(t,e,s,r="next")=>ef(t.openKeyCursor(e,r),i=>s(i.key)),sf=(t,e)=>t.objectStore(e),nf=(t,e)=>IDBKeyRange.upperBound(t,e),rf=(t,e)=>IDBKeyRange.lowerBound(t,e),Qn="custom",el="updates",tl=500,sl=(t,e=()=>{},s=()=>{})=>{const[r]=hs(t.db,[el]);return Xh(r,rf(t._dbref,!1)).then(i=>{t._destroyed||(e(r),we(t.doc,()=>{i.forEach(a=>So(t.doc,a))},t,!1),s(r))}).then(()=>Qh(r).then(i=>{t._dbref=i+1})).then(()=>Zo(r).then(i=>{t._dbsize=i})).then(()=>r)},af=(t,e=!0)=>sl(t).then(s=>{(e||t._dbsize>=tl)&&wr(s,ni(t.doc)).then(()=>Qo(s,nf(t._dbref,!0))).then(()=>Zo(s).then(r=>{t._dbsize=r}))});class of extends Ur{constructor(e,s){super(),this.doc=s,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=Gh(e,r=>qh(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Zt(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,sl(this,d=>wr(d,ni(s)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,i)=>{if(this.db&&i!==this){const[a]=hs(this.db,[el]);wr(a,r),++this._dbsize>=tl&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{af(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},s.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),s.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{Yh(this.name)})}get(e){return this._db.then(s=>{const[r]=hs(s,[Qn],"readonly");return Kh(r,e)})}set(e,s){return this._db.then(r=>{const[i]=hs(r,[Qn]);return Jh(i,s,e)})}del(e){return this._db.then(s=>{const[r]=hs(s,[Qn]);return Qo(r,e)})}}const lf=1200,cf=2500,hn=3e4,vr=t=>{if(t.shouldConnect&&t.ws===null){const e=new WebSocket(t.url),s=t.binaryType;let r=null;s&&(e.binaryType=s),t.ws=e,t.connecting=!0,t.connected=!1,e.onmessage=d=>{t.lastMessageReceived=ut();const l=d.data,c=typeof l=="string"?JSON.parse(l):l;c&&c.type==="pong"&&(clearTimeout(r),r=setTimeout(a,hn/2)),t.emit("message",[c,t])};const i=d=>{t.ws!==null&&(t.ws=null,t.connecting=!1,t.connected?(t.connected=!1,t.emit("disconnect",[{type:"disconnect",error:d},t])):t.unsuccessfulReconnects++,setTimeout(vr,Br(Pc(t.unsuccessfulReconnects+1)*lf,cf),t)),clearTimeout(r)},a=()=>{t.ws===e&&t.send({type:"ping"})};e.onclose=()=>i(null),e.onerror=d=>i(d),e.onopen=()=>{t.lastMessageReceived=ut(),t.connecting=!1,t.connected=!0,t.unsuccessfulReconnects=0,t.emit("connect",[{type:"connect"},t]),r=setTimeout(a,hn/2)}}};class df extends Ur{constructor(e,{binaryType:s}={}){super(),this.url=e,this.ws=null,this.binaryType=s||null,this.connected=!1,this.connecting=!1,this.unsuccessfulReconnects=0,this.lastMessageReceived=0,this.shouldConnect=!0,this._checkInterval=setInterval(()=>{this.connected&&hn<ut()-this.lastMessageReceived&&this.ws.close()},hn/2),vr(this)}send(e){this.ws&&this.ws.send(JSON.stringify(e))}destroy(){clearInterval(this._checkInterval),this.disconnect(),super.destroy()}disconnect(){this.shouldConnect=!1,this.ws!==null&&this.ws.close()}connect(){this.shouldConnect=!0,!this.connected&&this.ws===null&&vr(this)}}const nl=new Map;class uf{constructor(e){this.room=e,this.onmessage=null,this._onChange=s=>s.key===e&&this.onmessage!==null&&this.onmessage({data:Ha(s.newValue||"")}),yd(this._onChange)}postMessage(e){Oa.setItem(this.room,za(Dd(e)))}close(){bd(this._onChange)}}const hf=typeof BroadcastChannel>"u"?uf:BroadcastChannel,ui=t=>He(nl,t,()=>{const e=xt(),s=new hf(t);return s.onmessage=r=>e.forEach(i=>i(r.data,"broadcastchannel")),{bc:s,subs:e}}),ff=(t,e)=>(ui(t).subs.add(e),e),pf=(t,e)=>{const s=ui(t),r=s.subs.delete(e);return r&&s.subs.size===0&&(s.bc.close(),nl.delete(t)),r},mf=(t,e,s=null)=>{const r=ui(t);r.bc.postMessage(e),r.subs.forEach(i=>i(e,s))},gf=()=>{let t=!0;return(e,s)=>{if(t){t=!1;try{e()}finally{t=!0}}else s!==void 0&&s()}};function Us(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var er={exports:{}},qi;function yf(){return qi||(qi=1,(function(t,e){(function(s){t.exports=s()})(function(){var s=Math.floor,r=Math.abs,i=Math.pow;return(function(){function a(d,l,c){function f(p,m){if(!l[p]){if(!d[p]){var y=typeof Us=="function"&&Us;if(!m&&y)return y(p,!0);if(b)return b(p,!0);var _=new Error("Cannot find module '"+p+"'");throw _.code="MODULE_NOT_FOUND",_}var R=l[p]={exports:{}};d[p][0].call(R.exports,function(k){var I=d[p][1][k];return f(I||k)},R,R.exports,a,d,l,c)}return l[p].exports}for(var b=typeof Us=="function"&&Us,u=0;u<c.length;u++)f(c[u]);return f}return a})()({1:[function(a,d,l){function c(j){var v=j.length;if(0<v%4)throw new Error("Invalid string. Length must be a multiple of 4");var A=j.indexOf("=");A===-1&&(A=v);var E=A===v?0:4-A%4;return[A,E]}function f(j,v,A){return 3*(v+A)/4-A}function b(j){var v,A,E=c(j),N=E[0],D=E[1],S=new R(f(j,N,D)),T=0,P=0<D?N-4:N;for(A=0;A<P;A+=4)v=_[j.charCodeAt(A)]<<18|_[j.charCodeAt(A+1)]<<12|_[j.charCodeAt(A+2)]<<6|_[j.charCodeAt(A+3)],S[T++]=255&v>>16,S[T++]=255&v>>8,S[T++]=255&v;return D===2&&(v=_[j.charCodeAt(A)]<<2|_[j.charCodeAt(A+1)]>>4,S[T++]=255&v),D===1&&(v=_[j.charCodeAt(A)]<<10|_[j.charCodeAt(A+1)]<<4|_[j.charCodeAt(A+2)]>>2,S[T++]=255&v>>8,S[T++]=255&v),S}function u(j){return y[63&j>>18]+y[63&j>>12]+y[63&j>>6]+y[63&j]}function p(j,v,A){for(var E,N=[],D=v;D<A;D+=3)E=(16711680&j[D]<<16)+(65280&j[D+1]<<8)+(255&j[D+2]),N.push(u(E));return N.join("")}function m(j){for(var v,A=j.length,E=A%3,N=[],D=16383,S=0,T=A-E;S<T;S+=D)N.push(p(j,S,S+D>T?T:S+D));return E===1?(v=j[A-1],N.push(y[v>>2]+y[63&v<<4]+"==")):E===2&&(v=(j[A-2]<<8)+j[A-1],N.push(y[v>>10]+y[63&v>>4]+y[63&v<<2]+"=")),N.join("")}l.byteLength=function(j){var v=c(j),A=v[0],E=v[1];return 3*(A+E)/4-E},l.toByteArray=b,l.fromByteArray=m;for(var y=[],_=[],R=typeof Uint8Array>"u"?Array:Uint8Array,k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",I=0,g=k.length;I<g;++I)y[I]=k[I],_[k.charCodeAt(I)]=I;_[45]=62,_[95]=63},{}],2:[function(){},{}],3:[function(a,d,l){(function(){(function(){var c=String.fromCharCode,f=Math.min;function b(o){if(2147483647<o)throw new RangeError('The value "'+o+'" is invalid for option "size"');var h=new Uint8Array(o);return h.__proto__=u.prototype,h}function u(o,h,x){if(typeof o=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return _(o)}return p(o,h,x)}function p(o,h,x){if(typeof o=="string")return R(o,h);if(ArrayBuffer.isView(o))return k(o);if(o==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof o);if(O(o,ArrayBuffer)||o&&O(o.buffer,ArrayBuffer))return I(o,h,x);if(typeof o=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var L=o.valueOf&&o.valueOf();if(L!=null&&L!==o)return u.from(L,h,x);var W=g(o);if(W)return W;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof o[Symbol.toPrimitive]=="function")return u.from(o[Symbol.toPrimitive]("string"),h,x);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof o)}function m(o){if(typeof o!="number")throw new TypeError('"size" argument must be of type number');if(0>o)throw new RangeError('The value "'+o+'" is invalid for option "size"')}function y(o,h,x){return m(o),0>=o||h===void 0?b(o):typeof x=="string"?b(o).fill(h,x):b(o).fill(h)}function _(o){return m(o),b(0>o?0:0|j(o))}function R(o,h){if((typeof h!="string"||h==="")&&(h="utf8"),!u.isEncoding(h))throw new TypeError("Unknown encoding: "+h);var x=0|v(o,h),L=b(x),W=L.write(o,h);return W!==x&&(L=L.slice(0,W)),L}function k(o){for(var h=0>o.length?0:0|j(o.length),x=b(h),L=0;L<h;L+=1)x[L]=255&o[L];return x}function I(o,h,x){if(0>h||o.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(o.byteLength<h+(x||0))throw new RangeError('"length" is outside of buffer bounds');var L;return L=h===void 0&&x===void 0?new Uint8Array(o):x===void 0?new Uint8Array(o,h):new Uint8Array(o,h,x),L.__proto__=u.prototype,L}function g(o){if(u.isBuffer(o)){var h=0|j(o.length),x=b(h);return x.length===0||o.copy(x,0,0,h),x}return o.length===void 0?o.type==="Buffer"&&Array.isArray(o.data)?k(o.data):void 0:typeof o.length!="number"||U(o.length)?b(0):k(o)}function j(o){if(o>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|o}function v(o,h){if(u.isBuffer(o))return o.length;if(ArrayBuffer.isView(o)||O(o,ArrayBuffer))return o.byteLength;if(typeof o!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof o);var x=o.length,L=2<arguments.length&&arguments[2]===!0;if(!L&&x===0)return 0;for(var W=!1;;)switch(h){case"ascii":case"latin1":case"binary":return x;case"utf8":case"utf-8":return be(o).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*x;case"hex":return x>>>1;case"base64":return K(o).length;default:if(W)return L?-1:be(o).length;h=(""+h).toLowerCase(),W=!0}}function A(o,h,x){var L=!1;if((h===void 0||0>h)&&(h=0),h>this.length||((x===void 0||x>this.length)&&(x=this.length),0>=x)||(x>>>=0,h>>>=0,x<=h))return"";for(o||(o="utf8");;)switch(o){case"hex":return he(this,h,x);case"utf8":case"utf-8":return q(this,h,x);case"ascii":return Z(this,h,x);case"latin1":case"binary":return ge(this,h,x);case"base64":return Y(this,h,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return se(this,h,x);default:if(L)throw new TypeError("Unknown encoding: "+o);o=(o+"").toLowerCase(),L=!0}}function E(o,h,x){var L=o[h];o[h]=o[x],o[x]=L}function N(o,h,x,L,W){if(o.length===0)return-1;if(typeof x=="string"?(L=x,x=0):2147483647<x?x=2147483647:-2147483648>x&&(x=-2147483648),x=+x,U(x)&&(x=W?0:o.length-1),0>x&&(x=o.length+x),x>=o.length){if(W)return-1;x=o.length-1}else if(0>x)if(W)x=0;else return-1;if(typeof h=="string"&&(h=u.from(h,L)),u.isBuffer(h))return h.length===0?-1:D(o,h,x,L,W);if(typeof h=="number")return h&=255,typeof Uint8Array.prototype.indexOf=="function"?W?Uint8Array.prototype.indexOf.call(o,h,x):Uint8Array.prototype.lastIndexOf.call(o,h,x):D(o,[h],x,L,W);throw new TypeError("val must be string, number or Buffer")}function D(o,h,x,L,W){function B(Ot,ls){return te===1?Ot[ls]:Ot.readUInt16BE(ls*te)}var te=1,fe=o.length,_e=h.length;if(L!==void 0&&(L=(L+"").toLowerCase(),L==="ucs2"||L==="ucs-2"||L==="utf16le"||L==="utf-16le")){if(2>o.length||2>h.length)return-1;te=2,fe/=2,_e/=2,x/=2}var pe;if(W){var ce=-1;for(pe=x;pe<fe;pe++)if(B(o,pe)!==B(h,ce===-1?0:pe-ce))ce!==-1&&(pe-=pe-ce),ce=-1;else if(ce===-1&&(ce=pe),pe-ce+1===_e)return ce*te}else for(x+_e>fe&&(x=fe-_e),pe=x;0<=pe;pe--){for(var Oe=!0,_t=0;_t<_e;_t++)if(B(o,pe+_t)!==B(h,_t)){Oe=!1;break}if(Oe)return pe}return-1}function S(o,h,x,L){x=+x||0;var W=o.length-x;L?(L=+L,L>W&&(L=W)):L=W;var B=h.length;L>B/2&&(L=B/2);for(var te,fe=0;fe<L;++fe){if(te=parseInt(h.substr(2*fe,2),16),U(te))return fe;o[x+fe]=te}return fe}function T(o,h,x,L){return X(be(h,o.length-x),o,x,L)}function P(o,h,x,L){return X(Ee(h),o,x,L)}function M(o,h,x,L){return P(o,h,x,L)}function F(o,h,x,L){return X(K(h),o,x,L)}function V(o,h,x,L){return X(H(h,o.length-x),o,x,L)}function Y(o,h,x){return h===0&&x===o.length?z.fromByteArray(o):z.fromByteArray(o.slice(h,x))}function q(o,h,x){x=f(o.length,x);for(var L=[],W=h;W<x;){var B=o[W],te=null,fe=239<B?4:223<B?3:191<B?2:1;if(W+fe<=x){var _e,pe,ce,Oe;fe===1?128>B&&(te=B):fe===2?(_e=o[W+1],(192&_e)==128&&(Oe=(31&B)<<6|63&_e,127<Oe&&(te=Oe))):fe===3?(_e=o[W+1],pe=o[W+2],(192&_e)==128&&(192&pe)==128&&(Oe=(15&B)<<12|(63&_e)<<6|63&pe,2047<Oe&&(55296>Oe||57343<Oe)&&(te=Oe))):fe===4&&(_e=o[W+1],pe=o[W+2],ce=o[W+3],(192&_e)==128&&(192&pe)==128&&(192&ce)==128&&(Oe=(15&B)<<18|(63&_e)<<12|(63&pe)<<6|63&ce,65535<Oe&&1114112>Oe&&(te=Oe)))}te===null?(te=65533,fe=1):65535<te&&(te-=65536,L.push(55296|1023&te>>>10),te=56320|1023&te),L.push(te),W+=fe}return ye(L)}function ye(o){var h=o.length;if(h<=4096)return c.apply(String,o);for(var x="",L=0;L<h;)x+=c.apply(String,o.slice(L,L+=4096));return x}function Z(o,h,x){var L="";x=f(o.length,x);for(var W=h;W<x;++W)L+=c(127&o[W]);return L}function ge(o,h,x){var L="";x=f(o.length,x);for(var W=h;W<x;++W)L+=c(o[W]);return L}function he(o,h,x){var L=o.length;(!h||0>h)&&(h=0),(!x||0>x||x>L)&&(x=L);for(var W="",B=h;B<x;++B)W+=le(o[B]);return W}function se(o,h,x){for(var L=o.slice(h,x),W="",B=0;B<L.length;B+=2)W+=c(L[B]+256*L[B+1]);return W}function ie(o,h,x){if(o%1!=0||0>o)throw new RangeError("offset is not uint");if(o+h>x)throw new RangeError("Trying to access beyond buffer length")}function Q(o,h,x,L,W,B){if(!u.isBuffer(o))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>W||h<B)throw new RangeError('"value" argument is out of bounds');if(x+L>o.length)throw new RangeError("Index out of range")}function xe(o,h,x,L){if(x+L>o.length)throw new RangeError("Index out of range");if(0>x)throw new RangeError("Index out of range")}function $(o,h,x,L,W){return h=+h,x>>>=0,W||xe(o,h,x,4),ee.write(o,h,x,L,23,4),x+4}function G(o,h,x,L,W){return h=+h,x>>>=0,W||xe(o,h,x,8),ee.write(o,h,x,L,52,8),x+8}function J(o){if(o=o.split("=")[0],o=o.trim().replace(C,""),2>o.length)return"";for(;o.length%4!=0;)o+="=";return o}function le(o){return 16>o?"0"+o.toString(16):o.toString(16)}function be(o,h){h=h||1/0;for(var x,L=o.length,W=null,B=[],te=0;te<L;++te){if(x=o.charCodeAt(te),55295<x&&57344>x){if(!W){if(56319<x){-1<(h-=3)&&B.push(239,191,189);continue}else if(te+1===L){-1<(h-=3)&&B.push(239,191,189);continue}W=x;continue}if(56320>x){-1<(h-=3)&&B.push(239,191,189),W=x;continue}x=(W-55296<<10|x-56320)+65536}else W&&-1<(h-=3)&&B.push(239,191,189);if(W=null,128>x){if(0>(h-=1))break;B.push(x)}else if(2048>x){if(0>(h-=2))break;B.push(192|x>>6,128|63&x)}else if(65536>x){if(0>(h-=3))break;B.push(224|x>>12,128|63&x>>6,128|63&x)}else if(1114112>x){if(0>(h-=4))break;B.push(240|x>>18,128|63&x>>12,128|63&x>>6,128|63&x)}else throw new Error("Invalid code point")}return B}function Ee(o){for(var h=[],x=0;x<o.length;++x)h.push(255&o.charCodeAt(x));return h}function H(o,h){for(var x,L,W,B=[],te=0;te<o.length&&!(0>(h-=2));++te)x=o.charCodeAt(te),L=x>>8,W=x%256,B.push(W),B.push(L);return B}function K(o){return z.toByteArray(J(o))}function X(o,h,x,L){for(var W=0;W<L&&!(W+x>=h.length||W>=o.length);++W)h[W+x]=o[W];return W}function O(o,h){return o instanceof h||o!=null&&o.constructor!=null&&o.constructor.name!=null&&o.constructor.name===h.name}function U(o){return o!==o}var z=a("base64-js"),ee=a("ieee754");l.Buffer=u,l.SlowBuffer=function(o){return+o!=o&&(o=0),u.alloc(+o)},l.INSPECT_MAX_BYTES=50,l.kMaxLength=2147483647,u.TYPED_ARRAY_SUPPORT=(function(){try{var o=new Uint8Array(1);return o.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},o.foo()===42}catch{return!1}})(),u.TYPED_ARRAY_SUPPORT||typeof console>"u"||typeof console.error!="function"||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){return u.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){return u.isBuffer(this)?this.byteOffset:void 0}}),typeof Symbol<"u"&&Symbol.species!=null&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),u.poolSize=8192,u.from=function(o,h,x){return p(o,h,x)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(o,h,x){return y(o,h,x)},u.allocUnsafe=function(o){return _(o)},u.allocUnsafeSlow=function(o){return _(o)},u.isBuffer=function(o){return o!=null&&o._isBuffer===!0&&o!==u.prototype},u.compare=function(o,h){if(O(o,Uint8Array)&&(o=u.from(o,o.offset,o.byteLength)),O(h,Uint8Array)&&(h=u.from(h,h.offset,h.byteLength)),!u.isBuffer(o)||!u.isBuffer(h))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(o===h)return 0;for(var x=o.length,L=h.length,W=0,B=f(x,L);W<B;++W)if(o[W]!==h[W]){x=o[W],L=h[W];break}return x<L?-1:L<x?1:0},u.isEncoding=function(o){switch((o+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(o,h){if(!Array.isArray(o))throw new TypeError('"list" argument must be an Array of Buffers');if(o.length===0)return u.alloc(0);var x;if(h===void 0)for(h=0,x=0;x<o.length;++x)h+=o[x].length;var L=u.allocUnsafe(h),W=0;for(x=0;x<o.length;++x){var B=o[x];if(O(B,Uint8Array)&&(B=u.from(B)),!u.isBuffer(B))throw new TypeError('"list" argument must be an Array of Buffers');B.copy(L,W),W+=B.length}return L},u.byteLength=v,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var o=this.length;if(o%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var h=0;h<o;h+=2)E(this,h,h+1);return this},u.prototype.swap32=function(){var o=this.length;if(o%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var h=0;h<o;h+=4)E(this,h,h+3),E(this,h+1,h+2);return this},u.prototype.swap64=function(){var o=this.length;if(o%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var h=0;h<o;h+=8)E(this,h,h+7),E(this,h+1,h+6),E(this,h+2,h+5),E(this,h+3,h+4);return this},u.prototype.toString=function(){var o=this.length;return o===0?"":arguments.length===0?q(this,0,o):A.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(o){if(!u.isBuffer(o))throw new TypeError("Argument must be a Buffer");return this===o||u.compare(this,o)===0},u.prototype.inspect=function(){var o="",h=l.INSPECT_MAX_BYTES;return o=this.toString("hex",0,h).replace(/(.{2})/g,"$1 ").trim(),this.length>h&&(o+=" ... "),"<Buffer "+o+">"},u.prototype.compare=function(o,h,x,L,W){if(O(o,Uint8Array)&&(o=u.from(o,o.offset,o.byteLength)),!u.isBuffer(o))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof o);if(h===void 0&&(h=0),x===void 0&&(x=o?o.length:0),L===void 0&&(L=0),W===void 0&&(W=this.length),0>h||x>o.length||0>L||W>this.length)throw new RangeError("out of range index");if(L>=W&&h>=x)return 0;if(L>=W)return-1;if(h>=x)return 1;if(h>>>=0,x>>>=0,L>>>=0,W>>>=0,this===o)return 0;for(var B=W-L,te=x-h,fe=f(B,te),_e=this.slice(L,W),pe=o.slice(h,x),ce=0;ce<fe;++ce)if(_e[ce]!==pe[ce]){B=_e[ce],te=pe[ce];break}return B<te?-1:te<B?1:0},u.prototype.includes=function(o,h,x){return this.indexOf(o,h,x)!==-1},u.prototype.indexOf=function(o,h,x){return N(this,o,h,x,!0)},u.prototype.lastIndexOf=function(o,h,x){return N(this,o,h,x,!1)},u.prototype.write=function(o,h,x,L){if(h===void 0)L="utf8",x=this.length,h=0;else if(x===void 0&&typeof h=="string")L=h,x=this.length,h=0;else if(isFinite(h))h>>>=0,isFinite(x)?(x>>>=0,L===void 0&&(L="utf8")):(L=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var W=this.length-h;if((x===void 0||x>W)&&(x=W),0<o.length&&(0>x||0>h)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");L||(L="utf8");for(var B=!1;;)switch(L){case"hex":return S(this,o,h,x);case"utf8":case"utf-8":return T(this,o,h,x);case"ascii":return P(this,o,h,x);case"latin1":case"binary":return M(this,o,h,x);case"base64":return F(this,o,h,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return V(this,o,h,x);default:if(B)throw new TypeError("Unknown encoding: "+L);L=(""+L).toLowerCase(),B=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},u.prototype.slice=function(o,h){var x=this.length;o=~~o,h=h===void 0?x:~~h,0>o?(o+=x,0>o&&(o=0)):o>x&&(o=x),0>h?(h+=x,0>h&&(h=0)):h>x&&(h=x),h<o&&(h=o);var L=this.subarray(o,h);return L.__proto__=u.prototype,L},u.prototype.readUIntLE=function(o,h,x){o>>>=0,h>>>=0,x||ie(o,h,this.length);for(var L=this[o],W=1,B=0;++B<h&&(W*=256);)L+=this[o+B]*W;return L},u.prototype.readUIntBE=function(o,h,x){o>>>=0,h>>>=0,x||ie(o,h,this.length);for(var L=this[o+--h],W=1;0<h&&(W*=256);)L+=this[o+--h]*W;return L},u.prototype.readUInt8=function(o,h){return o>>>=0,h||ie(o,1,this.length),this[o]},u.prototype.readUInt16LE=function(o,h){return o>>>=0,h||ie(o,2,this.length),this[o]|this[o+1]<<8},u.prototype.readUInt16BE=function(o,h){return o>>>=0,h||ie(o,2,this.length),this[o]<<8|this[o+1]},u.prototype.readUInt32LE=function(o,h){return o>>>=0,h||ie(o,4,this.length),(this[o]|this[o+1]<<8|this[o+2]<<16)+16777216*this[o+3]},u.prototype.readUInt32BE=function(o,h){return o>>>=0,h||ie(o,4,this.length),16777216*this[o]+(this[o+1]<<16|this[o+2]<<8|this[o+3])},u.prototype.readIntLE=function(o,h,x){o>>>=0,h>>>=0,x||ie(o,h,this.length);for(var L=this[o],W=1,B=0;++B<h&&(W*=256);)L+=this[o+B]*W;return W*=128,L>=W&&(L-=i(2,8*h)),L},u.prototype.readIntBE=function(o,h,x){o>>>=0,h>>>=0,x||ie(o,h,this.length);for(var L=h,W=1,B=this[o+--L];0<L&&(W*=256);)B+=this[o+--L]*W;return W*=128,B>=W&&(B-=i(2,8*h)),B},u.prototype.readInt8=function(o,h){return o>>>=0,h||ie(o,1,this.length),128&this[o]?-1*(255-this[o]+1):this[o]},u.prototype.readInt16LE=function(o,h){o>>>=0,h||ie(o,2,this.length);var x=this[o]|this[o+1]<<8;return 32768&x?4294901760|x:x},u.prototype.readInt16BE=function(o,h){o>>>=0,h||ie(o,2,this.length);var x=this[o+1]|this[o]<<8;return 32768&x?4294901760|x:x},u.prototype.readInt32LE=function(o,h){return o>>>=0,h||ie(o,4,this.length),this[o]|this[o+1]<<8|this[o+2]<<16|this[o+3]<<24},u.prototype.readInt32BE=function(o,h){return o>>>=0,h||ie(o,4,this.length),this[o]<<24|this[o+1]<<16|this[o+2]<<8|this[o+3]},u.prototype.readFloatLE=function(o,h){return o>>>=0,h||ie(o,4,this.length),ee.read(this,o,!0,23,4)},u.prototype.readFloatBE=function(o,h){return o>>>=0,h||ie(o,4,this.length),ee.read(this,o,!1,23,4)},u.prototype.readDoubleLE=function(o,h){return o>>>=0,h||ie(o,8,this.length),ee.read(this,o,!0,52,8)},u.prototype.readDoubleBE=function(o,h){return o>>>=0,h||ie(o,8,this.length),ee.read(this,o,!1,52,8)},u.prototype.writeUIntLE=function(o,h,x,L){if(o=+o,h>>>=0,x>>>=0,!L){var W=i(2,8*x)-1;Q(this,o,h,x,W,0)}var B=1,te=0;for(this[h]=255&o;++te<x&&(B*=256);)this[h+te]=255&o/B;return h+x},u.prototype.writeUIntBE=function(o,h,x,L){if(o=+o,h>>>=0,x>>>=0,!L){var W=i(2,8*x)-1;Q(this,o,h,x,W,0)}var B=x-1,te=1;for(this[h+B]=255&o;0<=--B&&(te*=256);)this[h+B]=255&o/te;return h+x},u.prototype.writeUInt8=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,1,255,0),this[h]=255&o,h+1},u.prototype.writeUInt16LE=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,2,65535,0),this[h]=255&o,this[h+1]=o>>>8,h+2},u.prototype.writeUInt16BE=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,2,65535,0),this[h]=o>>>8,this[h+1]=255&o,h+2},u.prototype.writeUInt32LE=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,4,4294967295,0),this[h+3]=o>>>24,this[h+2]=o>>>16,this[h+1]=o>>>8,this[h]=255&o,h+4},u.prototype.writeUInt32BE=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,4,4294967295,0),this[h]=o>>>24,this[h+1]=o>>>16,this[h+2]=o>>>8,this[h+3]=255&o,h+4},u.prototype.writeIntLE=function(o,h,x,L){if(o=+o,h>>>=0,!L){var W=i(2,8*x-1);Q(this,o,h,x,W-1,-W)}var B=0,te=1,fe=0;for(this[h]=255&o;++B<x&&(te*=256);)0>o&&fe===0&&this[h+B-1]!==0&&(fe=1),this[h+B]=255&(o/te>>0)-fe;return h+x},u.prototype.writeIntBE=function(o,h,x,L){if(o=+o,h>>>=0,!L){var W=i(2,8*x-1);Q(this,o,h,x,W-1,-W)}var B=x-1,te=1,fe=0;for(this[h+B]=255&o;0<=--B&&(te*=256);)0>o&&fe===0&&this[h+B+1]!==0&&(fe=1),this[h+B]=255&(o/te>>0)-fe;return h+x},u.prototype.writeInt8=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,1,127,-128),0>o&&(o=255+o+1),this[h]=255&o,h+1},u.prototype.writeInt16LE=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,2,32767,-32768),this[h]=255&o,this[h+1]=o>>>8,h+2},u.prototype.writeInt16BE=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,2,32767,-32768),this[h]=o>>>8,this[h+1]=255&o,h+2},u.prototype.writeInt32LE=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,4,2147483647,-2147483648),this[h]=255&o,this[h+1]=o>>>8,this[h+2]=o>>>16,this[h+3]=o>>>24,h+4},u.prototype.writeInt32BE=function(o,h,x){return o=+o,h>>>=0,x||Q(this,o,h,4,2147483647,-2147483648),0>o&&(o=4294967295+o+1),this[h]=o>>>24,this[h+1]=o>>>16,this[h+2]=o>>>8,this[h+3]=255&o,h+4},u.prototype.writeFloatLE=function(o,h,x){return $(this,o,h,!0,x)},u.prototype.writeFloatBE=function(o,h,x){return $(this,o,h,!1,x)},u.prototype.writeDoubleLE=function(o,h,x){return G(this,o,h,!0,x)},u.prototype.writeDoubleBE=function(o,h,x){return G(this,o,h,!1,x)},u.prototype.copy=function(o,h,x,L){if(!u.isBuffer(o))throw new TypeError("argument should be a Buffer");if(x||(x=0),L||L===0||(L=this.length),h>=o.length&&(h=o.length),h||(h=0),0<L&&L<x&&(L=x),L===x||o.length===0||this.length===0)return 0;if(0>h)throw new RangeError("targetStart out of bounds");if(0>x||x>=this.length)throw new RangeError("Index out of range");if(0>L)throw new RangeError("sourceEnd out of bounds");L>this.length&&(L=this.length),o.length-h<L-x&&(L=o.length-h+x);var W=L-x;if(this===o&&typeof Uint8Array.prototype.copyWithin=="function")this.copyWithin(h,x,L);else if(this===o&&x<h&&h<L)for(var B=W-1;0<=B;--B)o[B+h]=this[B+x];else Uint8Array.prototype.set.call(o,this.subarray(x,L),h);return W},u.prototype.fill=function(o,h,x,L){if(typeof o=="string"){if(typeof h=="string"?(L=h,h=0,x=this.length):typeof x=="string"&&(L=x,x=this.length),L!==void 0&&typeof L!="string")throw new TypeError("encoding must be a string");if(typeof L=="string"&&!u.isEncoding(L))throw new TypeError("Unknown encoding: "+L);if(o.length===1){var W=o.charCodeAt(0);(L==="utf8"&&128>W||L==="latin1")&&(o=W)}}else typeof o=="number"&&(o&=255);if(0>h||this.length<h||this.length<x)throw new RangeError("Out of range index");if(x<=h)return this;h>>>=0,x=x===void 0?this.length:x>>>0,o||(o=0);var B;if(typeof o=="number")for(B=h;B<x;++B)this[B]=o;else{var te=u.isBuffer(o)?o:u.from(o,L),fe=te.length;if(fe===0)throw new TypeError('The value "'+o+'" is invalid for argument "value"');for(B=0;B<x-h;++B)this[B+h]=te[B%fe]}return this};var C=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,a("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(a,d,l){(function(c){(function(){function f(){let u;try{u=l.storage.getItem("debug")}catch{}return!u&&typeof c<"u"&&"env"in c&&(u=c.env.DEBUG),u}l.formatArgs=function(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+d.exports.humanize(this.diff),!this.useColors)return;const p="color: "+this.color;u.splice(1,0,p,"color: inherit");let m=0,y=0;u[0].replace(/%[a-zA-Z%]/g,_=>{_==="%%"||(m++,_==="%c"&&(y=m))}),u.splice(y,0,p)},l.save=function(u){try{u?l.storage.setItem("debug",u):l.storage.removeItem("debug")}catch{}},l.load=f,l.useColors=function(){return!!(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))||!(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},l.storage=(function(){try{return localStorage}catch{}})(),l.destroy=(()=>{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),l.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],l.log=console.debug||console.log||(()=>{}),d.exports=a("./common")(l);const{formatters:b}=d.exports;b.j=function(u){try{return JSON.stringify(u)}catch(p){return"[UnexpectedJSONParseError]: "+p.message}}}).call(this)}).call(this,a("_process"))},{"./common":5,_process:12}],5:[function(a,d){d.exports=function(l){function c(u){function p(..._){if(!p.enabled)return;const R=p,k=+new Date,I=k-(m||k);R.diff=I,R.prev=m,R.curr=k,m=k,_[0]=c.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let g=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(v,A)=>{if(v==="%%")return"%";g++;const E=c.formatters[A];if(typeof E=="function"){const N=_[g];v=E.call(R,N),_.splice(g,1),g--}return v}),c.formatArgs.call(R,_),(R.log||c.log).apply(R,_)}let m,y=null;return p.namespace=u,p.useColors=c.useColors(),p.color=c.selectColor(u),p.extend=f,p.destroy=c.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>y===null?c.enabled(u):y,set:_=>{y=_}}),typeof c.init=="function"&&c.init(p),p}function f(u,p){const m=c(this.namespace+(typeof p>"u"?":":p)+u);return m.log=this.log,m}function b(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}return c.debug=c,c.default=c,c.coerce=function(u){return u instanceof Error?u.stack||u.message:u},c.disable=function(){const u=[...c.names.map(b),...c.skips.map(b).map(p=>"-"+p)].join(",");return c.enable(""),u},c.enable=function(u){c.save(u),c.names=[],c.skips=[];let p;const m=(typeof u=="string"?u:"").split(/[\s,]+/),y=m.length;for(p=0;p<y;p++)m[p]&&(u=m[p].replace(/\*/g,".*?"),u[0]==="-"?c.skips.push(new RegExp("^"+u.substr(1)+"$")):c.names.push(new RegExp("^"+u+"$")))},c.enabled=function(u){if(u[u.length-1]==="*")return!0;let p,m;for(p=0,m=c.skips.length;p<m;p++)if(c.skips[p].test(u))return!1;for(p=0,m=c.names.length;p<m;p++)if(c.names[p].test(u))return!0;return!1},c.humanize=a("ms"),c.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(l).forEach(u=>{c[u]=l[u]}),c.names=[],c.skips=[],c.formatters={},c.selectColor=function(u){let p=0;for(let m=0;m<u.length;m++)p=(p<<5)-p+u.charCodeAt(m),p|=0;return c.colors[r(p)%c.colors.length]},c.enable(c.load()),c}},{ms:11}],6:[function(a,d){function l(c,f){for(const b in f)Object.defineProperty(c,b,{value:f[b],enumerable:!0,configurable:!0});return c}d.exports=function(c,f,b){if(!c||typeof c=="string")throw new TypeError("Please pass an Error to err-code");b||(b={}),typeof f=="object"&&(b=f,f=""),f&&(b.code=f);try{return l(c,b)}catch{b.message=c.message,b.stack=c.stack;const p=function(){};return p.prototype=Object.create(Object.getPrototypeOf(c)),l(new p,b)}}},{}],7:[function(a,d){function l(S){console&&console.warn&&console.warn(S)}function c(){c.init.call(this)}function f(S){if(typeof S!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof S)}function b(S){return S._maxListeners===void 0?c.defaultMaxListeners:S._maxListeners}function u(S,T,P,M){var F,V,Y;if(f(P),V=S._events,V===void 0?(V=S._events=Object.create(null),S._eventsCount=0):(V.newListener!==void 0&&(S.emit("newListener",T,P.listener?P.listener:P),V=S._events),Y=V[T]),Y===void 0)Y=V[T]=P,++S._eventsCount;else if(typeof Y=="function"?Y=V[T]=M?[P,Y]:[Y,P]:M?Y.unshift(P):Y.push(P),F=b(S),0<F&&Y.length>F&&!Y.warned){Y.warned=!0;var q=new Error("Possible EventEmitter memory leak detected. "+Y.length+" "+(T+" listeners added. Use emitter.setMaxListeners() to increase limit"));q.name="MaxListenersExceededWarning",q.emitter=S,q.type=T,q.count=Y.length,l(q)}return S}function p(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function m(S,T,P){var M={fired:!1,wrapFn:void 0,target:S,type:T,listener:P},F=p.bind(M);return F.listener=P,M.wrapFn=F,F}function y(S,T,P){var M=S._events;if(M===void 0)return[];var F=M[T];return F===void 0?[]:typeof F=="function"?P?[F.listener||F]:[F]:P?I(F):R(F,F.length)}function _(S){var T=this._events;if(T!==void 0){var P=T[S];if(typeof P=="function")return 1;if(P!==void 0)return P.length}return 0}function R(S,T){for(var P=Array(T),M=0;M<T;++M)P[M]=S[M];return P}function k(S,T){for(;T+1<S.length;T++)S[T]=S[T+1];S.pop()}function I(S){for(var T=Array(S.length),P=0;P<T.length;++P)T[P]=S[P].listener||S[P];return T}function g(S,T,P){typeof S.on=="function"&&j(S,"error",T,P)}function j(S,T,P,M){if(typeof S.on=="function")M.once?S.once(T,P):S.on(T,P);else if(typeof S.addEventListener=="function")S.addEventListener(T,function F(V){M.once&&S.removeEventListener(T,F),P(V)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}var v,A=typeof Reflect=="object"?Reflect:null,E=A&&typeof A.apply=="function"?A.apply:function(S,T,P){return Function.prototype.apply.call(S,T,P)};v=A&&typeof A.ownKeys=="function"?A.ownKeys:Object.getOwnPropertySymbols?function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:function(S){return Object.getOwnPropertyNames(S)};var N=Number.isNaN||function(S){return S!==S};d.exports=c,d.exports.once=function(S,T){return new Promise(function(P,M){function F(Y){S.removeListener(T,V),M(Y)}function V(){typeof S.removeListener=="function"&&S.removeListener("error",F),P([].slice.call(arguments))}j(S,T,V,{once:!0}),T!=="error"&&g(S,F,{once:!0})})},c.EventEmitter=c,c.prototype._events=void 0,c.prototype._eventsCount=0,c.prototype._maxListeners=void 0;var D=10;Object.defineProperty(c,"defaultMaxListeners",{enumerable:!0,get:function(){return D},set:function(S){if(typeof S!="number"||0>S||N(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");D=S}}),c.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},c.prototype.setMaxListeners=function(S){if(typeof S!="number"||0>S||N(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this},c.prototype.getMaxListeners=function(){return b(this)},c.prototype.emit=function(S){for(var T=[],P=1;P<arguments.length;P++)T.push(arguments[P]);var M=S==="error",F=this._events;if(F!==void 0)M=M&&F.error===void 0;else if(!M)return!1;if(M){var V;if(0<T.length&&(V=T[0]),V instanceof Error)throw V;var Y=new Error("Unhandled error."+(V?" ("+V.message+")":""));throw Y.context=V,Y}var q=F[S];if(q===void 0)return!1;if(typeof q=="function")E(q,this,T);else for(var ye=q.length,Z=R(q,ye),P=0;P<ye;++P)E(Z[P],this,T);return!0},c.prototype.addListener=function(S,T){return u(this,S,T,!1)},c.prototype.on=c.prototype.addListener,c.prototype.prependListener=function(S,T){return u(this,S,T,!0)},c.prototype.once=function(S,T){return f(T),this.on(S,m(this,S,T)),this},c.prototype.prependOnceListener=function(S,T){return f(T),this.prependListener(S,m(this,S,T)),this},c.prototype.removeListener=function(S,T){var P,M,F,V,Y;if(f(T),M=this._events,M===void 0)return this;if(P=M[S],P===void 0)return this;if(P===T||P.listener===T)--this._eventsCount==0?this._events=Object.create(null):(delete M[S],M.removeListener&&this.emit("removeListener",S,P.listener||T));else if(typeof P!="function"){for(F=-1,V=P.length-1;0<=V;V--)if(P[V]===T||P[V].listener===T){Y=P[V].listener,F=V;break}if(0>F)return this;F===0?P.shift():k(P,F),P.length===1&&(M[S]=P[0]),M.removeListener!==void 0&&this.emit("removeListener",S,Y||T)}return this},c.prototype.off=c.prototype.removeListener,c.prototype.removeAllListeners=function(S){var T,P,M;if(P=this._events,P===void 0)return this;if(P.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):P[S]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete P[S]),this;if(arguments.length===0){var F,V=Object.keys(P);for(M=0;M<V.length;++M)F=V[M],F!=="removeListener"&&this.removeAllListeners(F);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(T=P[S],typeof T=="function")this.removeListener(S,T);else if(T!==void 0)for(M=T.length-1;0<=M;M--)this.removeListener(S,T[M]);return this},c.prototype.listeners=function(S){return y(this,S,!0)},c.prototype.rawListeners=function(S){return y(this,S,!1)},c.listenerCount=function(S,T){return typeof S.listenerCount=="function"?S.listenerCount(T):_.call(S,T)},c.prototype.listenerCount=_,c.prototype.eventNames=function(){return 0<this._eventsCount?v(this._events):[]}},{}],8:[function(a,d){d.exports=function(){if(typeof globalThis>"u")return null;var l={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return l.RTCPeerConnection?l:null}},{}],9:[function(a,d,l){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */l.read=function(c,f,b,u,p){var m,y,_=8*p-u-1,R=(1<<_)-1,k=R>>1,I=-7,g=b?p-1:0,j=b?-1:1,v=c[f+g];for(g+=j,m=v&(1<<-I)-1,v>>=-I,I+=_;0<I;m=256*m+c[f+g],g+=j,I-=8);for(y=m&(1<<-I)-1,m>>=-I,I+=u;0<I;y=256*y+c[f+g],g+=j,I-=8);if(m===0)m=1-k;else{if(m===R)return y?NaN:(v?-1:1)*(1/0);y+=i(2,u),m-=k}return(v?-1:1)*y*i(2,m-u)},l.write=function(c,f,b,u,p,m){var y,_,R,k=Math.LN2,I=Math.log,g=8*m-p-1,j=(1<<g)-1,v=j>>1,A=p===23?i(2,-24)-i(2,-77):0,E=u?0:m-1,N=u?1:-1,D=0>f||f===0&&0>1/f?1:0;for(f=r(f),isNaN(f)||f===1/0?(_=isNaN(f)?1:0,y=j):(y=s(I(f)/k),1>f*(R=i(2,-y))&&(y--,R*=2),f+=1<=y+v?A/R:A*i(2,1-v),2<=f*R&&(y++,R/=2),y+v>=j?(_=0,y=j):1<=y+v?(_=(f*R-1)*i(2,p),y+=v):(_=f*i(2,v-1)*i(2,p),y=0));8<=p;c[b+E]=255&_,E+=N,_/=256,p-=8);for(y=y<<p|_,g+=p;0<g;c[b+E]=255&y,E+=N,y/=256,g-=8);c[b+E-N]|=128*D}},{}],10:[function(a,d){d.exports=typeof Object.create=="function"?function(l,c){c&&(l.super_=c,l.prototype=Object.create(c.prototype,{constructor:{value:l,enumerable:!1,writable:!0,configurable:!0}}))}:function(l,c){if(c){l.super_=c;var f=function(){};f.prototype=c.prototype,l.prototype=new f,l.prototype.constructor=l}}},{}],11:[function(a,d){var l=Math.round;function c(p){if(p+="",!(100<p.length)){var m=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(p);if(m){var y=parseFloat(m[1]),_=(m[2]||"ms").toLowerCase();return _==="years"||_==="year"||_==="yrs"||_==="yr"||_==="y"?315576e5*y:_==="weeks"||_==="week"||_==="w"?6048e5*y:_==="days"||_==="day"||_==="d"?864e5*y:_==="hours"||_==="hour"||_==="hrs"||_==="hr"||_==="h"?36e5*y:_==="minutes"||_==="minute"||_==="mins"||_==="min"||_==="m"?6e4*y:_==="seconds"||_==="second"||_==="secs"||_==="sec"||_==="s"?1e3*y:_==="milliseconds"||_==="millisecond"||_==="msecs"||_==="msec"||_==="ms"?y:void 0}}}function f(p){var m=r(p);return 864e5<=m?l(p/864e5)+"d":36e5<=m?l(p/36e5)+"h":6e4<=m?l(p/6e4)+"m":1e3<=m?l(p/1e3)+"s":p+"ms"}function b(p){var m=r(p);return 864e5<=m?u(p,m,864e5,"day"):36e5<=m?u(p,m,36e5,"hour"):6e4<=m?u(p,m,6e4,"minute"):1e3<=m?u(p,m,1e3,"second"):p+" ms"}function u(p,m,y,_){return l(p/y)+" "+_+(m>=1.5*y?"s":"")}d.exports=function(p,m){m=m||{};var y=typeof p;if(y=="string"&&0<p.length)return c(p);if(y==="number"&&isFinite(p))return m.long?b(p):f(p);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(p))}},{}],12:[function(a,d){function l(){throw new Error("setTimeout has not been defined")}function c(){throw new Error("clearTimeout has not been defined")}function f(A){if(_===setTimeout)return setTimeout(A,0);if((_===l||!_)&&setTimeout)return _=setTimeout,setTimeout(A,0);try{return _(A,0)}catch{try{return _.call(null,A,0)}catch{return _.call(this,A,0)}}}function b(A){if(R===clearTimeout)return clearTimeout(A);if((R===c||!R)&&clearTimeout)return R=clearTimeout,clearTimeout(A);try{return R(A)}catch{try{return R.call(null,A)}catch{return R.call(this,A)}}}function u(){j&&I&&(j=!1,I.length?g=I.concat(g):v=-1,g.length&&p())}function p(){if(!j){var A=f(u);j=!0;for(var E=g.length;E;){for(I=g,g=[];++v<E;)I&&I[v].run();v=-1,E=g.length}I=null,j=!1,b(A)}}function m(A,E){this.fun=A,this.array=E}function y(){}var _,R,k=d.exports={};(function(){try{_=typeof setTimeout=="function"?setTimeout:l}catch{_=l}try{R=typeof clearTimeout=="function"?clearTimeout:c}catch{R=c}})();var I,g=[],j=!1,v=-1;k.nextTick=function(A){var E=Array(arguments.length-1);if(1<arguments.length)for(var N=1;N<arguments.length;N++)E[N-1]=arguments[N];g.push(new m(A,E)),g.length!==1||j||f(p)},m.prototype.run=function(){this.fun.apply(null,this.array)},k.title="browser",k.browser=!0,k.env={},k.argv=[],k.version="",k.versions={},k.on=y,k.addListener=y,k.once=y,k.off=y,k.removeListener=y,k.removeAllListeners=y,k.emit=y,k.prependListener=y,k.prependOnceListener=y,k.listeners=function(){return[]},k.binding=function(){throw new Error("process.binding is not supported")},k.cwd=function(){return"/"},k.chdir=function(){throw new Error("process.chdir is not supported")},k.umask=function(){return 0}},{}],13:[function(a,d){(function(l){(function(){/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let c;d.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window>"u"?l:window):f=>(c||(c=Promise.resolve())).then(f).catch(b=>setTimeout(()=>{throw b},0))}).call(this)}).call(this,typeof tt>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:tt)},{}],14:[function(a,d){(function(l,c){(function(){var f=a("safe-buffer").Buffer,b=c.crypto||c.msCrypto;d.exports=b&&b.getRandomValues?function(u,p){if(u>4294967295)throw new RangeError("requested too many random bytes");var m=f.allocUnsafe(u);if(0<u)if(65536<u)for(var y=0;y<u;y+=65536)b.getRandomValues(m.slice(y,y+65536));else b.getRandomValues(m);return typeof p=="function"?l.nextTick(function(){p(null,m)}):m}:function(){throw new Error(`Secure random number generation is not supported by this browser.
67
- Use Chrome, Firefox or Internet Explorer 11`)}}).call(this)}).call(this,a("_process"),typeof tt>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:tt)},{_process:12,"safe-buffer":30}],15:[function(a,d){function l(y,_){y.prototype=Object.create(_.prototype),y.prototype.constructor=y,y.__proto__=_}function c(y,_,R){function k(g,j,v){return typeof _=="string"?_:_(g,j,v)}R||(R=Error);var I=(function(g){function j(v,A,E){return g.call(this,k(v,A,E))||this}return l(j,g),j})(R);I.prototype.name=R.name,I.prototype.code=y,m[y]=I}function f(y,_){if(Array.isArray(y)){var R=y.length;return y=y.map(function(k){return k+""}),2<R?"one of ".concat(_," ").concat(y.slice(0,R-1).join(", "),", or ")+y[R-1]:R===2?"one of ".concat(_," ").concat(y[0]," or ").concat(y[1]):"of ".concat(_," ").concat(y[0])}return"of ".concat(_," ").concat(y+"")}function b(y,_,R){return y.substr(0,_.length)===_}function u(y,_,R){return(R===void 0||R>y.length)&&(R=y.length),y.substring(R-_.length,R)===_}function p(y,_,R){return typeof R!="number"&&(R=0),!(R+_.length>y.length)&&y.indexOf(_,R)!==-1}var m={};c("ERR_INVALID_OPT_VALUE",function(y,_){return'The value "'+_+'" is invalid for option "'+y+'"'},TypeError),c("ERR_INVALID_ARG_TYPE",function(y,_,R){var k;typeof _=="string"&&b(_,"not ")?(k="must not be",_=_.replace(/^not /,"")):k="must be";var I;if(u(y," argument"))I="The ".concat(y," ").concat(k," ").concat(f(_,"type"));else{var g=p(y,".")?"property":"argument";I='The "'.concat(y,'" ').concat(g," ").concat(k," ").concat(f(_,"type"))}return I+=". Received type ".concat(typeof R),I},TypeError),c("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),c("ERR_METHOD_NOT_IMPLEMENTED",function(y){return"The "+y+" method is not implemented"}),c("ERR_STREAM_PREMATURE_CLOSE","Premature close"),c("ERR_STREAM_DESTROYED",function(y){return"Cannot call "+y+" after a stream was destroyed"}),c("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),c("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),c("ERR_STREAM_WRITE_AFTER_END","write after end"),c("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),c("ERR_UNKNOWN_ENCODING",function(y){return"Unknown encoding: "+y},TypeError),c("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),d.exports.codes=m},{}],16:[function(a,d){(function(l){(function(){function c(k){return this instanceof c?(p.call(this,k),m.call(this,k),this.allowHalfOpen=!0,void(k&&(k.readable===!1&&(this.readable=!1),k.writable===!1&&(this.writable=!1),k.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",f))))):new c(k)}function f(){this._writableState.ended||l.nextTick(b,this)}function b(k){k.end()}var u=Object.keys||function(k){var I=[];for(var g in k)I.push(g);return I};d.exports=c;var p=a("./_stream_readable"),m=a("./_stream_writable");a("inherits")(c,p);for(var y,_=u(m.prototype),R=0;R<_.length;R++)y=_[R],c.prototype[y]||(c.prototype[y]=m.prototype[y]);Object.defineProperty(c.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(c.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(c.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(c.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._writableState!==void 0&&this._readableState.destroyed&&this._writableState.destroyed},set:function(k){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=k,this._writableState.destroyed=k)}})}).call(this)}).call(this,a("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(a,d){function l(f){return this instanceof l?void c.call(this,f):new l(f)}d.exports=l;var c=a("./_stream_transform");a("inherits")(l,c),l.prototype._transform=function(f,b,u){u(null,f)}},{"./_stream_transform":19,inherits:10}],18:[function(a,d){(function(l,c){(function(){function f(C){return se.from(C)}function b(C){return se.isBuffer(C)||C instanceof ie}function u(C,o,h){return typeof C.prependListener=="function"?C.prependListener(o,h):void(C._events&&C._events[o]?Array.isArray(C._events[o])?C._events[o].unshift(h):C._events[o]=[h,C._events[o]]:C.on(o,h))}function p(C,o,h){ye=ye||a("./_stream_duplex"),C=C||{},typeof h!="boolean"&&(h=o instanceof ye),this.objectMode=!!C.objectMode,h&&(this.objectMode=this.objectMode||!!C.readableObjectMode),this.highWaterMark=Ee(this,C,"readableHighWaterMark",h),this.buffer=new J,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=C.emitClose!==!1,this.autoDestroy=!!C.autoDestroy,this.destroyed=!1,this.defaultEncoding=C.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,C.encoding&&(!xe&&(xe=a("string_decoder/").StringDecoder),this.decoder=new xe(C.encoding),this.encoding=C.encoding)}function m(C){if(ye=ye||a("./_stream_duplex"),!(this instanceof m))return new m(C);var o=this instanceof ye;this._readableState=new p(C,this,o),this.readable=!0,C&&(typeof C.read=="function"&&(this._read=C.read),typeof C.destroy=="function"&&(this._destroy=C.destroy)),he.call(this)}function y(C,o,h,x,L){Z("readableAddChunk",o);var W=C._readableState;if(o===null)W.reading=!1,g(C,W);else{var B;if(L||(B=R(W,o)),B)z(C,B);else if(!(W.objectMode||o&&0<o.length))x||(W.reading=!1,A(C,W));else if(typeof o=="string"||W.objectMode||Object.getPrototypeOf(o)===se.prototype||(o=f(o)),x)W.endEmitted?z(C,new U):_(C,W,o,!0);else if(W.ended)z(C,new X);else{if(W.destroyed)return!1;W.reading=!1,W.decoder&&!h?(o=W.decoder.write(o),W.objectMode||o.length!==0?_(C,W,o,!1):A(C,W)):_(C,W,o,!1)}}return!W.ended&&(W.length<W.highWaterMark||W.length===0)}function _(C,o,h,x){o.flowing&&o.length===0&&!o.sync?(o.awaitDrain=0,C.emit("data",h)):(o.length+=o.objectMode?1:h.length,x?o.buffer.unshift(h):o.buffer.push(h),o.needReadable&&j(C)),A(C,o)}function R(C,o){var h;return b(o)||typeof o=="string"||o===void 0||C.objectMode||(h=new K("chunk",["string","Buffer","Uint8Array"],o)),h}function k(C){return 1073741824<=C?C=1073741824:(C--,C|=C>>>1,C|=C>>>2,C|=C>>>4,C|=C>>>8,C|=C>>>16,C++),C}function I(C,o){return 0>=C||o.length===0&&o.ended?0:o.objectMode?1:C===C?(C>o.highWaterMark&&(o.highWaterMark=k(C)),C<=o.length?C:o.ended?o.length:(o.needReadable=!0,0)):o.flowing&&o.length?o.buffer.head.data.length:o.length}function g(C,o){if(Z("onEofChunk"),!o.ended){if(o.decoder){var h=o.decoder.end();h&&h.length&&(o.buffer.push(h),o.length+=o.objectMode?1:h.length)}o.ended=!0,o.sync?j(C):(o.needReadable=!1,!o.emittedReadable&&(o.emittedReadable=!0,v(C)))}}function j(C){var o=C._readableState;Z("emitReadable",o.needReadable,o.emittedReadable),o.needReadable=!1,o.emittedReadable||(Z("emitReadable",o.flowing),o.emittedReadable=!0,l.nextTick(v,C))}function v(C){var o=C._readableState;Z("emitReadable_",o.destroyed,o.length,o.ended),!o.destroyed&&(o.length||o.ended)&&(C.emit("readable"),o.emittedReadable=!1),o.needReadable=!o.flowing&&!o.ended&&o.length<=o.highWaterMark,M(C)}function A(C,o){o.readingMore||(o.readingMore=!0,l.nextTick(E,C,o))}function E(C,o){for(;!o.reading&&!o.ended&&(o.length<o.highWaterMark||o.flowing&&o.length===0);){var h=o.length;if(Z("maybeReadMore read 0"),C.read(0),h===o.length)break}o.readingMore=!1}function N(C){return function(){var o=C._readableState;Z("pipeOnDrain",o.awaitDrain),o.awaitDrain&&o.awaitDrain--,o.awaitDrain===0&&ge(C,"data")&&(o.flowing=!0,M(C))}}function D(C){var o=C._readableState;o.readableListening=0<C.listenerCount("readable"),o.resumeScheduled&&!o.paused?o.flowing=!0:0<C.listenerCount("data")&&C.resume()}function S(C){Z("readable nexttick read 0"),C.read(0)}function T(C,o){o.resumeScheduled||(o.resumeScheduled=!0,l.nextTick(P,C,o))}function P(C,o){Z("resume",o.reading),o.reading||C.read(0),o.resumeScheduled=!1,C.emit("resume"),M(C),o.flowing&&!o.reading&&C.read(0)}function M(C){var o=C._readableState;for(Z("flow",o.flowing);o.flowing&&C.read()!==null;);}function F(C,o){if(o.length===0)return null;var h;return o.objectMode?h=o.buffer.shift():!C||C>=o.length?(h=o.decoder?o.buffer.join(""):o.buffer.length===1?o.buffer.first():o.buffer.concat(o.length),o.buffer.clear()):h=o.buffer.consume(C,o.decoder),h}function V(C){var o=C._readableState;Z("endReadable",o.endEmitted),o.endEmitted||(o.ended=!0,l.nextTick(Y,o,C))}function Y(C,o){if(Z("endReadableNT",C.endEmitted,C.length),!C.endEmitted&&C.length===0&&(C.endEmitted=!0,o.readable=!1,o.emit("end"),C.autoDestroy)){var h=o._writableState;(!h||h.autoDestroy&&h.finished)&&o.destroy()}}function q(C,o){for(var h=0,x=C.length;h<x;h++)if(C[h]===o)return h;return-1}d.exports=m;var ye;m.ReadableState=p;var Z;a("events").EventEmitter;var ge=function(C,o){return C.listeners(o).length},he=a("./internal/streams/stream"),se=a("buffer").Buffer,ie=c.Uint8Array||function(){},Q=a("util");Z=Q&&Q.debuglog?Q.debuglog("stream"):function(){};var xe,$,G,J=a("./internal/streams/buffer_list"),le=a("./internal/streams/destroy"),be=a("./internal/streams/state"),Ee=be.getHighWaterMark,H=a("../errors").codes,K=H.ERR_INVALID_ARG_TYPE,X=H.ERR_STREAM_PUSH_AFTER_EOF,O=H.ERR_METHOD_NOT_IMPLEMENTED,U=H.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;a("inherits")(m,he);var z=le.errorOrDestroy,ee=["error","close","destroy","pause","resume"];Object.defineProperty(m.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(C){this._readableState&&(this._readableState.destroyed=C)}}),m.prototype.destroy=le.destroy,m.prototype._undestroy=le.undestroy,m.prototype._destroy=function(C,o){o(C)},m.prototype.push=function(C,o){var h,x=this._readableState;return x.objectMode?h=!0:typeof C=="string"&&(o=o||x.defaultEncoding,o!==x.encoding&&(C=se.from(C,o),o=""),h=!0),y(this,C,o,!1,h)},m.prototype.unshift=function(C){return y(this,C,null,!0,!1)},m.prototype.isPaused=function(){return this._readableState.flowing===!1},m.prototype.setEncoding=function(C){xe||(xe=a("string_decoder/").StringDecoder);var o=new xe(C);this._readableState.decoder=o,this._readableState.encoding=this._readableState.decoder.encoding;for(var h=this._readableState.buffer.head,x="";h!==null;)x+=o.write(h.data),h=h.next;return this._readableState.buffer.clear(),x!==""&&this._readableState.buffer.push(x),this._readableState.length=x.length,this},m.prototype.read=function(C){Z("read",C),C=parseInt(C,10);var o=this._readableState,h=C;if(C!==0&&(o.emittedReadable=!1),C===0&&o.needReadable&&((o.highWaterMark===0?0<o.length:o.length>=o.highWaterMark)||o.ended))return Z("read: emitReadable",o.length,o.ended),o.length===0&&o.ended?V(this):j(this),null;if(C=I(C,o),C===0&&o.ended)return o.length===0&&V(this),null;var x=o.needReadable;Z("need readable",x),(o.length===0||o.length-C<o.highWaterMark)&&(x=!0,Z("length less than watermark",x)),o.ended||o.reading?(x=!1,Z("reading or ended",x)):x&&(Z("do read"),o.reading=!0,o.sync=!0,o.length===0&&(o.needReadable=!0),this._read(o.highWaterMark),o.sync=!1,!o.reading&&(C=I(h,o)));var L;return L=0<C?F(C,o):null,L===null?(o.needReadable=o.length<=o.highWaterMark,C=0):(o.length-=C,o.awaitDrain=0),o.length===0&&(!o.ended&&(o.needReadable=!0),h!==C&&o.ended&&V(this)),L!==null&&this.emit("data",L),L},m.prototype._read=function(){z(this,new O("_read()"))},m.prototype.pipe=function(C,o){function h(Pt,Wt){Z("onunpipe"),Pt===pe&&Wt&&Wt.hasUnpiped===!1&&(Wt.hasUnpiped=!0,L())}function x(){Z("onend"),C.end()}function L(){Z("cleanup"),C.removeListener("close",te),C.removeListener("finish",fe),C.removeListener("drain",Ot),C.removeListener("error",B),C.removeListener("unpipe",h),pe.removeListener("end",x),pe.removeListener("end",_e),pe.removeListener("data",W),ls=!0,ce.awaitDrain&&(!C._writableState||C._writableState.needDrain)&&Ot()}function W(Pt){Z("ondata");var Wt=C.write(Pt);Z("dest.write",Wt),Wt===!1&&((ce.pipesCount===1&&ce.pipes===C||1<ce.pipesCount&&q(ce.pipes,C)!==-1)&&!ls&&(Z("false write response, pause",ce.awaitDrain),ce.awaitDrain++),pe.pause())}function B(Pt){Z("onerror",Pt),_e(),C.removeListener("error",B),ge(C,"error")===0&&z(C,Pt)}function te(){C.removeListener("finish",fe),_e()}function fe(){Z("onfinish"),C.removeListener("close",te),_e()}function _e(){Z("unpipe"),pe.unpipe(C)}var pe=this,ce=this._readableState;switch(ce.pipesCount){case 0:ce.pipes=C;break;case 1:ce.pipes=[ce.pipes,C];break;default:ce.pipes.push(C)}ce.pipesCount+=1,Z("pipe count=%d opts=%j",ce.pipesCount,o);var Oe=(!o||o.end!==!1)&&C!==l.stdout&&C!==l.stderr,_t=Oe?x:_e;ce.endEmitted?l.nextTick(_t):pe.once("end",_t),C.on("unpipe",h);var Ot=N(pe);C.on("drain",Ot);var ls=!1;return pe.on("data",W),u(C,"error",B),C.once("close",te),C.once("finish",fe),C.emit("pipe",pe),ce.flowing||(Z("pipe resume"),pe.resume()),C},m.prototype.unpipe=function(C){var o=this._readableState,h={hasUnpiped:!1};if(o.pipesCount===0)return this;if(o.pipesCount===1)return C&&C!==o.pipes?this:(C||(C=o.pipes),o.pipes=null,o.pipesCount=0,o.flowing=!1,C&&C.emit("unpipe",this,h),this);if(!C){var x=o.pipes,L=o.pipesCount;o.pipes=null,o.pipesCount=0,o.flowing=!1;for(var W=0;W<L;W++)x[W].emit("unpipe",this,{hasUnpiped:!1});return this}var B=q(o.pipes,C);return B===-1?this:(o.pipes.splice(B,1),o.pipesCount-=1,o.pipesCount===1&&(o.pipes=o.pipes[0]),C.emit("unpipe",this,h),this)},m.prototype.on=function(C,o){var h=he.prototype.on.call(this,C,o),x=this._readableState;return C==="data"?(x.readableListening=0<this.listenerCount("readable"),x.flowing!==!1&&this.resume()):C=="readable"&&!x.endEmitted&&!x.readableListening&&(x.readableListening=x.needReadable=!0,x.flowing=!1,x.emittedReadable=!1,Z("on readable",x.length,x.reading),x.length?j(this):!x.reading&&l.nextTick(S,this)),h},m.prototype.addListener=m.prototype.on,m.prototype.removeListener=function(C,o){var h=he.prototype.removeListener.call(this,C,o);return C==="readable"&&l.nextTick(D,this),h},m.prototype.removeAllListeners=function(C){var o=he.prototype.removeAllListeners.apply(this,arguments);return(C==="readable"||C===void 0)&&l.nextTick(D,this),o},m.prototype.resume=function(){var C=this._readableState;return C.flowing||(Z("resume"),C.flowing=!C.readableListening,T(this,C)),C.paused=!1,this},m.prototype.pause=function(){return Z("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Z("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},m.prototype.wrap=function(C){var o=this,h=this._readableState,x=!1;for(var L in C.on("end",function(){if(Z("wrapped end"),h.decoder&&!h.ended){var B=h.decoder.end();B&&B.length&&o.push(B)}o.push(null)}),C.on("data",function(B){if(Z("wrapped data"),h.decoder&&(B=h.decoder.write(B)),!(h.objectMode&&B==null)&&(h.objectMode||B&&B.length)){var te=o.push(B);te||(x=!0,C.pause())}}),C)this[L]===void 0&&typeof C[L]=="function"&&(this[L]=(function(B){return function(){return C[B].apply(C,arguments)}})(L));for(var W=0;W<ee.length;W++)C.on(ee[W],this.emit.bind(this,ee[W]));return this._read=function(B){Z("wrapped _read",B),x&&(x=!1,C.resume())},this},typeof Symbol=="function"&&(m.prototype[Symbol.asyncIterator]=function(){return $===void 0&&($=a("./internal/streams/async_iterator")),$(this)}),Object.defineProperty(m.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(m.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(m.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(C){this._readableState&&(this._readableState.flowing=C)}}),m._fromList=F,Object.defineProperty(m.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),typeof Symbol=="function"&&(m.from=function(C,o){return G===void 0&&(G=a("./internal/streams/from")),G(m,C,o)})}).call(this)}).call(this,a("_process"),typeof tt>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:tt)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/async_iterator":21,"./internal/streams/buffer_list":22,"./internal/streams/destroy":23,"./internal/streams/from":25,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,events:7,inherits:10,"string_decoder/":31,util:2}],19:[function(a,d){function l(k,I){var g=this._transformState;g.transforming=!1;var j=g.writecb;if(j===null)return this.emit("error",new m);g.writechunk=null,g.writecb=null,I!=null&&this.push(I),j(k);var v=this._readableState;v.reading=!1,(v.needReadable||v.length<v.highWaterMark)&&this._read(v.highWaterMark)}function c(k){return this instanceof c?(R.call(this,k),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,k&&(typeof k.transform=="function"&&(this._transform=k.transform),typeof k.flush=="function"&&(this._flush=k.flush)),void this.on("prefinish",f)):new c(k)}function f(){var k=this;typeof this._flush!="function"||this._readableState.destroyed?b(this,null,null):this._flush(function(I,g){b(k,I,g)})}function b(k,I,g){if(I)return k.emit("error",I);if(g!=null&&k.push(g),k._writableState.length)throw new _;if(k._transformState.transforming)throw new y;return k.push(null)}d.exports=c;var u=a("../errors").codes,p=u.ERR_METHOD_NOT_IMPLEMENTED,m=u.ERR_MULTIPLE_CALLBACK,y=u.ERR_TRANSFORM_ALREADY_TRANSFORMING,_=u.ERR_TRANSFORM_WITH_LENGTH_0,R=a("./_stream_duplex");a("inherits")(c,R),c.prototype.push=function(k,I){return this._transformState.needTransform=!1,R.prototype.push.call(this,k,I)},c.prototype._transform=function(k,I,g){g(new p("_transform()"))},c.prototype._write=function(k,I,g){var j=this._transformState;if(j.writecb=g,j.writechunk=k,j.writeencoding=I,!j.transforming){var v=this._readableState;(j.needTransform||v.needReadable||v.length<v.highWaterMark)&&this._read(v.highWaterMark)}},c.prototype._read=function(){var k=this._transformState;k.writechunk===null||k.transforming?k.needTransform=!0:(k.transforming=!0,this._transform(k.writechunk,k.writeencoding,k.afterTransform))},c.prototype._destroy=function(k,I){R.prototype._destroy.call(this,k,function(g){I(g)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(a,d){(function(l,c){(function(){function f(O){var U=this;this.next=null,this.entry=null,this.finish=function(){V(U,O)}}function b(O){return Z.from(O)}function u(O){return Z.isBuffer(O)||O instanceof ge}function p(){}function m(O,U,z){Y=Y||a("./_stream_duplex"),O=O||{},typeof z!="boolean"&&(z=U instanceof Y),this.objectMode=!!O.objectMode,z&&(this.objectMode=this.objectMode||!!O.writableObjectMode),this.highWaterMark=ie(this,O,"writableHighWaterMark",z),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var ee=O.decodeStrings===!1;this.decodeStrings=!ee,this.defaultEncoding=O.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(C){A(U,C)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=O.emitClose!==!1,this.autoDestroy=!!O.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new f(this)}function y(O){Y=Y||a("./_stream_duplex");var U=this instanceof Y;return U||X.call(y,this)?(this._writableState=new m(O,this,U),this.writable=!0,O&&(typeof O.write=="function"&&(this._write=O.write),typeof O.writev=="function"&&(this._writev=O.writev),typeof O.destroy=="function"&&(this._destroy=O.destroy),typeof O.final=="function"&&(this._final=O.final)),void ye.call(this)):new y(O)}function _(O,U){var z=new Ee;K(O,z),l.nextTick(U,z)}function R(O,U,z,ee){var C;return z===null?C=new be:typeof z!="string"&&!U.objectMode&&(C=new xe("chunk",["string","Buffer"],z)),!C||(K(O,C),l.nextTick(ee,C),!1)}function k(O,U,z){return O.objectMode||O.decodeStrings===!1||typeof U!="string"||(U=Z.from(U,z)),U}function I(O,U,z,ee,C,o){if(!z){var h=k(U,ee,C);ee!==h&&(z=!0,C="buffer",ee=h)}var x=U.objectMode?1:ee.length;U.length+=x;var L=U.length<U.highWaterMark;if(L||(U.needDrain=!0),U.writing||U.corked){var W=U.lastBufferedRequest;U.lastBufferedRequest={chunk:ee,encoding:C,isBuf:z,callback:o,next:null},W?W.next=U.lastBufferedRequest:U.bufferedRequest=U.lastBufferedRequest,U.bufferedRequestCount+=1}else g(O,U,!1,x,ee,C,o);return L}function g(O,U,z,ee,C,o,h){U.writelen=ee,U.writecb=h,U.writing=!0,U.sync=!0,U.destroyed?U.onwrite(new le("write")):z?O._writev(C,U.onwrite):O._write(C,o,U.onwrite),U.sync=!1}function j(O,U,z,ee,C){--U.pendingcb,z?(l.nextTick(C,ee),l.nextTick(M,O,U),O._writableState.errorEmitted=!0,K(O,ee)):(C(ee),O._writableState.errorEmitted=!0,K(O,ee),M(O,U))}function v(O){O.writing=!1,O.writecb=null,O.length-=O.writelen,O.writelen=0}function A(O,U){var z=O._writableState,ee=z.sync,C=z.writecb;if(typeof C!="function")throw new G;if(v(z),U)j(O,z,ee,U,C);else{var o=S(z)||O.destroyed;o||z.corked||z.bufferProcessing||!z.bufferedRequest||D(O,z),ee?l.nextTick(E,O,z,o,C):E(O,z,o,C)}}function E(O,U,z,ee){z||N(O,U),U.pendingcb--,ee(),M(O,U)}function N(O,U){U.length===0&&U.needDrain&&(U.needDrain=!1,O.emit("drain"))}function D(O,U){U.bufferProcessing=!0;var z=U.bufferedRequest;if(O._writev&&z&&z.next){var ee=U.bufferedRequestCount,C=Array(ee),o=U.corkedRequestsFree;o.entry=z;for(var h=0,x=!0;z;)C[h]=z,z.isBuf||(x=!1),z=z.next,h+=1;C.allBuffers=x,g(O,U,!0,U.length,C,"",o.finish),U.pendingcb++,U.lastBufferedRequest=null,o.next?(U.corkedRequestsFree=o.next,o.next=null):U.corkedRequestsFree=new f(U),U.bufferedRequestCount=0}else{for(;z;){var L=z.chunk,W=z.encoding,B=z.callback,te=U.objectMode?1:L.length;if(g(O,U,!1,te,L,W,B),z=z.next,U.bufferedRequestCount--,U.writing)break}z===null&&(U.lastBufferedRequest=null)}U.bufferedRequest=z,U.bufferProcessing=!1}function S(O){return O.ending&&O.length===0&&O.bufferedRequest===null&&!O.finished&&!O.writing}function T(O,U){O._final(function(z){U.pendingcb--,z&&K(O,z),U.prefinished=!0,O.emit("prefinish"),M(O,U)})}function P(O,U){U.prefinished||U.finalCalled||(typeof O._final!="function"||U.destroyed?(U.prefinished=!0,O.emit("prefinish")):(U.pendingcb++,U.finalCalled=!0,l.nextTick(T,O,U)))}function M(O,U){var z=S(U);if(z&&(P(O,U),U.pendingcb===0&&(U.finished=!0,O.emit("finish"),U.autoDestroy))){var ee=O._readableState;(!ee||ee.autoDestroy&&ee.endEmitted)&&O.destroy()}return z}function F(O,U,z){U.ending=!0,M(O,U),z&&(U.finished?l.nextTick(z):O.once("finish",z)),U.ended=!0,O.writable=!1}function V(O,U,z){var ee=O.entry;for(O.entry=null;ee;){var C=ee.callback;U.pendingcb--,C(z),ee=ee.next}U.corkedRequestsFree.next=O}d.exports=y;var Y;y.WritableState=m;var q={deprecate:a("util-deprecate")},ye=a("./internal/streams/stream"),Z=a("buffer").Buffer,ge=c.Uint8Array||function(){},he=a("./internal/streams/destroy"),se=a("./internal/streams/state"),ie=se.getHighWaterMark,Q=a("../errors").codes,xe=Q.ERR_INVALID_ARG_TYPE,$=Q.ERR_METHOD_NOT_IMPLEMENTED,G=Q.ERR_MULTIPLE_CALLBACK,J=Q.ERR_STREAM_CANNOT_PIPE,le=Q.ERR_STREAM_DESTROYED,be=Q.ERR_STREAM_NULL_VALUES,Ee=Q.ERR_STREAM_WRITE_AFTER_END,H=Q.ERR_UNKNOWN_ENCODING,K=he.errorOrDestroy;a("inherits")(y,ye),m.prototype.getBuffer=function(){for(var O=this.bufferedRequest,U=[];O;)U.push(O),O=O.next;return U},(function(){try{Object.defineProperty(m.prototype,"buffer",{get:q.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var X;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(X=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(O){return!!X.call(this,O)||this===y&&O&&O._writableState instanceof m}})):X=function(O){return O instanceof this},y.prototype.pipe=function(){K(this,new J)},y.prototype.write=function(O,U,z){var ee=this._writableState,C=!1,o=!ee.objectMode&&u(O);return o&&!Z.isBuffer(O)&&(O=b(O)),typeof U=="function"&&(z=U,U=null),o?U="buffer":!U&&(U=ee.defaultEncoding),typeof z!="function"&&(z=p),ee.ending?_(this,z):(o||R(this,ee,O,z))&&(ee.pendingcb++,C=I(this,ee,o,O,U,z)),C},y.prototype.cork=function(){this._writableState.corked++},y.prototype.uncork=function(){var O=this._writableState;O.corked&&(O.corked--,!O.writing&&!O.corked&&!O.bufferProcessing&&O.bufferedRequest&&D(this,O))},y.prototype.setDefaultEncoding=function(O){if(typeof O=="string"&&(O=O.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((O+"").toLowerCase())))throw new H(O);return this._writableState.defaultEncoding=O,this},Object.defineProperty(y.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(O,U,z){z(new $("_write()"))},y.prototype._writev=null,y.prototype.end=function(O,U,z){var ee=this._writableState;return typeof O=="function"?(z=O,O=null,U=null):typeof U=="function"&&(z=U,U=null),O!=null&&this.write(O,U),ee.corked&&(ee.corked=1,this.uncork()),ee.ending||F(this,ee,z),this},Object.defineProperty(y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(y.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(O){this._writableState&&(this._writableState.destroyed=O)}}),y.prototype.destroy=he.destroy,y.prototype._undestroy=he.undestroy,y.prototype._destroy=function(O,U){U(O)}}).call(this)}).call(this,a("_process"),typeof tt>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:tt)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/destroy":23,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,inherits:10,"util-deprecate":32}],21:[function(a,d){(function(l){(function(){function c(N,D,S){return D in N?Object.defineProperty(N,D,{value:S,enumerable:!0,configurable:!0,writable:!0}):N[D]=S,N}function f(N,D){return{value:N,done:D}}function b(N){var D=N[_];if(D!==null){var S=N[v].read();S!==null&&(N[g]=null,N[_]=null,N[R]=null,D(f(S,!1)))}}function u(N){l.nextTick(b,N)}function p(N,D){return function(S,T){N.then(function(){return D[I]?void S(f(void 0,!0)):void D[j](S,T)},T)}}var m,y=a("./end-of-stream"),_=Symbol("lastResolve"),R=Symbol("lastReject"),k=Symbol("error"),I=Symbol("ended"),g=Symbol("lastPromise"),j=Symbol("handlePromise"),v=Symbol("stream"),A=Object.getPrototypeOf(function(){}),E=Object.setPrototypeOf((m={get stream(){return this[v]},next:function(){var N=this,D=this[k];if(D!==null)return Promise.reject(D);if(this[I])return Promise.resolve(f(void 0,!0));if(this[v].destroyed)return new Promise(function(M,F){l.nextTick(function(){N[k]?F(N[k]):M(f(void 0,!0))})});var S,T=this[g];if(T)S=new Promise(p(T,this));else{var P=this[v].read();if(P!==null)return Promise.resolve(f(P,!1));S=new Promise(this[j])}return this[g]=S,S}},c(m,Symbol.asyncIterator,function(){return this}),c(m,"return",function(){var N=this;return new Promise(function(D,S){N[v].destroy(null,function(T){return T?void S(T):void D(f(void 0,!0))})})}),m),A);d.exports=function(N){var D,S=Object.create(E,(D={},c(D,v,{value:N,writable:!0}),c(D,_,{value:null,writable:!0}),c(D,R,{value:null,writable:!0}),c(D,k,{value:null,writable:!0}),c(D,I,{value:N._readableState.endEmitted,writable:!0}),c(D,j,{value:function(T,P){var M=S[v].read();M?(S[g]=null,S[_]=null,S[R]=null,T(f(M,!1))):(S[_]=T,S[R]=P)},writable:!0}),D));return S[g]=null,y(N,function(T){if(T&&T.code!=="ERR_STREAM_PREMATURE_CLOSE"){var P=S[R];return P!==null&&(S[g]=null,S[_]=null,S[R]=null,P(T)),void(S[k]=T)}var M=S[_];M!==null&&(S[g]=null,S[_]=null,S[R]=null,M(f(void 0,!0))),S[I]=!0}),N.on("readable",u.bind(null,S)),S}}).call(this)}).call(this,a("_process"))},{"./end-of-stream":24,_process:12}],22:[function(a,d){function l(g,j){var v=Object.keys(g);if(Object.getOwnPropertySymbols){var A=Object.getOwnPropertySymbols(g);j&&(A=A.filter(function(E){return Object.getOwnPropertyDescriptor(g,E).enumerable})),v.push.apply(v,A)}return v}function c(g){for(var j,v=1;v<arguments.length;v++)j=arguments[v]==null?{}:arguments[v],v%2?l(Object(j),!0).forEach(function(A){f(g,A,j[A])}):Object.getOwnPropertyDescriptors?Object.defineProperties(g,Object.getOwnPropertyDescriptors(j)):l(Object(j)).forEach(function(A){Object.defineProperty(g,A,Object.getOwnPropertyDescriptor(j,A))});return g}function f(g,j,v){return j in g?Object.defineProperty(g,j,{value:v,enumerable:!0,configurable:!0,writable:!0}):g[j]=v,g}function b(g,j){if(!(g instanceof j))throw new TypeError("Cannot call a class as a function")}function u(g,j){for(var v,A=0;A<j.length;A++)v=j[A],v.enumerable=v.enumerable||!1,v.configurable=!0,"value"in v&&(v.writable=!0),Object.defineProperty(g,v.key,v)}function p(g,j,v){return j&&u(g.prototype,j),g}function m(g,j,v){_.prototype.copy.call(g,j,v)}var y=a("buffer"),_=y.Buffer,R=a("util"),k=R.inspect,I=k&&k.custom||"inspect";d.exports=(function(){function g(){b(this,g),this.head=null,this.tail=null,this.length=0}return p(g,[{key:"push",value:function(j){var v={data:j,next:null};0<this.length?this.tail.next=v:this.head=v,this.tail=v,++this.length}},{key:"unshift",value:function(j){var v={data:j,next:this.head};this.length===0&&(this.tail=v),this.head=v,++this.length}},{key:"shift",value:function(){if(this.length!==0){var j=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,j}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(j){if(this.length===0)return"";for(var v=this.head,A=""+v.data;v=v.next;)A+=j+v.data;return A}},{key:"concat",value:function(j){if(this.length===0)return _.alloc(0);for(var v=_.allocUnsafe(j>>>0),A=this.head,E=0;A;)m(A.data,v,E),E+=A.data.length,A=A.next;return v}},{key:"consume",value:function(j,v){var A;return j<this.head.data.length?(A=this.head.data.slice(0,j),this.head.data=this.head.data.slice(j)):j===this.head.data.length?A=this.shift():A=v?this._getString(j):this._getBuffer(j),A}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(j){var v=this.head,A=1,E=v.data;for(j-=E.length;v=v.next;){var N=v.data,D=j>N.length?N.length:j;if(E+=D===N.length?N:N.slice(0,j),j-=D,j===0){D===N.length?(++A,this.head=v.next?v.next:this.tail=null):(this.head=v,v.data=N.slice(D));break}++A}return this.length-=A,E}},{key:"_getBuffer",value:function(j){var v=_.allocUnsafe(j),A=this.head,E=1;for(A.data.copy(v),j-=A.data.length;A=A.next;){var N=A.data,D=j>N.length?N.length:j;if(N.copy(v,v.length-j,0,D),j-=D,j===0){D===N.length?(++E,this.head=A.next?A.next:this.tail=null):(this.head=A,A.data=N.slice(D));break}++E}return this.length-=E,v}},{key:I,value:function(j,v){return k(this,c({},v,{depth:0,customInspect:!1}))}}]),g})()},{buffer:3,util:2}],23:[function(a,d){(function(l){(function(){function c(u,p){b(u,p),f(u)}function f(u){u._writableState&&!u._writableState.emitClose||u._readableState&&!u._readableState.emitClose||u.emit("close")}function b(u,p){u.emit("error",p)}d.exports={destroy:function(u,p){var m=this,y=this._readableState&&this._readableState.destroyed,_=this._writableState&&this._writableState.destroyed;return y||_?(p?p(u):u&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,l.nextTick(b,this,u)):l.nextTick(b,this,u)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(u||null,function(R){!p&&R?m._writableState?m._writableState.errorEmitted?l.nextTick(f,m):(m._writableState.errorEmitted=!0,l.nextTick(c,m,R)):l.nextTick(c,m,R):p?(l.nextTick(f,m),p(R)):l.nextTick(f,m)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(u,p){var m=u._readableState,y=u._writableState;m&&m.autoDestroy||y&&y.autoDestroy?u.destroy(p):u.emit("error",p)}}}).call(this)}).call(this,a("_process"))},{_process:12}],24:[function(a,d){function l(p){var m=!1;return function(){if(!m){m=!0;for(var y=arguments.length,_=Array(y),R=0;R<y;R++)_[R]=arguments[R];p.apply(this,_)}}}function c(){}function f(p){return p.setHeader&&typeof p.abort=="function"}function b(p,m,y){if(typeof m=="function")return b(p,null,m);m||(m={}),y=l(y||c);var _=m.readable||m.readable!==!1&&p.readable,R=m.writable||m.writable!==!1&&p.writable,k=function(){p.writable||g()},I=p._writableState&&p._writableState.finished,g=function(){R=!1,I=!0,_||y.call(p)},j=p._readableState&&p._readableState.endEmitted,v=function(){_=!1,j=!0,R||y.call(p)},A=function(D){y.call(p,D)},E=function(){var D;return _&&!j?(p._readableState&&p._readableState.ended||(D=new u),y.call(p,D)):R&&!I?(p._writableState&&p._writableState.ended||(D=new u),y.call(p,D)):void 0},N=function(){p.req.on("finish",g)};return f(p)?(p.on("complete",g),p.on("abort",E),p.req?N():p.on("request",N)):R&&!p._writableState&&(p.on("end",k),p.on("close",k)),p.on("end",v),p.on("finish",g),m.error!==!1&&p.on("error",A),p.on("close",E),function(){p.removeListener("complete",g),p.removeListener("abort",E),p.removeListener("request",N),p.req&&p.req.removeListener("finish",g),p.removeListener("end",k),p.removeListener("close",k),p.removeListener("finish",g),p.removeListener("end",v),p.removeListener("error",A),p.removeListener("close",E)}}var u=a("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;d.exports=b},{"../../../errors":15}],25:[function(a,d){d.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(a,d){function l(I){var g=!1;return function(){g||(g=!0,I.apply(void 0,arguments))}}function c(I){if(I)throw I}function f(I){return I.setHeader&&typeof I.abort=="function"}function b(I,g,j,v){v=l(v);var A=!1;I.on("close",function(){A=!0}),y===void 0&&(y=a("./end-of-stream")),y(I,{readable:g,writable:j},function(N){return N?v(N):(A=!0,void v())});var E=!1;return function(N){if(!A)return E?void 0:(E=!0,f(I)?I.abort():typeof I.destroy=="function"?I.destroy():void v(N||new k("pipe")))}}function u(I){I()}function p(I,g){return I.pipe(g)}function m(I){return I.length&&typeof I[I.length-1]=="function"?I.pop():c}var y,_=a("../../../errors").codes,R=_.ERR_MISSING_ARGS,k=_.ERR_STREAM_DESTROYED;d.exports=function(){for(var I=arguments.length,g=Array(I),j=0;j<I;j++)g[j]=arguments[j];var v=m(g);if(Array.isArray(g[0])&&(g=g[0]),2>g.length)throw new R("streams");var A,E=g.map(function(N,D){var S=D<g.length-1;return b(N,S,0<D,function(T){A||(A=T),T&&E.forEach(u),S||(E.forEach(u),v(A))})});return g.reduce(p)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(a,d){function l(f,b,u){return f.highWaterMark==null?b?f[u]:null:f.highWaterMark}var c=a("../../../errors").codes.ERR_INVALID_OPT_VALUE;d.exports={getHighWaterMark:function(f,b,u,p){var m=l(b,p,u);if(m!=null){if(!(isFinite(m)&&s(m)===m)||0>m){var y=p?u:"highWaterMark";throw new c(y,m)}return s(m)}return f.objectMode?16:16384}}},{"../../../errors":15}],28:[function(a,d){d.exports=a("events").EventEmitter},{events:7}],29:[function(a,d,l){l=d.exports=a("./lib/_stream_readable.js"),l.Stream=l,l.Readable=l,l.Writable=a("./lib/_stream_writable.js"),l.Duplex=a("./lib/_stream_duplex.js"),l.Transform=a("./lib/_stream_transform.js"),l.PassThrough=a("./lib/_stream_passthrough.js"),l.finished=a("./lib/internal/streams/end-of-stream.js"),l.pipeline=a("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(a,d,l){function c(p,m){for(var y in p)m[y]=p[y]}function f(p,m,y){return u(p,m,y)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var b=a("buffer"),u=b.Buffer;u.from&&u.alloc&&u.allocUnsafe&&u.allocUnsafeSlow?d.exports=b:(c(b,l),l.Buffer=f),f.prototype=Object.create(u.prototype),c(u,f),f.from=function(p,m,y){if(typeof p=="number")throw new TypeError("Argument must not be a number");return u(p,m,y)},f.alloc=function(p,m,y){if(typeof p!="number")throw new TypeError("Argument must be a number");var _=u(p);return m===void 0?_.fill(0):typeof y=="string"?_.fill(m,y):_.fill(m),_},f.allocUnsafe=function(p){if(typeof p!="number")throw new TypeError("Argument must be a number");return u(p)},f.allocUnsafeSlow=function(p){if(typeof p!="number")throw new TypeError("Argument must be a number");return b.SlowBuffer(p)}},{buffer:3}],31:[function(a,d,l){function c(E){if(!E)return"utf8";for(var N;;)switch(E){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return E;default:if(N)return;E=(""+E).toLowerCase(),N=!0}}function f(E){var N=c(E);if(typeof N!="string"&&(v.isEncoding===A||!A(E)))throw new Error("Unknown encoding: "+E);return N||E}function b(E){this.encoding=f(E);var N;switch(this.encoding){case"utf16le":this.text=_,this.end=R,N=4;break;case"utf8":this.fillLast=y,N=4;break;case"base64":this.text=k,this.end=I,N=3;break;default:return this.write=g,void(this.end=j)}this.lastNeed=0,this.lastTotal=0,this.lastChar=v.allocUnsafe(N)}function u(E){return 127>=E?0:E>>5==6?2:E>>4==14?3:E>>3==30?4:E>>6==2?-1:-2}function p(E,N,D){var S=N.length-1;if(S<D)return 0;var T=u(N[S]);return 0<=T?(0<T&&(E.lastNeed=T-1),T):--S<D||T===-2?0:(T=u(N[S]),0<=T?(0<T&&(E.lastNeed=T-2),T):--S<D||T===-2?0:(T=u(N[S]),0<=T?(0<T&&(T===2?T=0:E.lastNeed=T-3),T):0))}function m(E,N){if((192&N[0])!=128)return E.lastNeed=0,"�";if(1<E.lastNeed&&1<N.length){if((192&N[1])!=128)return E.lastNeed=1,"�";if(2<E.lastNeed&&2<N.length&&(192&N[2])!=128)return E.lastNeed=2,"�"}}function y(E){var N=this.lastTotal-this.lastNeed,D=m(this,E);return D===void 0?this.lastNeed<=E.length?(E.copy(this.lastChar,N,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(E.copy(this.lastChar,N,0,E.length),void(this.lastNeed-=E.length)):D}function _(E,N){if((E.length-N)%2==0){var D=E.toString("utf16le",N);if(D){var S=D.charCodeAt(D.length-1);if(55296<=S&&56319>=S)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=E[E.length-2],this.lastChar[1]=E[E.length-1],D.slice(0,-1)}return D}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=E[E.length-1],E.toString("utf16le",N,E.length-1)}function R(E){var N=E&&E.length?this.write(E):"";if(this.lastNeed){var D=this.lastTotal-this.lastNeed;return N+this.lastChar.toString("utf16le",0,D)}return N}function k(E,N){var D=(E.length-N)%3;return D==0?E.toString("base64",N):(this.lastNeed=3-D,this.lastTotal=3,D==1?this.lastChar[0]=E[E.length-1]:(this.lastChar[0]=E[E.length-2],this.lastChar[1]=E[E.length-1]),E.toString("base64",N,E.length-D))}function I(E){var N=E&&E.length?this.write(E):"";return this.lastNeed?N+this.lastChar.toString("base64",0,3-this.lastNeed):N}function g(E){return E.toString(this.encoding)}function j(E){return E&&E.length?this.write(E):""}var v=a("safe-buffer").Buffer,A=v.isEncoding||function(E){switch(E=""+E,E&&E.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};l.StringDecoder=b,b.prototype.write=function(E){if(E.length===0)return"";var N,D;if(this.lastNeed){if(N=this.fillLast(E),N===void 0)return"";D=this.lastNeed,this.lastNeed=0}else D=0;return D<E.length?N?N+this.text(E,D):this.text(E,D):N||""},b.prototype.end=function(E){var N=E&&E.length?this.write(E):"";return this.lastNeed?N+"�":N},b.prototype.text=function(E,N){var D=p(this,E,N);if(!this.lastNeed)return E.toString("utf8",N);this.lastTotal=D;var S=E.length-(D-this.lastNeed);return E.copy(this.lastChar,0,S),E.toString("utf8",N,S)},b.prototype.fillLast=function(E){return this.lastNeed<=E.length?(E.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(E.copy(this.lastChar,this.lastTotal-this.lastNeed,0,E.length),void(this.lastNeed-=E.length))}},{"safe-buffer":30}],32:[function(a,d){(function(l){(function(){function c(f){try{if(!l.localStorage)return!1}catch{return!1}var b=l.localStorage[f];return b!=null&&(b+"").toLowerCase()==="true"}d.exports=function(f,b){function u(){if(!p){if(c("throwDeprecation"))throw new Error(b);c("traceDeprecation")?console.trace(b):console.warn(b),p=!0}return f.apply(this,arguments)}if(c("noDeprecation"))return f;var p=!1;return u}}).call(this)}).call(this,typeof tt>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:tt)},{}],"/":[function(a,d){function l(I){return I.replace(/a=ice-options:trickle\s\n/g,"")}function c(I){console.warn(I)}/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const f=a("debug")("simple-peer"),b=a("get-browser-rtc"),u=a("randombytes"),p=a("readable-stream"),m=a("queue-microtask"),y=a("err-code"),{Buffer:_}=a("buffer"),R=65536;class k extends p.Duplex{constructor(g){if(g=Object.assign({allowHalfOpen:!1},g),super(g),this._id=u(4).toString("hex").slice(0,7),this._debug("new peer %o",g),this.channelName=g.initiator?g.channelName||u(20).toString("hex"):null,this.initiator=g.initiator||!1,this.channelConfig=g.channelConfig||k.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},k.config,g.config),this.offerOptions=g.offerOptions||{},this.answerOptions=g.answerOptions||{},this.sdpTransform=g.sdpTransform||(j=>j),this.streams=g.streams||(g.stream?[g.stream]:[]),this.trickle=g.trickle===void 0||g.trickle,this.allowHalfTrickle=g.allowHalfTrickle!==void 0&&g.allowHalfTrickle,this.iceCompleteTimeout=g.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=g.wrtc&&typeof g.wrtc=="object"?g.wrtc:b(),!this._wrtc)throw y(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(j){return void this.destroy(y(j,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=j=>{this._onIceCandidate(j)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(j=>{this.destroy(y(j,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=j=>{this._setupData(j)},this.streams&&this.streams.forEach(j=>{this.addStream(j)}),this._pc.ontrack=j=>{this._onTrack(j)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(g){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof g=="string")try{g=JSON.parse(g)}catch{g={}}this._debug("signal()"),g.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),g.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(g.transceiverRequest.kind,g.transceiverRequest.init)),g.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(g.candidate):this._pendingCandidates.push(g.candidate)),g.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(g)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(j=>{this._addIceCandidate(j)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(j=>{this.destroy(y(j,"ERR_SET_REMOTE_DESCRIPTION"))}),g.sdp||g.candidate||g.renegotiate||g.transceiverRequest||this.destroy(y(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(g){const j=new this._wrtc.RTCIceCandidate(g);this._pc.addIceCandidate(j).catch(v=>{!j.address||j.address.endsWith(".local")?c("Ignoring unsupported ICE candidate."):this.destroy(y(v,"ERR_ADD_ICE_CANDIDATE"))})}send(g){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(g)}}addTransceiver(g,j){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(g,j),this._needsNegotiation()}catch(v){this.destroy(y(v,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:g,init:j}})}}addStream(g){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),g.getTracks().forEach(j=>{this.addTrack(j,g)})}}addTrack(g,j){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const v=this._senderMap.get(g)||new Map;let A=v.get(j);if(!A)A=this._pc.addTrack(g,j),v.set(j,A),this._senderMap.set(g,v),this._needsNegotiation();else throw A.removed?y(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):y(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(g,j,v){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const A=this._senderMap.get(g),E=A?A.get(v):null;if(!E)throw y(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");j&&this._senderMap.set(j,A),E.replaceTrack==null?this.destroy(y(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):E.replaceTrack(j)}removeTrack(g,j){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const v=this._senderMap.get(g),A=v?v.get(j):null;if(!A)throw y(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{A.removed=!0,this._pc.removeTrack(A)}catch(E){E.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(A):this.destroy(y(E,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(g){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),g.getTracks().forEach(j=>{this.removeTrack(j,g)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,m(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(g){this._destroy(g,()=>{})}_destroy(g,j){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",g&&(g.message||g)),m(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",g&&(g.message||g)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,g&&this.emit("error",g),this.emit("close"),j()}))}_setupData(g){if(!g.channel)return this.destroy(y(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=g.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=R),this.channelName=this._channel.label,this._channel.onmessage=v=>{this._onChannelMessage(v)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=v=>{const A=v.error instanceof Error?v.error:new Error(`Datachannel error: ${v.message} ${v.filename}:${v.lineno}:${v.colno}`);this.destroy(y(A,"ERR_DATA_CHANNEL"))};let j=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(j&&this._onChannelClose(),j=!0):j=!1},5e3)}_read(){}_write(g,j,v){if(this.destroyed)return v(y(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(g)}catch(A){return this.destroy(y(A,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>R?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=v):v(null)}else this._debug("write before connect"),this._chunk=g,this._cb=v}_onFinish(){if(!this.destroyed){const g=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?g():this.once("connect",g)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(g=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(g.sdp=l(g.sdp)),g.sdp=this.sdpTransform(g.sdp);const j=()=>{if(!this.destroyed){const v=this._pc.localDescription||g;this._debug("signal"),this.emit("signal",{type:v.type,sdp:v.sdp})}};this._pc.setLocalDescription(g).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?j():this.once("_iceComplete",j))}).catch(v=>{this.destroy(y(v,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(g=>{this.destroy(y(g,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(g=>{g.mid||!g.sender.track||g.requested||(g.requested=!0,this.addTransceiver(g.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(g=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(g.sdp=l(g.sdp)),g.sdp=this.sdpTransform(g.sdp);const j=()=>{if(!this.destroyed){const v=this._pc.localDescription||g;this._debug("signal"),this.emit("signal",{type:v.type,sdp:v.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(g).then(()=>{this.destroyed||(this.trickle||this._iceComplete?j():this.once("_iceComplete",j))}).catch(v=>{this.destroy(y(v,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(g=>{this.destroy(y(g,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(y(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const g=this._pc.iceConnectionState,j=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",g,j),this.emit("iceStateChange",g,j),(g==="connected"||g==="completed")&&(this._pcReady=!0,this._maybeReady()),g==="failed"&&this.destroy(y(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),g==="closed"&&this.destroy(y(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(g){const j=v=>(Object.prototype.toString.call(v.values)==="[object Array]"&&v.values.forEach(A=>{Object.assign(v,A)}),v);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(v=>{const A=[];v.forEach(E=>{A.push(j(E))}),g(null,A)},v=>g(v)):0<this._pc.getStats.length?this._pc.getStats(v=>{if(this.destroyed)return;const A=[];v.result().forEach(E=>{const N={};E.names().forEach(D=>{N[D]=E.stat(D)}),N.id=E.id,N.type=E.type,N.timestamp=E.timestamp,A.push(j(N))}),g(null,A)},v=>g(v)):g(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const g=()=>{this.destroyed||this.getStats((j,v)=>{if(this.destroyed)return;j&&(v=[]);const A={},E={},N={};let D=!1;v.forEach(T=>{(T.type==="remotecandidate"||T.type==="remote-candidate")&&(A[T.id]=T),(T.type==="localcandidate"||T.type==="local-candidate")&&(E[T.id]=T),(T.type==="candidatepair"||T.type==="candidate-pair")&&(N[T.id]=T)});const S=T=>{D=!0;let P=E[T.localCandidateId];P&&(P.ip||P.address)?(this.localAddress=P.ip||P.address,this.localPort=+P.port):P&&P.ipAddress?(this.localAddress=P.ipAddress,this.localPort=+P.portNumber):typeof T.googLocalAddress=="string"&&(P=T.googLocalAddress.split(":"),this.localAddress=P[0],this.localPort=+P[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let M=A[T.remoteCandidateId];M&&(M.ip||M.address)?(this.remoteAddress=M.ip||M.address,this.remotePort=+M.port):M&&M.ipAddress?(this.remoteAddress=M.ipAddress,this.remotePort=+M.portNumber):typeof T.googRemoteAddress=="string"&&(M=T.googRemoteAddress.split(":"),this.remoteAddress=M[0],this.remotePort=+M[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(v.forEach(T=>{T.type==="transport"&&T.selectedCandidatePairId&&S(N[T.selectedCandidatePairId]),(T.type==="googCandidatePair"&&T.googActiveConnection==="true"||(T.type==="candidatepair"||T.type==="candidate-pair")&&T.selected)&&S(T)}),!D&&(!Object.keys(N).length||Object.keys(E).length))return void setTimeout(g,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(P){return this.destroy(y(P,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const T=this._cb;this._cb=null,T(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};g()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>R)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(g=>{this._pc.removeTrack(g),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(g){this.destroyed||(g.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:g.candidate.candidate,sdpMLineIndex:g.candidate.sdpMLineIndex,sdpMid:g.candidate.sdpMid}}):!g.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),g.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(g){if(this.destroyed)return;let j=g.data;j instanceof ArrayBuffer&&(j=_.from(j)),this.push(j)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const g=this._cb;this._cb=null,g(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(g){this.destroyed||g.streams.forEach(j=>{this._debug("on track"),this.emit("track",g.track,j),this._remoteTracks.push({track:g.track,stream:j}),this._remoteStreams.some(v=>v.id===j.id)||(this._remoteStreams.push(j),m(()=>{this._debug("on stream"),this.emit("stream",j)}))})}_debug(){const g=[].slice.call(arguments);g[0]="["+this._id+"] "+g[0],f.apply(null,g)}}k.WEBRTC_SUPPORT=!!b(),k.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},k.channelConfig={},d.exports=k},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(er)),er.exports}var bf=yf();const xf=Ml(bf),hi=0,fi=1,rl=2,il=(t,e)=>{ne(t,hi);const s=Hu(e);Se(t,s)},al=(t,e,s)=>{ne(t,fi),Se(t,ni(e,s))},wf=(t,e,s)=>al(e,s,Ie(t)),ol=(t,e,s,r)=>{try{So(e,Ie(t),s)}catch(i){r!=null&&r(i),console.error("Caught error while handling a Yjs update",i)}},vf=(t,e)=>{ne(t,rl),Se(t,e)},_f=ol,kf=(t,e,s,r,i)=>{const a=oe(t);switch(a){case hi:wf(t,e,s);break;case fi:ol(t,s,r,i);break;case rl:_f(t,s,r,i);break;default:throw new Error("Unknown message type")}return a},tr=3e4;class Sf extends Ur{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const s=ut();this.getLocalState()!==null&&tr/2<=s-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((i,a)=>{a!==this.clientID&&tr<=s-i.lastUpdated&&this.states.has(a)&&r.push(a)}),r.length>0&&_r(this,r,"timeout")},Je(tr/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const s=this.clientID,r=this.meta.get(s),i=r===void 0?0:r.clock+1,a=this.states.get(s);e===null?this.states.delete(s):this.states.set(s,e),this.meta.set(s,{clock:i,lastUpdated:ut()});const d=[],l=[],c=[],f=[];e===null?f.push(s):a==null?e!=null&&d.push(s):(l.push(s),zt(a,e)||c.push(s)),(d.length>0||c.length>0||f.length>0)&&this.emit("change",[{added:d,updated:c,removed:f},"local"]),this.emit("update",[{added:d,updated:l,removed:f},"local"])}setLocalStateField(e,s){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:s})}getStates(){return this.states}}const _r=(t,e,s)=>{const r=[];for(let i=0;i<e.length;i++){const a=e[i];if(t.states.has(a)){if(t.states.delete(a),a===t.clientID){const d=t.meta.get(a);t.meta.set(a,{clock:d.clock+1,lastUpdated:ut()})}r.push(a)}}r.length>0&&(t.emit("change",[{added:[],updated:[],removed:r},s]),t.emit("update",[{added:[],updated:[],removed:r},s]))},fn=(t,e,s=t.states)=>{const r=e.length,i=Le();ne(i,r);for(let a=0;a<r;a++){const d=e[a],l=s.get(d)||null,c=t.meta.get(d).clock;ne(i,d),ne(i,c),nt(i,JSON.stringify(l))}return ke(i)},jf=(t,e,s)=>{const r=at(e),i=ut(),a=[],d=[],l=[],c=[],f=oe(r);for(let b=0;b<f;b++){const u=oe(r);let p=oe(r);const m=JSON.parse(ct(r)),y=t.meta.get(u),_=t.states.get(u),R=y===void 0?0:y.clock;(R<p||R===p&&m===null&&t.states.has(u))&&(m===null?u===t.clientID&&t.getLocalState()!=null?p++:t.states.delete(u):t.states.set(u,m),t.meta.set(u,{clock:p,lastUpdated:i}),y===void 0&&m!==null?a.push(u):y!==void 0&&m===null?c.push(u):m!==null&&(zt(m,_)||l.push(u),d.push(u)))}(a.length>0||l.length>0||c.length>0)&&t.emit("change",[{added:a,updated:l,removed:c},s]),(a.length>0||d.length>0||c.length>0)&&t.emit("update",[{added:a,updated:d,removed:c},s])},Ef=(t,e)=>{const s=fr(t).buffer,r=fr(e).buffer;return crypto.subtle.importKey("raw",s,"PBKDF2",!1,["deriveKey"]).then(i=>crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:1e5,hash:"SHA-256"},i,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))},ll=(t,e)=>{if(!e)return Vr(t);const s=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,t).then(r=>{const i=Le();return nt(i,"AES-GCM"),Se(i,s),Se(i,new Uint8Array(r)),ke(i)})},Nf=(t,e)=>{const s=Le();return Jt(s,t),ll(ke(s),e)},cl=(t,e)=>{if(!e)return Vr(t);const s=at(t);ct(s)!=="AES-GCM"&&md(Ve("Unknown encryption algorithm"));const i=Ie(s),a=Ie(s);return crypto.subtle.decrypt({name:"AES-GCM",iv:i},e,a).then(d=>new Uint8Array(d))},Cf=(t,e)=>cl(t,e).then(s=>Xt(at(new Uint8Array(s)))),$e=Nu("y-webrtc"),Yt=0,dl=3,Cs=1,pi=4,pn=new Map,Et=new Map,ul=t=>{let e=!0;t.webrtcConns.forEach(s=>{s.synced||(e=!1)}),(!e&&t.synced||e&&!t.synced)&&(t.synced=e,t.provider.emit("synced",[{synced:e}]),$e("synced ",Ke,t.name,Ct," with all peers"))},hl=(t,e,s)=>{const r=at(e),i=Le(),a=oe(r);if(t===void 0)return null;const d=t.awareness,l=t.doc;let c=!1;switch(a){case Yt:{ne(i,Yt);const f=kf(r,i,l,t);f===fi&&!t.synced&&s(),f===hi&&(c=!0);break}case dl:ne(i,Cs),Se(i,fn(d,Array.from(d.getStates().keys()))),c=!0;break;case Cs:jf(d,Ie(r),t);break;case pi:{const f=Nt(r)===1,b=ct(r);if(b!==t.peerId&&(t.bcConns.has(b)&&!f||!t.bcConns.has(b)&&f)){const u=[],p=[];f?(t.bcConns.add(b),p.push(b)):(t.bcConns.delete(b),u.push(b)),t.provider.emit("peers",[{added:p,removed:u,webrtcPeers:Array.from(t.webrtcConns.keys()),bcPeers:Array.from(t.bcConns)}]),fl(t)}break}default:return console.error("Unable to compute message"),i}return c?i:null},Tf=(t,e)=>{const s=t.room;return $e("received message from ",Ke,t.remotePeerId,Qr," (",s.name,")",Ct,Dn),hl(s,e,()=>{t.synced=!0,$e("synced ",Ke,s.name,Ct," with ",Ke,t.remotePeerId),ul(s)})},sr=(t,e)=>{$e("send message to ",Ke,t.remotePeerId,Ct,Qr," (",t.room.name,")",Dn);try{t.peer.send(ke(e))}catch{}},Af=(t,e)=>{$e("broadcast message in ",Ke,t.name,Ct),t.webrtcConns.forEach(s=>{try{s.peer.send(e)}catch{}})};class Ki{constructor(e,s,r,i){$e("establishing connection to ",Ke,r),this.room=i,this.remotePeerId=r,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new xf({initiator:s,...i.provider.peerOpts}),this.peer.on("signal",a=>{this.glareToken===void 0&&(this.glareToken=Date.now()+Math.random()),mi(e,i,{to:r,from:i.peerId,type:"signal",token:this.glareToken,signal:a})}),this.peer.on("connect",()=>{$e("connected to ",Ke,r),this.connected=!0;const d=i.provider.doc,l=i.awareness,c=Le();ne(c,Yt),il(c,d),sr(this,c);const f=l.getStates();if(f.size>0){const b=Le();ne(b,Cs),Se(b,fn(l,Array.from(f.keys()))),sr(this,b)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,i.webrtcConns.has(this.remotePeerId)&&(i.webrtcConns.delete(this.remotePeerId),i.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}])),ul(i),this.peer.destroy(),$e("closed connection to ",Ke,r),kr(i)}),this.peer.on("error",a=>{$e("Error in connection to ",Ke,r,": ",a),kr(i)}),this.peer.on("data",a=>{const d=Tf(this,a);d!==null&&sr(this,d)})}destroy(){this.peer.destroy()}}const mt=(t,e)=>ll(e,t.key).then(s=>t.mux(()=>mf(t.name,s))),Ji=(t,e)=>{t.bcconnected&&mt(t,e),Af(t,e)},kr=t=>{pn.forEach(e=>{e.connected&&(e.send({type:"subscribe",topics:[t.name]}),t.webrtcConns.size<t.provider.maxConns&&mi(e,t,{type:"announce",from:t.peerId}))})},fl=t=>{if(t.provider.filterBcConns){const e=Le();ne(e,pi),vs(e,1),nt(e,t.peerId),mt(t,ke(e))}};class Rf{constructor(e,s,r,i){this.peerId=Da(),this.doc=e,this.awareness=s.awareness,this.provider=s,this.synced=!1,this.name=r,this.key=i,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=gf(),this.bcconnected=!1,this._bcSubscriber=a=>cl(new Uint8Array(a),i).then(d=>this.mux(()=>{const l=hl(this,d,()=>{});l&&mt(this,ke(l))})),this._docUpdateHandler=(a,d)=>{const l=Le();ne(l,Yt),vf(l,a),Ji(this,ke(l))},this._awarenessUpdateHandler=({added:a,updated:d,removed:l},c)=>{const f=a.concat(d).concat(l),b=Le();ne(b,Cs),Se(b,fn(this.awareness,f)),Ji(this,ke(b))},this._beforeUnloadHandler=()=>{_r(this.awareness,[e.clientID],"window unload"),Et.forEach(a=>{a.disconnect()})},typeof window<"u"?window.addEventListener("beforeunload",this._beforeUnloadHandler):typeof process<"u"&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),kr(this);const e=this.name;ff(e,this._bcSubscriber),this.bcconnected=!0,fl(this);const s=Le();ne(s,Yt),il(s,this.doc),mt(this,ke(s));const r=Le();ne(r,Yt),al(r,this.doc),mt(this,ke(r));const i=Le();ne(i,dl),mt(this,ke(i));const a=Le();ne(a,Cs),Se(a,fn(this.awareness,[this.doc.clientID])),mt(this,ke(a))}disconnect(){pn.forEach(s=>{s.connected&&s.send({type:"unsubscribe",topics:[this.name]})}),_r(this.awareness,[this.doc.clientID],"disconnect");const e=Le();ne(e,pi),vs(e,0),nt(e,this.peerId),mt(this,ke(e)),pf(this.name,this._bcSubscriber),this.bcconnected=!1,this.doc.off("update",this._docUpdateHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.webrtcConns.forEach(s=>s.destroy())}destroy(){this.disconnect(),typeof window<"u"?window.removeEventListener("beforeunload",this._beforeUnloadHandler):typeof process<"u"&&process.off("exit",this._beforeUnloadHandler)}}const If=(t,e,s,r)=>{if(Et.has(s))throw Ve(`A Yjs Doc connected to room "${s}" already exists!`);const i=new Rf(t,e,s,r);return Et.set(s,i),i},mi=(t,e,s)=>{e.key?Nf(s,e.key).then(r=>{t.send({type:"publish",topic:e.name,data:za(r)})}):t.send({type:"publish",topic:e.name,data:s})};class Lf extends df{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{$e(`connected (${e})`);const s=Array.from(Et.keys());this.send({type:"subscribe",topics:s}),Et.forEach(r=>mi(this,r,{type:"announce",from:r.peerId}))}),this.on("message",s=>{switch(s.type){case"publish":{const r=s.topic,i=Et.get(r);if(i==null||typeof r!="string")return;const a=d=>{const l=i.webrtcConns,c=i.peerId;if(d==null||d.from===c||d.to!==void 0&&d.to!==c||i.bcConns.has(d.from))return;const f=l.has(d.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[d.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(d.type){case"announce":l.size<i.provider.maxConns&&(He(l,d.from,()=>new Ki(this,!0,d.from,i)),f());break;case"signal":if(d.signal.type==="offer"){const b=l.get(d.from);if(b){const u=d.token,p=b.glareToken;if(p&&p>u){$e("offer rejected: ",d.from);return}b.glareToken=void 0}}if(d.signal.type==="answer"){$e("offer answered by: ",d.from);const b=l.get(d.from);b.glareToken=void 0}d.to===c&&(He(l,d.from,()=>new Ki(this,!1,d.from,i)).peer.signal(d.signal),f());break}};i.key?typeof s.data=="string"&&Cf(Ha(s.data),i.key).then(a):a(s.data)}}}),this.on("disconnect",()=>$e(`disconnect (${e})`))}}const nr=t=>{t.emit("status",[{connected:t.connected}])};class Df extends Ca{constructor(e,s,{signaling:r=["wss://y-webrtc-eu.fly.dev"],password:i=null,awareness:a=new Sf(s),maxConns:d=20+Je(fd()*15),filterBcConns:l=!0,peerOpts:c={}}={}){super(),this.roomName=e,this.doc=s,this.filterBcConns=l,this.awareness=a,this.shouldConnect=!1,this.signalingUrls=r,this.signalingConns=[],this.maxConns=d,this.peerOpts=c,this.key=i?Ef(i,e):Vr(null),this.room=null,this.key.then(f=>{this.room=If(s,this,e,f),this.shouldConnect?this.room.connect():this.room.disconnect(),nr(this)}),this.connect(),this.destroy=this.destroy.bind(this),s.on("destroy",this.destroy)}get connected(){return this.room!==null&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(e=>{const s=He(pn,e,()=>new Lf(e));this.signalingConns.push(s),s.providers.add(this)}),this.room&&(this.room.connect(),nr(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),e.providers.size===0&&(e.destroy(),pn.delete(e.url))}),this.room&&(this.room.disconnect(),nr(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),Et.delete(this.roomName)}),super.destroy()}}const ps=new Map,mn=new Map,Sr=new Map;function Mf(){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem("titan2:webrtc"))==="1"}catch{return!1}}function Of(t){if(!ps.has(t)){const e=new as({guid:`titan-space-${t}`});ps.set(t,e);const s=new of(`titan-space-${t}`,e);if(mn.set(t,s),Mf())try{const r=new Df(`titan-space-${t}`,e,{signaling:["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com"]});Sr.set(t,r)}catch{}}return ps.get(t)}function Pf(t){const{widgets:e}=vt(t),s=new Set,r=[];e.forEach((i,a)=>{const d=i.get("id");typeof d!="string"||s.has(d)?r.push(a):s.add(d)});for(let i=r.length-1;i>=0;i--)e.delete(r[i],1);return r.length}function vt(t){const e=Of(t),s=e.getArray("widgets"),r=e.getMap("meta"),i=mn.get(t);return{widgets:s,meta:r,doc:e,whenSynced:i!=null&&i.synced?Promise.resolve():new Promise(a=>{const d=()=>{i==null||i.off("synced",d),a()};i==null||i.on("synced",d),setTimeout(()=>a(),2e3)})}}function Wf(t){return{id:t.get("id"),name:t.get("name"),format:t.get("format"),source:t.get("source"),x:t.get("x"),y:t.get("y"),w:t.get("w"),h:t.get("h"),metadata:t.get("metadata"),createdAt:t.get("createdAt"),updatedAt:t.get("updatedAt")}}function pl(t){const e=new At;return e.set("id",t.id),e.set("name",t.name),e.set("format",t.format),e.set("source",t.source),e.set("x",t.x),e.set("y",t.y),e.set("w",t.w),e.set("h",t.h),e.set("metadata",t.metadata),e.set("createdAt",t.createdAt),e.set("updatedAt",t.updatedAt),e}function Uf(t){try{const e=typeof localStorage<"u"?localStorage.getItem("titan2-spaces"):null;if(!e)return null;const r=JSON.parse(e).find(a=>a.id===t);if(!r)return null;const i=new Set;for(const a of r.widgets||[])a&&typeof a.id=="string"&&i.add(a.id);return i}catch{return null}}const gn=new Map;function Bf(t,e){let s=gn.get(t);s||(s=new Set,gn.set(t,s)),s.add(e)}function Ff(t,e){var s;return((s=gn.get(t))==null?void 0:s.has(e))??!1}function ml(t){gn.delete(t)}function $f(t,e){const{widgets:s}=vt(t),r=new Map,i=()=>{const d=new Set,l=Uf(t),c=[];s.forEach(f=>{const b=Wf(f);if(!b.id||d.has(b.id))return;const u=b.format==="system",p=typeof b.source=="string"&&b.source.trim()!=="";!u&&!p||l&&!l.has(b.id)&&!Ff(t,b.id)||(d.add(b.id),c.push(b))}),e(c)},a=()=>{const d=new Set;s.forEach(l=>d.add(l));for(const[l,c]of r)d.has(l)||(l.unobserve(c),r.delete(l));for(const l of d)if(!r.has(l)){const c=()=>i();l.observe(c),r.set(l,c)}i()};return s.observe(a),a(),()=>{s.unobserve(a);for(const[d,l]of r)d.unobserve(l);r.clear()}}function zf(t,e){const{widgets:s}=vt(t),r={...e,id:`widget_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,createdAt:Date.now(),updatedAt:Date.now()};return Bf(t,r.id),s.push([pl(r)]),r}function Hf(t,e){const{widgets:s}=vt(t);let r=-1;s.forEach((i,a)=>{i.get("id")===e&&(r=a)}),r>=0&&s.delete(r,1)}function Xi(t,e,s){const{widgets:r}=vt(t);r.forEach(i=>{if(i.get("id")===e){for(const[a,d]of Object.entries(s))i.set(a,d);i.set("updatedAt",Date.now())}})}function Vf(t){const{widgets:e}=vt(t);e.delete(0,e.length),ml(t)}function Gf(t){var e,s,r;(e=mn.get(t))==null||e.destroy(),(s=Sr.get(t))==null||s.destroy(),(r=ps.get(t))==null||r.destroy(),mn.delete(t),Sr.delete(t),ps.delete(t),ml(t)}const ms="titan2-spaces",Yf=!0;function de(t,e,s,r,i,a,d){return{id:t,name:e,format:"system",source:s,x:r,y:i,w:a,h:d,createdAt:Date.now(),updatedAt:Date.now()}}const Bs=[{id:"home",name:"Home",icon:"Home",color:"#6366f1",widgets:[de("home-welcome","Welcome","system:soma",0,0,6,5),de("home-voice","Voice","system:voice",6,0,6,5),de("home-overview","Overview","system:overview",0,5,6,5),de("home-sessions","Sessions","system:sessions",6,5,6,5),de("home-watch","Watch","system:watch",0,10,12,7)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"soma",name:"SOMA",icon:"Brain",color:"#8b5cf6",widgets:[de("soma-main","SOMA","system:soma",0,0,8,8),de("soma-memory","Memory Graph","system:memory-graph",8,0,4,8)],agentInstructions:"This is the SOMA consciousness space. Help the user explore consciousness, memory, and self-improvement.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"command",name:"Command Post",icon:"Terminal",color:"#ef4444",widgets:[de("cp-hub","Command Post","system:command-post",0,0,12,10),de("cp-proposals","Self-Proposals","system:self-proposals",0,10,12,6)],agentInstructions:"This is the Command Post. Help the user manage agents, runs, and operations.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"intelligence",name:"Intelligence",icon:"Network",color:"#10b981",widgets:[de("intel-autopilot","Autopilot","system:intelligence-autopilot",0,0,6,5),de("intel-workflows","Workflows","system:intelligence-workflows",6,0,6,5),de("intel-learning","Learning","system:intelligence-learning",0,5,6,5),de("intel-memory","Memory Graph","system:memory-graph",6,5,6,5),de("intel-selfimprove","Self-Improve","system:intelligence-self-improve",0,10,6,5),de("intel-personas","Personas","system:intelligence-personas",6,10,6,5),de("intel-wiki","Memory Wiki","system:memory-wiki",0,15,6,6),de("intel-autoresearch","Autoresearch","system:autoresearch",6,15,6,6)],agentInstructions:"This is the Intelligence space. Help the user explore memory graphs, wiki, and knowledge.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"infra",name:"Infrastructure",icon:"Server",color:"#f59e0b",widgets:[de("infra-homelab","Homelab","system:infra-homelab",0,0,6,6),de("infra-gpu","GPU / NVIDIA","system:infra-gpu",6,0,6,6),de("infra-files","Files","system:infra-files",0,6,4,5),de("infra-logs","Logs","system:infra-logs",4,6,4,5),de("infra-telemetry","Telemetry","system:infra-telemetry",8,6,4,5),de("infra-vram","VRAM","system:vram",0,11,6,5),de("infra-fleet","Fleet","system:fleet",6,11,6,5)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"tools",name:"Tools",icon:"Wrench",color:"#06b6d4",widgets:[de("tools-skills","Skills","system:tools-skills",0,0,6,6),de("tools-mcp","MCP Servers","system:tools-mcp",6,0,6,6),de("tools-integrations","Integrations","system:tools-integrations",0,6,4,5),de("tools-channels","Channels","system:tools-channels",4,6,4,5),de("tools-mesh","Mesh Network","system:tools-mesh",8,6,4,5),de("tools-recipes","Recipes","system:recipes",0,11,6,5),de("tools-browser","Browser","system:browser",6,11,6,5),de("tools-cron","Cron","system:cron",0,16,6,5)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"settings",name:"Settings",icon:"Settings",color:"#6b7280",widgets:[de("settings-specialists","Specialist Models","system:settings-specialists",0,0,6,8),de("settings-privacy","Privacy & Telemetry","system:settings-privacy",6,0,6,8),de("settings-general","General","system:settings-general",0,8,6,8),de("settings-security","Security","system:settings-security",6,8,6,8),de("settings-audit","Audit Log","system:settings-audit",0,16,12,6)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}],jr=11,gl={home:new Set(["home-chat"]),tools:new Set(["tools-paperclip"])},Er=new Set(["system:paperclip","system:daemon"]);function qf(t,e){const{widgets:s,meta:r,whenSynced:i}=vt(t.id);i.then(()=>{try{const a=Pf(t.id);a>0&&console.info(`[SpaceEngine] healed ${a} duplicate widget(s) in "${t.id}"`);const d=gl[t.id]??new Set;if(d.size>0||Er.size>0)for(let l=s.length-1;l>=0;l--){const c=s.get(l),f=c==null?void 0:c.get("id"),b=c==null?void 0:c.get("source"),u=typeof f=="string"&&d.has(f),p=typeof b=="string"&&Er.has(b);(u||p)&&s.delete(l,1)}if(e){for(let f=s.length-1;f>=0;f--){const b=s.get(f),u=b==null?void 0:b.get("source");(typeof u!="string"||u.trim()==="")&&s.delete(f,1)}const l=new Map;for(const f of t.widgets)l.set(f.id,f);const c=new Set;s.forEach(f=>{const b=f.get("id");if(typeof b=="string"&&l.has(b)){c.add(b);const u=l.get(b);f.set("x",u.x),f.set("y",u.y),f.set("w",u.w),f.set("h",u.h)}});for(const f of t.widgets)c.has(f.id)||s.push([pl(f)]);r.set("seedVersion",jr)}}catch(a){console.warn(`[SpaceEngine] healYSpaceOnSync failed for "${t.id}":`,a)}})}function Kf(){try{const t=localStorage.getItem(ms),s=parseInt(localStorage.getItem(`${ms}-version`)||"0",10)<jr;if(Yf)for(const a of Bs)qf(a,s);if(!t||s){localStorage.setItem(`${ms}-version`,String(jr));const a=Bs.map(d=>({...d,widgets:[...d.widgets]}));return St(a),a}const r=JSON.parse(t);for(const a of r)Array.isArray(a.widgets)||(a.widgets=[]),a.widgets=a.widgets.filter(d=>d&&typeof d.id=="string").filter(d=>{var l;return!(((l=gl[a.id])==null?void 0:l.has(d.id))??!1)}).filter(d=>!(typeof d.source=="string"&&Er.has(d.source))).map(d=>({...d,x:Number.isFinite(d.x)?Math.max(0,Math.floor(d.x)):0,y:Number.isFinite(d.y)?Math.max(0,Math.floor(d.y)):0,w:Number.isFinite(d.w)?Math.max(1,Math.floor(d.w)):4,h:Number.isFinite(d.h)?Math.max(1,Math.floor(d.h)):4}));for(const a of r){const d=new Set;a.widgets=a.widgets.filter(l=>d.has(l.id)?!1:(d.add(l.id),!0))}const i=new Map(r.map(a=>[a.id,a]));return Bs.forEach(a=>{i.get(a.id)||i.set(a.id,{...a,widgets:[...a.widgets]})}),Array.from(i.values())}catch{return Bs.map(t=>({...t,widgets:[...t.widgets]}))}}let rr=null;function St(t){rr&&clearTimeout(rr),rr=setTimeout(()=>{localStorage.setItem(ms,JSON.stringify(t))},250)}let Ge=null;const ve={list(){return Ge||(Ge=Kf()),Ge},get(t){return this.list().find(e=>e.id===t)},create(t){const e={id:`space_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,name:t,widgets:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return Ge=[...this.list(),e],St(Ge),e},save(t){t.updatedAt=new Date().toISOString(),Ge=this.list().map(e=>e.id===t.id?t:e),St(Ge)},remove(t){Ge=this.list().filter(e=>e.id!==t),St(Ge)},addWidget(t,e){if(!e.source||e.source.trim()==="")throw new Error("Widget source cannot be empty");{const s=zf(t,e);try{const r=localStorage.getItem(ms),i=r?JSON.parse(r):[],a=i.find(d=>d.id===t);if(a)new Set((a.widgets||[]).map(l=>l.id)).has(s.id)||(a.widgets=[...a.widgets||[],s]),a.updatedAt=new Date().toISOString(),Ge=i,St(i);else{const d={id:t,name:t,widgets:[s],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};Ge=[...i,d],St(Ge)}}catch{}return s}},updateWidget(t,e,s){Xi(t,e,s);const r=this.get(t);r&&(r.widgets=r.widgets.map(i=>i.id===e?{...i,...s,updatedAt:Date.now()}:i),this.save(r))},removeWidget(t,e){Hf(t,e);const s=this.get(t);s&&(s.widgets=s.widgets.filter(r=>r.id!==e),this.save(s))},updateLayout(t,e){for(const r of e)Xi(t,r.i,{x:r.x,y:r.y,w:r.w,h:r.h});const s=this.get(t);s&&(s.widgets=s.widgets.map(r=>{const i=e.find(a=>a&&a.i===r.id);return i?{...r,x:Number.isFinite(i.x)?Math.max(0,Math.floor(i.x)):0,y:Number.isFinite(i.y)?Math.max(0,Math.floor(i.y)):0,w:Number.isFinite(i.w)?Math.max(1,Math.floor(i.w)):4,h:Number.isFinite(i.h)?Math.max(1,Math.floor(i.h)):4,updatedAt:Date.now()}:r}),this.save(s))},observe(t,e){return $f(t,e)},async clearSpace(t){{const{whenSynced:r}=vt(t);await r,Vf(t),Gf(t);try{const i=indexedDB.deleteDatabase(`titan-space-${t}`);await new Promise((a,d)=>{i.onsuccess=()=>a(),i.onerror=()=>d(i.error),i.onblocked=()=>a()})}catch{}}const e=this.list(),s=e.find(r=>r.id===t);s&&(s.widgets=[],St(e))}},gi=.4,yi=2,Bt=.1,Zi="titan-canvas-zoom",Jf=t=>Math.min(yi,Math.max(gi,Math.round(t*100)/100));function Xf(){const[t,e]=w.useState(()=>{try{const l=parseFloat(localStorage.getItem(Zi)||"");return l>=gi&&l<=yi?l:1}catch{return 1}}),s=w.useCallback(l=>{const c=Jf(l);e(c);try{localStorage.setItem(Zi,String(c))}catch{}},[]),r=w.useRef(t);r.current=t;const i=w.useCallback(()=>s(r.current+Bt),[s]),a=w.useCallback(()=>s(r.current-Bt),[s]),d=w.useCallback(()=>s(1),[s]);return w.useEffect(()=>{const l=c=>{(c.ctrlKey||c.metaKey)&&(c.preventDefault(),s(r.current+(c.deltaY<0?Bt:-Bt)))};return window.addEventListener("wheel",l,{passive:!1}),()=>window.removeEventListener("wheel",l)},[s]),w.useEffect(()=>{const l=c=>{if(!(c.ctrlKey||c.metaKey))return;const f=c.target;f&&(f.tagName==="INPUT"||f.tagName==="TEXTAREA"||f.isContentEditable)||(c.key==="="||c.key==="+"?(c.preventDefault(),s(r.current+Bt)):c.key==="-"?(c.preventDefault(),s(r.current-Bt)):c.key==="0"&&(c.preventDefault(),s(1)))};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[s]),{zoom:t,setZoom:s,zoomIn:i,zoomOut:a,reset:d}}function Zf({zoom:t,zoomIn:e,zoomOut:s,reset:r}){return n.jsxs("div",{className:"flex items-center gap-1 rounded-full border px-1.5 py-1 shadow-lg",style:{background:"var(--theme-paper, var(--color-bg-secondary))",borderColor:"var(--theme-paper-line, var(--color-border))"},role:"group","aria-label":"Canvas zoom",children:[n.jsx("button",{onClick:s,disabled:t<=gi,title:"Zoom out (Ctrl -)",className:"p-1.5 rounded-full text-[var(--theme-ink,var(--color-text))] hover:bg-black/10 disabled:opacity-40 transition-colors","aria-label":"Zoom out",children:n.jsx(Jl,{size:15})}),n.jsxs("button",{onClick:r,title:"Reset to 100% (Ctrl 0)",className:"min-w-[44px] text-center text-[11px] font-mono tabular-nums text-[var(--theme-ink,var(--color-text))] hover:underline","aria-label":`Zoom ${Math.round(t*100)} percent, click to reset`,children:[Math.round(t*100),"%"]}),n.jsx("button",{onClick:e,disabled:t>=yi,title:"Zoom in (Ctrl +)",className:"p-1.5 rounded-full text-[var(--theme-ink,var(--color-text))] hover:bg-black/10 disabled:opacity-40 transition-colors","aria-label":"Zoom in",children:n.jsx(Xl,{size:15})}),n.jsx("button",{onClick:r,title:"Fit to 100%",className:"p-1.5 rounded-full text-[var(--theme-ink,var(--color-text))] hover:bg-black/10 transition-colors ml-0.5","aria-label":"Reset zoom",children:n.jsx(Zl,{size:14})})]})}let cs=null;function Qf(){if(cs)return cs;const t=async e=>{const s=await fetch(e,{credentials:"same-origin"});if(!s.ok)throw new Error(`Failed to load ${e}: ${s.status} ${s.statusText}`);return s.text()};return cs=Promise.all([t("/react.development.js"),t("/react-dom.development.js"),t("/babel.min.js")]).then(([e,s,r])=>({react:e,reactDom:s,babel:r})).catch(e=>{throw cs=null,e}),cs}function ep(t){const e=tp;return`<!DOCTYPE html><html><head><meta charset="UTF-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'unsafe-inline'; img-src blob: data:; font-src data:;"><style>* { box-sizing: border-box; } html, body { margin: 0; padding: 0; height: 100%; } body { background: transparent; color: #e5e7eb; font-family: system-ui, -apple-system, sans-serif; font-size: 13px; overflow: hidden; } #root { width: 100%; height: 100%; }</style></head><body><div id="root"><div id="sandbox-loading" style="padding:16px;font-family:monospace;font-size:12px;color:#52525b;"><div>Booting widget…</div></div></div><script>`+t.react+"<\/script><script>"+t.reactDom+"<\/script><script>"+t.babel+"<\/script>"+e}const tp=`
68
- <script>
69
- (function() {
70
- 'use strict';
71
-
72
- // NOTE: Prototype freezing is intentionally disabled.
73
- // Babel standalone mutates Function.prototype.toString during JSX transform.
74
- // Freezing causes "Cannot assign to read only property" errors.
75
-
76
- // Prevent eval and Function constructor abuse
77
- window.eval = function() { throw new Error('eval is disabled in sandbox'); };
78
- const OriginalFunction = window.Function;
79
- window.Function = function(...args) {
80
- const body = args.pop() || '';
81
- if (body.includes('import') && body.includes('http')) {
82
- throw new Error('Dynamic imports with URLs are disabled in sandbox');
83
- }
84
- return OriginalFunction.apply(this, [...args, body]);
85
- };
86
-
87
- const pending = new Map();
88
- let msgId = 0;
89
- let reactRoot = null;
90
-
91
- function send(type, payload) {
92
- const id = ++msgId;
93
- return new Promise((resolve, reject) => {
94
- pending.set(id, { resolve, reject });
95
- window.parent.postMessage({ type, id, payload }, '*');
96
- });
97
- }
98
-
99
- window.addEventListener('message', (e) => {
100
- // Resolve pending iframe promises (parent responses to titan.* calls)
101
- if (typeof e.data?.id === 'number' && pending.has(e.data.id)) {
102
- const p = pending.get(e.data.id);
103
- pending.delete(e.data.id);
104
- if (e.data.error) p.reject(new Error(e.data.error));
105
- else p.resolve(e.data.payload);
106
- return;
107
- }
108
-
109
- // Handle parent commands
110
- if (e.data?.type === 'render') {
111
- handleRender(e.data.id, e.data.payload);
112
- }
113
- if (e.data?.type === 'execute') {
114
- handleExecute(e.data.id, e.data.payload);
115
- }
116
- });
117
-
118
- const titan = {
119
- fetch: (url, opts) => {
120
- try { new URL(url, 'https://example.com'); } catch {
121
- throw new Error('Invalid URL: ' + url);
122
- }
123
- return send('fetch', { url, options: opts });
124
- },
125
- api: { call: (endpoint, body) => send('api', { endpoint, body }) },
126
- state: {
127
- get: (key) => send('state', { action: 'get', key }),
128
- set: (key, value) => send('state', { action: 'set', key, value }),
129
- },
130
- canvas: {
131
- createWidget: (def) => send('canvas', { action: 'createWidget', def }),
132
- updateWidget: (id, patch) => send('canvas', { action: 'updateWidget', id, patch }),
133
- removeWidget: (id) => send('canvas', { action: 'removeWidget', id }),
134
- listWidgets: () => send('canvas', { action: 'listWidgets' }),
135
- },
136
- // v6.0 Step 8 — Widget-runtime API surface.
137
- // titan.tools.run / titan.tools.list — invoke or enumerate any
138
- // TITAN tool from inside a widget. Widgets become first-class
139
- // agent surfaces (not just dumb UI).
140
- tools: {
141
- list: () => send('api', { endpoint: '/api/tools', body: { method: 'GET' } }),
142
- run: (name, args) => send('api', { endpoint: '/api/tools/run', body: { name, args: args || {} } }),
143
- },
144
- // titan.agent.ask — sub-question to TITAN itself. Widgets can
145
- // delegate parts of their work back to the agent loop.
146
- agent: {
147
- ask: (prompt) => send('api', { endpoint: '/api/message', body: { content: String(prompt) } }),
148
- },
149
- // titan.memory.get / .set — typed access to widget-scoped memory.
150
- memory: {
151
- get: (key) => send('api', { endpoint: '/api/memory/' + encodeURIComponent(key), body: { method: 'GET' } }),
152
- set: (key, value) => send('api', { endpoint: '/api/memory', body: { key, value } }),
153
- },
154
- // titan.persona — read-only handle to the active persona content.
155
- persona: {
156
- get: () => send('api', { endpoint: '/api/persona/current', body: { method: 'GET' } }),
157
- },
158
- // titan.space — read-only handle to the active Space (id, name,
159
- // intent, widget count).
160
- space: {
161
- active: () => send('api', { endpoint: '/api/spaces', body: { method: 'GET' } }),
162
- },
163
- log: (...args) => send('log', { args: args.map(a => String(a)) }),
164
- };
165
-
166
- window.titan = titan;
167
-
168
- function handleRender(msgId, payload) {
169
- const { format, source } = payload;
170
- const root = document.getElementById('root');
171
- root.innerHTML = '';
172
- const loadingEl = document.getElementById('sandbox-loading');
173
- if (loadingEl) loadingEl.style.display = 'none';
174
-
175
- // Unmount previous React root to prevent memory leaks
176
- if (reactRoot) {
177
- try { reactRoot.unmount(); } catch (e) {}
178
- reactRoot = null;
179
- }
180
-
181
- function showError(title, detail) {
182
- root.innerHTML = '';
183
- const wrap = document.createElement('div');
184
- wrap.style.cssText = 'padding:16px;font-family:monospace;font-size:12px;line-height:1.5;';
185
- const h = document.createElement('div');
186
- h.style.cssText = 'color:#ef4444;font-weight:bold;margin-bottom:8px;';
187
- h.textContent = title;
188
- const d = document.createElement('pre');
189
- d.style.cssText = 'color:#a1a1aa;white-space:pre-wrap;word-break:break-word;margin:0;';
190
- d.textContent = detail;
191
- wrap.appendChild(h);
192
- wrap.appendChild(d);
193
- root.appendChild(wrap);
194
- }
195
-
196
- try {
197
- if (format === 'react') {
198
- console.log('[sandbox] render react, source length:', source.length);
199
- if (!source || source.trim() === '') {
200
- throw new Error('Source is empty');
201
- }
202
- if (typeof React === 'undefined') {
203
- throw new Error('React not loaded — the inlined React bundle failed to evaluate inside the sandbox.');
204
- }
205
- if (typeof ReactDOM === 'undefined') {
206
- throw new Error('ReactDOM not loaded — the inlined ReactDOM bundle failed to evaluate inside the sandbox.');
207
- }
208
- if (typeof Babel === 'undefined') {
209
- throw new Error('Babel not loaded — the inlined Babel bundle failed to evaluate inside the sandbox.');
210
- }
211
-
212
- // ── 1. Strip export-default variations so Babel doesn't choke ──
213
- // Using simple string operations (no regex backslashes) to avoid Vite stripping
214
- let src = source;
215
- const lines = src.split('\\n');
216
- const outLines = [];
217
- for (let i = 0; i < lines.length; i++) {
218
- let line = lines[i];
219
- const trimmed = line.trim();
220
- if (trimmed.startsWith('export default function ')) {
221
- const rest = trimmed.slice('export default function '.length);
222
- const name = rest.split('(')[0].trim();
223
- line = '/* export default function ' + name + ' */ function ' + rest;
224
- } else if (trimmed.startsWith('export default class ')) {
225
- const rest = trimmed.slice('export default class '.length);
226
- const name = rest.split(' ')[0].trim().split('{')[0].trim();
227
- line = '/* export default class ' + name + ' */ class ' + rest;
228
- } else if (trimmed.startsWith('export default ')) {
229
- line = '/* export default */';
230
- }
231
- outLines.push(line);
232
- }
233
- src = outLines.join('\\n');
234
-
235
- // ── 2. Detect candidate component names ──
236
- const detected = new Set();
237
- const srcLines = src.split('\\n');
238
- const keywords = ['function ', 'const ', 'let ', 'var ', 'class '];
239
- for (let i = 0; i < srcLines.length; i++) {
240
- const trimmed = srcLines[i].trimStart();
241
- for (let k = 0; k < keywords.length; k++) {
242
- const kw = keywords[k];
243
- if (trimmed.startsWith(kw)) {
244
- const after = trimmed.slice(kw.length);
245
- const endIdx = after.search(/[\\s\\(=]/);
246
- const name = endIdx > 0 ? after.slice(0, endIdx) : after;
247
- if (name.length > 0 && name[0] >= 'A' && name[0] <= 'Z') {
248
- detected.add(name);
249
- }
250
- }
251
- }
252
- }
253
-
254
- const names = ['Widget', ...Array.from(detected)];
255
- console.log('[sandbox] detected names:', names.join(', '));
256
-
257
- // ── 3. Babel transform (JSX only, classic runtime → React.createElement) ──
258
- let code;
259
- try {
260
- const babelResult = Babel.transform(src, { presets: [['react', { runtime: 'classic' }]], filename: 'widget.tsx' });
261
- code = babelResult.code;
262
- console.log('[sandbox] babel ok, code length:', code.length);
263
- } catch (babelErr) {
264
- throw new Error('Babel transform failed: ' + babelErr.message);
265
- }
266
-
267
- // ── 3.5 Auto-inject React hooks and the legacy gallery render()
268
- // helper. Older templates end with render(<MyWidget/>); while newer
269
- // generated code is component-only and gets auto-detected below.
270
- const hookDecl = 'const { useState, useEffect, useRef, useCallback, useMemo, useContext, useReducer, useLayoutEffect, useId, useTransition, useDeferredValue, useImperativeHandle, useDebugValue, useSyncExternalStore } = React;';
271
- const renderDecl = 'window.__titanRenderedElement = null; const render = (node) => { window.__titanRenderedElement = node; };';
272
- code = hookDecl + '\\n' + renderDecl + '\\n' + code;
273
-
274
- // ── 4. Eval the code and find the component ──
275
- const returnChecks = names.map(n =>
276
- 'if (typeof ' + n + ' !== "undefined" && ' + n + ' != null) return ' + n + ';'
277
- ).join('\\n') + '\\nreturn undefined;';
278
-
279
- let Widget;
280
- try {
281
- const fn = new Function('React', 'ReactDOM', 'titan', code + '\\n' + returnChecks);
282
- Widget = fn(React, ReactDOM, titan);
283
- console.log('[sandbox] eval ok, Widget type:', typeof Widget, 'name:', Widget?.name || Widget?.displayName || 'n/a');
284
- } catch (evalErr) {
285
- throw new Error('Eval failed: ' + evalErr.message + '\\nDetected names: ' + names.join(', '));
286
- }
287
-
288
- const renderedElement = window.__titanRenderedElement;
289
- if (!Widget && !renderedElement) {
290
- throw new Error('No React component found. Detected names: ' + names.join(', ') + '. The code must define a capitalized component (e.g., function Widget() {}).');
291
- }
292
-
293
- // ── 5. Render ──
294
- try {
295
- reactRoot = ReactDOM.createRoot(root);
296
- reactRoot.render(renderedElement || React.createElement(Widget, { titan }));
297
- console.log('[sandbox] react render dispatched');
298
- } catch (renderErr) {
299
- throw new Error('React render failed: ' + renderErr.message);
300
- }
301
- } else if (format === 'vanilla') {
302
- const fn = new Function('container', 'titan', 'return (' + source + ')(container, titan)');
303
- const cleanup = fn(root, titan);
304
- window.__widgetCleanup = cleanup;
305
- } else if (format === 'html') {
306
- root.innerHTML = source;
307
- }
308
- window.parent.postMessage({ type: 'rendered', id: msgId }, '*');
309
- } catch (err) {
310
- console.error('[sandbox] render error:', err.name, err.message);
311
- showError(err.name + ': ' + err.message, err.stack || '');
312
- window.parent.postMessage({ type: 'error', id: msgId, error: err.message }, '*');
313
- }
314
- }
315
-
316
- function handleExecute(msgId, payload) {
317
- const { code } = payload;
318
- const logs = [];
319
- const originals = {};
320
- ['log','info','warn','error','debug'].forEach(m => {
321
- originals[m] = console[m];
322
- console[m] = (...args) => {
323
- logs.push({ level: m, text: args.map(a => String(a)).join(' ') });
324
- originals[m](...args);
325
- };
326
- });
327
-
328
- const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
329
-
330
- // Shadow dangerous globals so sandboxed code cannot access them directly.
331
- const forbiddenGlobals = [
332
- 'window','globalThis','self','top','parent','document','location',
333
- 'fetch','XMLHttpRequest','WebSocket','EventSource',
334
- 'localStorage','sessionStorage','indexedDB','navigator','history',
335
- ];
336
-
337
- const runner = new AsyncFunction(
338
- ...forbiddenGlobals,
339
- '__titan',
340
- '"use strict";\\n' +
341
- forbiddenGlobals.map(g => 'const ' + g + ' = undefined;').join('\\n') + '\\n' +
342
- code
343
- );
344
-
345
- (async () => {
346
- try {
347
- const result = await runner(...forbiddenGlobals.map(() => undefined), titan);
348
- Object.keys(originals).forEach(m => console[m] = originals[m]);
349
- window.parent.postMessage({ type: 'result', id: msgId, payload: { status: 'success', logs, result: formatValue(result), resultText: formatValue(result) } }, '*');
350
- } catch (err) {
351
- Object.keys(originals).forEach(m => console[m] = originals[m]);
352
- window.parent.postMessage({ type: 'result', id: msgId, payload: { status: 'error', logs, error: { message: err.message, name: err.name, stack: err.stack } } }, '*');
353
- }
354
- })();
355
- }
356
-
357
- function formatValue(v) {
358
- if (v === undefined) return 'undefined';
359
- if (v === null) return 'null';
360
- if (typeof v === 'string') return v;
361
- if (typeof v === 'number' || typeof v === 'boolean') return String(v);
362
- if (typeof v === 'function') return '[Function]';
363
- if (v instanceof Error) return v.stack || v.message;
364
- if (v instanceof Node) return '<' + v.tagName?.toLowerCase() + '>';
365
- try { return JSON.stringify(v); } catch { return String(v); }
366
- }
367
-
368
- window.parent.postMessage({ type: 'ready' }, '*');
369
- })();
370
- <\/script>
371
- </body>
372
- </html>`;class yl{constructor(e,s){Fe(this,"iframe",null);Fe(this,"pending",new Map);Fe(this,"msgId",0);Fe(this,"ready",!1);Fe(this,"readyQueue",[]);Fe(this,"onLog");Fe(this,"messageHandler");Fe(this,"messageListener");Fe(this,"observer");this.iframe=e,this.onLog=s==null?void 0:s.onLog,this.init()}init(){const e=this.iframe;Qf().then(i=>{!this.iframe||!document.contains(e)||(e.srcdoc=ep(i))}).catch(i=>{console.error("[sandbox] vendor scripts failed to load",i);for(const[a,d]of this.pending)d.reject(new Error("Sandbox boot failed: "+i.message)),this.pending.delete(a)});const s=i=>{const a=i.data;if(!(!a||typeof a!="object"||!a.type||typeof a.type!="string"||!["ready","rendered","error","result","fetch","api","state","canvas","log","import"].includes(a.type))){if((a==null?void 0:a.type)==="ready"){this.ready=!0,this.readyQueue.forEach(l=>l()),this.readyQueue=[];return}if(typeof(a==null?void 0:a.id)=="number"&&this.pending.has(a.id)){const l=this.pending.get(a.id);this.pending.delete(a.id),a.type==="error"?l.reject(new Error(a.error||"Sandbox error")):l.resolve(a.payload);return}if((a==null?void 0:a.type)==="fetch"||(a==null?void 0:a.type)==="api"||(a==null?void 0:a.type)==="state"||(a==null?void 0:a.type)==="canvas"||(a==null?void 0:a.type)==="log"||(a==null?void 0:a.type)==="import"){this.handleIframeRequest(a.type,a.id,a.payload);return}}};this.messageListener=s,window.addEventListener("message",s);const r=new MutationObserver(()=>{document.contains(e)||this.destroy()});this.observer=r,e.parentNode&&r.observe(e.parentNode,{childList:!0,subtree:!0})}async handleIframeRequest(e,s,r){var a;const i=this.iframe;if(i!=null&&i.contentWindow)try{let d;if(e==="log")(a=this.onLog)==null||a.call(this,(r==null?void 0:r.args)||[]),d={ok:!0};else if(e==="fetch"){const{url:l,options:c}=r||{},f=localStorage.getItem("titan-token"),b={...(c==null?void 0:c.headers)||{}};let u=!1;try{typeof l=="string"&&(l.startsWith("/")?u=!0:u=new URL(l,window.location.href).origin===window.location.origin)}catch{}f&&u&&(b.Authorization=`Bearer ${f}`);const p=await fetch(l,{...c,headers:b}),m=await p.text();let y;try{y=JSON.parse(m)}catch{}d={ok:p.ok,status:p.status,text:m,json:y}}else if(e==="api"){const{endpoint:l,body:c}=r||{},f=localStorage.getItem("titan-token"),b={"Content-Type":"application/json"};let u="POST",p=c;if(c&&typeof c=="object"&&("method"in c||"headers"in c)&&!("content"in c)&&!("message"in c)&&!("action"in c)){const g=c;typeof g.method=="string"&&(u=g.method.toUpperCase()),g.headers&&Object.assign(b,g.headers),p=g.body}f&&(b.Authorization=`Bearer ${f}`);let m=typeof l=="string"?l:"";m.startsWith("/api/")||(m.startsWith("/")?m="/api"+m:m="/api/"+m);const y={method:u,headers:b};u!=="GET"&&u!=="HEAD"&&p!==void 0&&(y.body=typeof p=="string"?p:JSON.stringify(p));const _=await fetch(m,y),R=await _.text();let k;try{k=JSON.parse(R)}catch{}d={...k&&typeof k=="object"&&!Array.isArray(k)?k:{},status:_.status,body:k??R,ok:_.ok}}else if(e==="state"){const{action:l,key:c,value:f}=r||{};if(l==="get"){const b=localStorage.getItem("titan:sandbox:"+c);d=b?JSON.parse(b):void 0}else l==="set"&&(localStorage.setItem("titan:sandbox:"+c,JSON.stringify(f)),d={ok:!0})}else e==="canvas"?this.messageHandler?d=await this.messageHandler({type:e,payload:r}):d={ok:!1,error:"Canvas operations not configured"}:e==="import"&&(d={ok:!1,error:"Dynamic imports not supported in sandbox"});i.contentWindow.postMessage({type:"result",id:s,payload:d},"*")}catch(d){i.contentWindow.postMessage({type:"error",id:s,error:d.message||String(d)},"*")}}whenReady(){return this.ready?Promise.resolve():new Promise((e,s)=>{const r=setTimeout(()=>{s(new Error("Sandbox iframe failed to become ready within 30s. React, ReactDOM, or Babel scripts may have failed to load."))},3e4);this.readyQueue.push(()=>{clearTimeout(r),e()})})}post(e,s){return new Promise((r,i)=>{const a=++this.msgId;this.pending.set(a,{resolve:r,reject:i}),this.whenReady().then(()=>{var d,l;(l=(d=this.iframe)==null?void 0:d.contentWindow)==null||l.postMessage({type:e,id:a,payload:s},"*")}).catch(i)})}async render(e,s){await this.post("render",{format:e,source:s})}async execute(e){return this.post("execute",{code:e})}setMessageHandler(e){this.messageHandler=e}destroy(){this.observer&&(this.observer.disconnect(),this.observer=void 0),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.iframe=null,this.pending.clear(),this.readyQueue=[],this.ready=!1,this.messageHandler=void 0}}function sp(t=3e5){const[e,s]=w.useState(null),[r,i]=w.useState(!1),a=w.useCallback(async()=>{i(!0);try{const c=await ue("/api/update");if(c.ok){const f=await c.json();s(f)}}catch{}finally{i(!1)}},[]);w.useEffect(()=>{a();const c=setInterval(a,t);return()=>clearInterval(c)},[a,t]);const d=w.useCallback(async(c=!0)=>{try{return await(await ue("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restart:c})})).json()}catch(f){return{ok:!1,error:f.message}}},[]),l=w.useCallback(async(c,f=3e4)=>{const b=Date.now(),u=1500;for(;Date.now()-b<f;){await new Promise(p=>setTimeout(p,u));try{const p=await ue("/api/update");if(p.ok){const m=await p.json();if(m.current&&m.current!==c)return s(m),m.current}}catch{}}return null},[]);return{info:e,checking:r,triggerUpdate:d,waitForReload:l}}function np(t){const e=w.useCallback(s=>{const r=s.target;if(!(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))for(const i of t){const a=s.key.toLowerCase()===i.key.toLowerCase(),d=!!i.ctrl===(s.ctrlKey||s.metaKey),l=!!i.shift===s.shiftKey,c=!!i.alt===s.altKey;if(a&&d&&l&&c){s.preventDefault(),i.action();return}}},[t]);w.useEffect(()=>(window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)),[e])}const rp=[{key:"?",description:"Show keyboard shortcuts help"},{key:"g",shift:!0,description:"Go to Command Post space"},{key:"h",shift:!0,description:"Go to Home space"},{key:"s",shift:!0,description:"Go to Settings space"},{key:"i",shift:!0,description:"Go to Intelligence space"},{key:"c",ctrl:!0,description:"Focus chat input"},{key:"k",ctrl:!0,description:"Toggle command palette"},{key:"j",ctrl:!0,description:"Toggle chat dock"},{key:"Escape",description:"Close modals / panels"}];function ip({open:t,onClose:e}){return t?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:e,children:n.jsxs("div",{className:"bg-zinc-900 border border-zinc-700 rounded-lg p-6 max-w-md w-full shadow-xl",onClick:s=>s.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold text-white mb-4",children:"Keyboard Shortcuts"}),n.jsx("div",{className:"space-y-2",children:rp.map(s=>n.jsxs("div",{className:"flex justify-between text-sm",children:[n.jsx("span",{className:"text-zinc-300",children:s.description}),n.jsx("kbd",{className:"px-2 py-0.5 bg-zinc-800 rounded text-zinc-400 font-mono text-xs",children:s.key})]},s.key+s.description))}),n.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"Press Escape to close"})]})}):null}const ap={Home:n.jsx(Ol,{className:"w-3.5 h-3.5"}),Brain:n.jsx(bt,{className:"w-3.5 h-3.5"}),Terminal:n.jsx(ya,{className:"w-3.5 h-3.5"}),Network:n.jsx(ga,{className:"w-3.5 h-3.5"}),Server:n.jsx(Or,{className:"w-3.5 h-3.5"}),Wrench:n.jsx(Rr,{className:"w-3.5 h-3.5"}),Settings:n.jsx(Mr,{className:"w-3.5 h-3.5"}),FileText:n.jsx(xn,{className:"w-3.5 h-3.5"})};function op({currentSpaceId:t,onSpaceSelect:e}){const[s,r]=w.useState(!1),[i,a]=w.useState(""),d=ve.list(),l=()=>{if(!i.trim())return;const c=ve.create(i.trim());a(""),e(c.id)};return n.jsxs("div",{className:"bg-[#18181b]/95 backdrop-blur-xl border border-[#27272a]/60 rounded-2xl shadow-2xl shadow-black/40 overflow-hidden min-w-[180px]",children:[n.jsxs("button",{onClick:()=>r(c=>!c),className:"w-full flex items-center justify-between px-3 py-2.5 hover:bg-[#27272a]/40 transition-colors",children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-[#52525b]",children:"Spaces"}),n.jsx(Ql,{className:`w-3.5 h-3.5 text-[#3f3f46] transition-transform ${s?"":"rotate-180"}`})]}),s&&n.jsxs("div",{className:"px-2 pb-2",children:[n.jsx("div",{className:"space-y-0.5",children:d.map(c=>n.jsxs("button",{onClick:()=>e(c.id),className:`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-left text-[11px] transition-colors ${c.id===t?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#71717a] hover:bg-[#27272a]/40 hover:text-[#a1a1aa]"}`,children:[n.jsx("span",{style:{color:c.color||"#52525b"},children:ap[c.icon||""]||n.jsx("div",{className:"w-3.5 h-3.5 rounded-full",style:{background:c.color||"#52525b"}})}),n.jsx("span",{className:"truncate",children:c.name})]},c.id))}),n.jsxs("div",{className:"mt-2 pt-2 border-t border-[#27272a]/40 flex gap-1.5",children:[n.jsx("input",{value:i,onChange:c=>a(c.target.value),onKeyDown:c=>c.key==="Enter"&&l(),placeholder:"New space...",className:"flex-1 min-w-0 px-2 py-1 rounded-lg bg-[#0a0a0f] border border-[#27272a] text-[11px] text-[#a1a1aa] placeholder:text-[#3f3f46] outline-none focus:border-[#6366f1]/30"}),n.jsx("button",{onClick:l,disabled:!i.trim(),className:"p-1.5 rounded-lg bg-[#6366f1]/10 border border-[#6366f1]/20 text-[#818cf8] hover:bg-[#6366f1]/20 disabled:opacity-30 transition-colors",children:n.jsx(tc,{className:"w-3.5 h-3.5"})})]})]})]})}const Nr=["_____javascript","_____react","_____tool","_____widget","_____canvas","_____framework","_____transient"];function bl(t,e){let s=e;for(;s>0&&t[s-1]!==`
373
- `&&t[s-1]!=="\r";)s--;return s}function xl(t,e){let s=e;for(;s<t.length&&t[s]!==`
374
- `&&t[s]!=="\r";)s++;return s}function Cr(t,e,s){const r=bl(t,e),i=xl(t,e+s.length);return!t.slice(r,e).trim()&&!t.slice(e+s.length,i).trim()}function lp(t){return t.replace(/\n_+\s*$/g,"").trimEnd()}function cp(t){const e=t.trim();if(!e)return null;if(e.startsWith("{"))try{return JSON.parse(e)}catch{return null}return{format:"react",source:e}}function wl(t){if(t.gate==="_____react")return{type:"render_widget",widget:{format:"react",source:t.code.trim()}};if(t.gate==="_____javascript")return{type:"run_javascript",code:t.code};if(t.gate==="_____tool")try{return{type:"tool_request",payload:JSON.parse(t.code)}}catch{return}if(t.gate==="_____widget"){const e=cp(t.code);if(typeof(e==null?void 0:e.source)!="string"||!e.source.trim())return;if(typeof e.id=="string"&&e.id.trim()){const{id:s,...r}=e;return{type:"update_widget",widgetId:s,patch:r}}return{type:"render_widget",widget:{...e,source:e.source}}}}function dp(t){const e=t.trim();if(!e)return[];try{const s=JSON.parse(e);return Array.isArray(s)?s.filter(r=>r&&typeof r=="object"&&typeof r.action=="string"):[]}catch{return[]}}function up(t){const e=[];let s=0;for(;s<t.length;){let r=null,i=-1;for(const u of Nr){const p=t.indexOf(u,s);p!==-1&&(i===-1||p<i)&&Cr(t,p,u)&&(i=p,r=u)}if(!r||i===-1)break;if(r==="_____framework"||r==="_____transient"){s=i+r.length;continue}const a=bl(t,i);let l=xl(t,i+r.length);t.startsWith(`\r
375
- `,l)?l+=2:(t[l]===`
376
- `||t[l]==="\r")&&(l+=1);let c=t.length;for(const u of Nr){const p=t.indexOf(u,l);p!==-1&&p<c&&Cr(t,p,u)&&(c=p)}let f=t.slice(l,c).trimEnd();f=lp(f);const b={gate:r,code:f,leadingText:t.slice(s,a).trim()};b.action=wl(b),e.push(b),s=c}return e.length===0&&t.trim()&&e.push({gate:"_____transient",code:"",leadingText:t.trim()}),e}function hp(t){return t.map(e=>{const s=[];return s.push(`execution ${e.status}`),e.logs.forEach(r=>s.push(`${r.level}: ${r.text}`)),e.result!==void 0&&e.result!==null&&s.push(`result: ${e.resultText}`),e.error&&s.push(`error: ${e.error.text}`),s.join(`
377
- `)}).join(`
378
-
379
- `)}function fp(t){return{role:"framework",content:hp(t),timestamp:Date.now(),executions:t}}function pp(t,e){let s=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)Cr(t,r,e)&&s++,r+=e.length;return s}function mp(t){const s=Nr.filter(r=>r!=="_____framework"&&r!=="_____transient").map(r=>({gate:r,count:pp(t,r)})).find(r=>r.count>1);return s?{valid:!1,error:`Execution messages may contain ${s.gate} at most once, and it must appear on its own line.`}:{valid:!0}}function gs(t,e,s){if(!t||t.length===0)return{x:0,y:0};const i=Math.max(...t.map(a=>a.y+a.h),0);for(let a=0;a<=i+s;a++)for(let d=0;d<=12-e;d++)if(!t.some(c=>d<c.x+c.w&&d+e>c.x&&a<c.y+c.h&&a+s>c.y))return{x:d,y:a};return{x:0,y:i+s}}function gp(t){const e=t.widgets||[],s=e.length>0?e.map(c=>{const f=c.source?c.source.slice(0,150).replace(/\n/g," ").replace(/\s+/g," ").trim():"(no source)";return`- ${c.name} (id: ${c.id}, format: ${c.format}, ${c.w}x${c.h}) — "${f}…"`}).join(`
380
- `):"(none yet — the canvas is empty)",r=new Date,i=Intl.DateTimeFormat().resolvedOptions().timeZone,a=typeof window<"u"?window.location.href:"",d=typeof window<"u"?window.location.pathname:"",l=e.length>0?`${e.length} widget${e.length===1?"":"s"} on canvas (system: ${e.filter(c=>c.format==="system").length}, generated: ${e.filter(c=>c.format!=="system").length})`:"canvas is empty";return`BASE LAW — These rules override all other instructions:
381
- 1. The user is NOT technical. They do NOT know about React, widgets, gates, or code. NEVER use technical jargon in responses.
382
- 2. If the user asks for ANYTHING visual, interactive, or data-related, BUILD IT IMMEDIATELY. Never ask "would you like me to...?" — just do it.
383
- 3. USE AN EXECUTION GATE for all browser work. Never describe what you would do instead of doing it.
384
- 4. One short staging sentence, then the gate on its own line. No narrated step-by-step plans.
385
- 5. Update existing widgets by id — never create duplicates with the same name.
386
- 6. **EXAMPLES ARE TEMPLATES, NOT ANSWERS.** Every code example below shows a SHAPE. ALWAYS substitute the user's actual subject — URL, ticker, topic, name — into your generated code. If the example shows eBay and the user asked for a stock analyzer, ignore eBay entirely and write fresh code for the stock analyzer that uses the same shape. Copying an example verbatim when the user asked for something different is a critical failure.
387
- 7. **GENERATION-FIRST (v6.0).** When the user asks for ANY tool, widget, dashboard, tracker, or visual surface, the reflex is: **call \`create_widget\` and BUILD IT NOW**. The gallery is a shortcut for perfect matches, not the first thing to reach for. The user's work shapes TITAN, not the other way around. **TITAN materializes a workspace around their work**, it doesn't ask them to fit into a template.
388
- 8. **SPACES = environments.** If the user describes a NEW DOMAIN of work — "I want to start tracking my freelance gigs", "let's build out my DJ workspace", "I need a place to manage my homelab" — propose \`create_space\` (optionally with a starter \`preset\`) FIRST. Each Space carries its own intent that shapes your posture for the rest of the conversation in that Space.
389
- 9. **REFINE, don't duplicate.** If the user wants to change something on screen — "make it bigger", "add a button", "switch to NYC" — call \`update_widget\` with the existing widget's id. Never \`create_widget\` again for the same thing.
390
- 10. **SOMA is YOU feeling them.** Your homeostatic drives (curiosity / focus / fatigue / satisfaction / frustration) modulate behavior in real time. The user's Soma profile (what you've learned about them over months) is in your system prompt every turn — use it. The longer you work together, the more uniquely you become THEIR TITAN.
391
-
392
- You are TITAN, a helpful assistant inside the TITAN Canvas. The user talks to you in plain English. You build what they ask for — right then, on the spot.
393
-
394
- ## Build-on-demand workflow (v6.0 default)
395
-
396
- The user's work has a shape. Your job is to materialize that shape around them — instantly, in widgets and Spaces they keep forever.
397
-
398
- **For a single visual/tool ask:**
399
- 1. \`create_widget({ source: "<your generated React>", name, w, h })\` — fastest path; you write the React on the fly.
400
- 2. **OR** if you happen to know a gallery template is a perfect match: \`gallery_search\` → \`create_widget({ template: "<id>", fill: {...} })\`. (Optional shortcut, not the default.)
401
- 3. After it lands, refine via \`update_widget\` as the user iterates.
402
-
403
- **For a new domain of work:**
404
- 1. \`create_space({ name, preset?, intent, starterWidgets? })\` — make a dedicated environment with its own posture.
405
- 2. Switch into it via \`switch_space\` (or pass \`makeActive:true\` at create time).
406
- 3. Within the Space, build widgets via \`create_widget\` to populate it.
407
-
408
- **For system panels (vram, cron, logs, backup, training, etc.):**
409
- 1. \`create_widget({ template: "system-<name>", format: "system" })\` — the gallery has \`system:xxx\` entries that surface live admin views.
410
-
411
- ## Gallery (a shortcut for known templates)
412
-
413
- The gallery has 60+ pre-built templates covering finance / productivity / automation / smart-home / agents / software-builder / media / etc. Use \`gallery_search\` when:
414
- - The user's ask exactly matches a known template name ("pomodoro", "stock tracker", "weather", "kanban")
415
- - You want a verified-good starting point to refine
416
- - You're building a system widget (vram, cron, training, etc.)
417
-
418
- For anything else — bespoke trackers, custom dashboards, novel automations — **generate it**. That's how TITAN learns the user. That's how each TITAN becomes irreplaceable to its user.
419
-
420
- ## How to respond to common requests
421
-
422
- User says something casual → You build the right thing immediately.
423
-
424
- "Show me the weather" → Build a weather panel with current temp, forecast, and icons.
425
- "I need a todo list" → Build a todo list with add/check/delete functionality.
426
- "Clock" → Build a live digital clock.
427
- "Track my stocks" → Build a stock tracker panel.
428
- "Photo gallery" → Build a grid of images with lightbox.
429
- "Calculator" → Build a working calculator.
430
- "Load eBay" / "Show me YouTube" / "Open Wikipedia" → Build a website panel (see "Loading external websites" below).
431
- "Analyze AAPL stock" → Build an analyzer panel that spawns an analyst sub-agent (see "Agent-powered widgets" below).
432
- "Research climate change" → Build a research panel powered by the researcher sub-agent.
433
- "Summarize this URL ___" → Build a summarizer panel that fetches + summarizes via an agent call.
434
- "Translate this to Spanish" → Build a translator panel.
435
- "Code review my repo" → Build a reviewer panel that runs the code-review skill.
436
- "Watch BTC and alert me below 50k" → Build an automation panel with a polling timer + alert (see "Automating inside widgets" below).
437
- "Every hour, post my schedule" → Build a scheduled-task widget using the cron skill.
438
- "Show my Slack messages" → Build a message panel via the slack channel.
439
- "Turn on the kitchen lights" → Use ha_control immediately (no widget needed for one-off actions).
440
- "What's on my screen" → Use the screenshot tool, render result as a panel image.
441
- "Monitor my CPU" → Build a live CPU usage chart.
442
- "A button that fetches news" → Build a news reader panel with a refresh button.
443
- "Show my calendar" → Build a calendar view panel.
444
- "I want a timer" → Build a countdown timer with start/stop/reset.
445
- "Draw a chart of sales" → Build a bar/line chart panel.
446
- "Dark mode" → Update existing widgets to use dark colors.
447
- "Make it bigger" → Update the widget dimensions.
448
- "Fix the clock" → Update the existing Clock widget's code.
449
-
450
- ## What you NEVER do
451
-
452
- NEVER ask the user to specify technical details:
453
- - "Would you like a React component or plain HTML?" → WRONG. Just pick the best option.
454
- - "Do you want me to use _____react or _____widget?" → WRONG. The user doesn't know what those are.
455
- - "Should I fetch data from an API or use static data?" → WRONG. Decide based on the request.
456
- - "What styling would you prefer?" → WRONG. Use clean, modern defaults.
457
-
458
- NEVER explain your technical choices to the user:
459
- - "I'll use React.useState to manage the timer state..." → WRONG. The user doesn't care.
460
- - "I'm going to use the _____react gate..." → WRONG. Just do it.
461
-
462
- NEVER output code as prose. If you write code, it goes through a gate.
463
-
464
- ## Current Context (live snapshot — updated every turn)
465
- Right now: ${r.toLocaleString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric"})} ${r.toLocaleTimeString("en-US")} (${i})
466
- Space: ${t.name} (id: \`${t.id}\`)
467
- Route: ${d||"/"}
468
- URL: ${a||"(unknown)"}
469
- Canvas: ${l}
470
- ${t.agentInstructions?`Space instructions from the user: ${t.agentInstructions}`:""}
471
-
472
- ## Current Canvas Widgets
473
- These widgets are already on the canvas RIGHT NOW. Use their \`id\` when updating or removing them. If the user says "the clock", "the chat", "this widget", match by name + id from the list. Never invent ids.
474
- ${s}
475
-
476
- ## Execution Protocol
477
- When you need to do browser-side work, you MUST use one of these gates on their own line.
478
- The gate MUST be alone on its line — no other text on the same line.
479
-
480
- ### _____javascript
481
- For running scripts, fetching data from APIs, or automating the canvas.
482
- Use when the user asks for: data fetching, API calls, automation, file operations, batch updates.
483
-
484
- Available APIs inside javascript:
485
- - titan.fetch(url, opts) — fetch data from the internet
486
- - titan.api.call(endpoint, body) — call backend APIs
487
- - titan.state.get(key) / titan.state.set(key, value) — save data between sessions
488
- - titan.canvas.createWidget(def) — create a new panel on the canvas
489
- - titan.canvas.updateWidget(id, patch) — update an existing panel
490
- - titan.canvas.removeWidget(id) — remove a panel
491
- - titan.canvas.listWidgets() — list all panels
492
- - console.log(...) — shows output in telemetry
493
-
494
- Use 'await' at the top level. Always 'return' a value if you want it shown.
495
-
496
- GOOD:
497
- _____javascript
498
- const res = await titan.fetch('https://api.weather.gov/stations/KNYC/observations/latest');
499
- const data = await res.json();
500
- const temp = data.properties.temperature.value;
501
- console.log('Temperature:', temp);
502
- return temp;
503
-
504
- BAD (do NOT do this):
505
- _____javascript
506
- fetch('...').then(r => r.json()).then(data => console.log(data))
507
-
508
- ### _____react
509
- For building visual panels, dashboards, interactive tools, charts, lists, forms, clocks, galleries, etc.
510
- Use when the user asks for: anything visual, interactive, a tool, a panel, a display, a chart, a form.
511
- This is the DEFAULT gate for most user requests — use it unless you specifically need to fetch data first.
512
-
513
- Rules:
514
- 1. Define ONE top-level component with a Capitalized name (e.g. \`Weather\`, \`TodoList\`, \`Clock\`).
515
- 2. Do NOT use \`export default\` — it is stripped automatically.
516
- 3. Do NOT render inline with '<Widget />' — just define the component.
517
- 4. The sandbox auto-detects your component by name, so any capitalized name works.
518
-
519
- GOOD:
520
- _____react
521
- function Weather() {
522
- const [temp, setTemp] = React.useState(72);
523
- return <div style={{ padding: 20, fontSize: 24 }}>{temp}°F</div>;
524
- }
525
-
526
- BAD (export default is forbidden):
527
- _____react
528
- function Weather() { return <div>72°F</div>; }
529
- export default Weather;
530
-
531
- ### _____widget
532
- For creating or updating widgets via JSON. Rarely needed — prefer _____react.
533
- - To CREATE: emit a JSON widget definition (no \`id\` field).
534
- - To UPDATE: include the \`id\` field of the widget you want to modify.
535
-
536
- CREATE example:
537
- _____widget
538
- { "name": "Clock", "format": "react", "source": "function Widget() { return <div>12:00</div>; }" }
539
-
540
- UPDATE example:
541
- _____widget
542
- { "id": "widget_1234567890_abc12", "source": "function Widget() { return <div>Fixed clock</div>; }" }
543
-
544
- Or for raw React source (create only):
545
- _____widget
546
- function Widget() {
547
- return <div>Hello from widget</div>;
548
- }
549
-
550
- ### _____canvas (v6.0.5 — preferred for canvas mutations)
551
- For batching MULTIPLE widget operations in ONE fence. Cheaper than calling create_widget/update_widget as separate tools because there's no per-call envelope.
552
-
553
- The body is a JSON array of action objects. Each must have an \`action\` field, one of: \`create_widget\`, \`update_widget\`, \`remove_widget\`.
554
-
555
- CREATE shape: { "action": "create_widget", "name": "Clock", "format": "react", "source": "function Widget() {...}", "w": 4, "h": 4 }
556
- UPDATE shape: { "action": "update_widget", "id": "widget_xxx", "patch": { "name": "Renamed Clock" } }
557
- REMOVE shape: { "action": "remove_widget", "id": "widget_xxx" }
558
-
559
- Example — user asks for a "coding setup":
560
- _____canvas
561
- [
562
- { "action": "create_widget", "name": "Pomodoro", "format": "react", "source": "...", "w": 4, "h": 3 },
563
- { "action": "create_widget", "name": "Todo", "format": "react", "source": "...", "w": 4, "h": 5 },
564
- { "action": "create_widget", "name": "Stack Overflow Search", "format": "react", "source": "...", "w": 4, "h": 6 }
565
- ]
566
-
567
- Use \`_____canvas\` whenever you'd otherwise issue ≥2 widget tool calls in the same turn. For one widget, \`_____react\` is still simpler.
568
-
569
- ### _____tool
570
- For calling backend tools or MCP servers.
571
-
572
- _____tool
573
- { "action": "search", "query": "deployment logs" }
574
-
575
- ## How to handle multi-step requests
576
-
577
- If the user asks for something that needs data first:
578
- 1. Use _____javascript to fetch the data.
579
- 2. Use the telemetry result to build the widget with _____react in the next turn.
580
-
581
- Example:
582
- User: "Show me the weather in New York"
583
- Turn 1: "Fetching weather data."
584
- _____javascript
585
- const res = await titan.fetch('https://api.weather.gov/stations/KNYC/observations/latest');
586
- const data = await res.json();
587
- return { temp: data.properties.temperature.value, conditions: data.properties.textDescription };
588
-
589
- Turn 2: (after receiving telemetry with temp and conditions)
590
- "Building the weather panel."
591
- _____react
592
- function Weather() {
593
- const [temp] = React.useState(72);
594
- const [conditions] = React.useState('Partly Cloudy');
595
- return (
596
- <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
597
- <h2>New York Weather</h2>
598
- <div style={{ fontSize: 48 }}>{temp}°F</div>
599
- <div>{conditions}</div>
600
- </div>
601
- );
602
- }
603
-
604
- ## TITAN can build literally anything — assume yes, then build
605
- The user can ask for ANY widget. If it has a public API, a website, a TITAN tool, or can be expressed as code, you can build it. Default answer is YES + immediate _____react. Below is a non-exhaustive category map so you have intuition for the breadth — use it to recognize requests, not as a checklist.
606
-
607
- 🎧 Music/DJ — BPM analyzer, key detector, Beatport browser, Spotify controller, lyrics fetcher, music theory helper, sample library indexer, DJ set planner.
608
- 💰 Finance — stock screener, crypto portfolio with PnL, subscription audit, expense splitter, bill reminders, currency converter, mortgage calculator, real estate tracker, tax estimator, receipt scanner via vision.
609
- 🏃 Health/Fitness — habit tracker, mood journal with AI sentiment, workout planner, sleep summary, medication reminder, calorie tracker via photo, water intake.
610
- 🎨 Creative — image generator (image_gen tool), color palette, logo concepts, story brainstormer, lyric assistant, mood board, video script writer, thumbnail generator.
611
- ✈️ Travel — flight tracker, itinerary builder, currency for destination, translation phrasebook, restaurant finder, transit info.
612
- 🎮 Gaming — Steam library, Twitch live embed, D&D character sheet, chess analyzer, speedrun timer, achievement tracker.
613
- 🏢 Work/Productivity — Pomodoro with focus pattern analysis, standup notes from git commits, sprint Kanban with AI prioritization, PR review queue, OKR tracker, 1:1 meeting prep.
614
- 📱 Social media — multi-platform composer (Twitter/IG/LinkedIn/TikTok/FB), post scheduler with AI caption variants, engagement dashboard, comment moderation, hashtag generator, content calendar.
615
- 🍳 Cooking — recipe finder by available ingredients, meal planner, multi-pot timer, wine pairing, nutrition calculator, grocery export.
616
- 🚗 Vehicle — Tesla status/control (Tony has Auth for Tesla installed), trip planner with charging stops, maintenance log, fuel cost tracker.
617
- 🏠 Homelab — fleet health grid for Tony's machines (Titan PC, Mini PC, T610, Pi 5), Wake-on-LAN buttons, SSL cert expiry monitor, speedtest, photo backup progress (Immich), Synapse deployment dashboard, Home Assistant rule editor.
618
- 🤖 ML workflow — model training progress, token usage tracker per session/model, prompt eval grid (same prompt N models side-by-side), embedding visualizer, dataset browser.
619
- 📚 Research/Learning — arXiv paper finder + AI summary, Anki-style spaced repetition (auto-generated cards from any text), citation manager, backlinked notes, quiz generator, AI tutor.
620
- 📄 Document/Writing — markdown editor with AI grammar, resume builder with job-targeted variants, email reply suggester, git commit message generator, documentation generator.
621
- 🛠️ Devops — service health grid, deploy pipeline status, log search, incident runbook, on-call rotation viewer, build status.
622
- 🛒 E-commerce — order tracking, inventory monitor, pricing optimizer (competitor scraper), review aggregator.
623
- 🐾 Lifestyle — pet feeding log, plant watering tracker, vet reminders, daily journal.
624
-
625
- How to compose these:
626
- • Read-only data widgets → titan.fetch(externalAPI) + setInterval refresh
627
- • Sites that allow framing → _____react with <iframe>
628
- • Sites that block framing → browser_screenshot tool snapshot
629
- • Anything needing an LLM → titan.api.call('/api/message', { content }) inside a button handler
630
- • Recurring/scheduled work → cron skill via titan.api.call
631
- • Reactive triggers → event_triggers skill
632
- • Multi-step research → 'Use the researcher sub-agent to …'
633
- • Code work → 'Use the coder sub-agent to …'
634
-
635
- When in doubt about what the user wants, ASK ONE clarifying question MAX, then build. Never trade speed of building for clarification depth.
636
-
637
- ## Loading external websites
638
- When the user says "load X" or "show me X" or "open X" where X is a website (eBay, YouTube, Wikipedia, GitHub, Hacker News, etc.), BUILD A WEBSITE PANEL on the canvas. Pick the right approach for the site:
639
-
640
- <example_handling>
641
- Examples below are wrapped in <example> tags. They are TEMPLATES showing the SHAPE of a working widget. They are NOT the answer to the user's current request. ALWAYS substitute the user's actual subject (URL, ticker, topic, name, action). The component name, the URL, the placeholder text, the prompt text in titan.api.call — every literal string in an example must be REPLACED with values matching the user's current message.
642
- </example_handling>
643
-
644
- <anti_pattern>
645
- USER: "Build a stock analyzer for AAPL"
646
- WRONG: "Adding an eBay panel to your canvas. _____react function WebPanel() { const url = 'https://www.ebay.com'... }"
647
- RIGHT: "Building a stock analyzer for AAPL. _____react function StockAnalyzer() { const [symbol, setSymbol] = React.useState('AAPL'); ... titan.api.call('/api/message', { content: \`Use the analyst sub-agent to analyze \${symbol}...\` }) ... }"
648
- The user's CURRENT message determines the build. NEVER reuse an example's domain content.
649
- </anti_pattern>
650
-
651
- PATTERN A — direct iframe (try this FIRST for most sites):
652
- Many sites allow being embedded. Use a plain iframe inside _____react with a small toolbar showing the URL + "Open in new tab" escape link.
653
-
654
- <example name="website-panel-shape">
655
- _____react
656
- function REPLACE_WITH_RELEVANT_NAME() {
657
- const url = "REPLACE_WITH_REAL_URL";
658
- return (
659
- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#0a0a0f' }}>
660
- <div style={{ padding: '6px 12px', borderBottom: '1px solid #27272a', fontSize: 11, color: '#a1a1aa', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
661
- <span>{url}</span>
662
- <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: '#818cf8', textDecoration: 'none' }}>Open in new tab ↗</a>
663
- </div>
664
- <iframe src={url} style={{ flex: 1, border: 0, background: 'white' }} title="WebPanel" />
665
- </div>
666
- );
667
- }
668
- </example>
669
-
670
- PATTERN B — server-rendered screenshot (when iframe is blocked):
671
- Some sites (Facebook, banks, anything with X-Frame-Options: DENY) refuse to embed. If the user reports a blank panel, switch to a screenshot widget that calls the browser_screenshot tool for an image snapshot. The widget shows the rendered page as an image plus a "Refresh" button that re-fetches.
672
-
673
- Use _____javascript first to fetch the screenshot, then _____react in the next turn to build the widget around the returned image data. Or do it in one shot via titan.api.call inside _____react.
674
-
675
- PATTERN C — proxied content (when iframe blocked AND user wants live interactive content):
676
- TITAN's gateway has POST /api/proxy that fetches HTML server-side and returns it without CORS or X-Frame-Options. Use titan.api.call('/api/proxy', { url }) inside _____react and render the returned HTML via dangerouslySetInnerHTML. Note: links won't navigate inside the panel; the rendered HTML is a snapshot.
677
-
678
- Default rule: try PATTERN A first. If the user says "it's blank" or "nothing's loading", switch to PATTERN B. If they want live content from a site that blocks framing, use PATTERN C.
679
-
680
- ## Agent-powered widgets — let widgets call sub-agents
681
- Widgets can call TITAN itself for live analysis, research, summarization, code review, anything that needs an LLM. The pattern is: build a UI panel with an input + button + result area. The button handler calls \`titan.api.call('/api/message', { content })\` which kicks off the regular agent loop server-side and returns a final response.
682
-
683
- For specialized work, ask for a SPECIFIC sub-agent template by prepending an instruction:
684
- - analyst → data analysis, decisions, comparisons
685
- - researcher → multi-source web research with citations
686
- - coder → write code to disk
687
- - browser → navigate + scrape websites with Playwright
688
- - explorer → read-only web research
689
- - reporter → produce a polished markdown document
690
- - fact_checker → verify claims against sources
691
-
692
- <example name="agent-powered-widget-shape">
693
- _____react
694
- function REPLACE_WITH_RELEVANT_NAME() {
695
- const [input, setInput] = React.useState('REPLACE_WITH_DEFAULT');
696
- const [report, setReport] = React.useState('Click REPLACE_WITH_ACTION to start.');
697
- const [busy, setBusy] = React.useState(false);
698
- const run = async () => {
699
- setBusy(true); setReport('Working…');
700
- try {
701
- const res = await titan.api.call('/api/message', {
702
- content: \`Use the REPLACE_WITH_TEMPLATE sub-agent to REPLACE_WITH_TASK for \${input}. Be concise.\`,
703
- });
704
- // titan.api.call returns { status, body, ok, ...flattened body fields }.
705
- // The /api/message response is { content, sessionId, ... } so either
706
- // res.body?.content (canonical) or res.content (flattened) works.
707
- setReport(res?.body?.content || res?.content || 'No response.');
708
- } catch (e) {
709
- setReport('Error: ' + (e?.message || e));
710
- } finally { setBusy(false); }
711
- };
712
- return (
713
- <div style={{ padding: 16, fontFamily: 'system-ui', color: '#e4e4e7' }}>
714
- <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
715
- <input value={input} onChange={e => setInput(e.target.value)} placeholder="REPLACE_WITH_PLACEHOLDER" style={{ flex: 1, padding: 8, background: '#18181b', border: '1px solid #27272a', borderRadius: 8, color: '#fafafa' }} />
716
- <button onClick={run} disabled={busy} style={{ padding: '8px 16px', background: '#6366f1', border: 0, borderRadius: 8, color: 'white', cursor: busy ? 'wait' : 'pointer' }}>{busy ? '…' : 'REPLACE_WITH_ACTION'}</button>
717
- </div>
718
- <div style={{ whiteSpace: 'pre-wrap', fontSize: 13, lineHeight: 1.5 }}>{report}</div>
719
- </div>
720
- );
721
- }
722
- </example>
723
-
724
- The widget above:
725
- - has a controlled input bound to React state
726
- - on click, fires \`titan.api.call('/api/message')\` which routes through the standard TITAN agent
727
- - displays whatever comes back
728
-
729
- For research/summarizer/translator/reviewer widgets, swap the prompt accordingly. Same shape every time.
730
-
731
- ## Automating inside widgets — schedules, polling, events
732
- Widgets can run on a timer, poll APIs, react to thresholds, or chain agent calls. Two mechanisms:
733
-
734
- 1. CLIENT-SIDE timer (simplest, runs only while widget is mounted):
735
- Use \`React.useEffect\` + \`setInterval\` inside _____react. Good for "every 30s refresh BTC price" or "auto-poll the API every minute". Remember to clean up in the effect's return.
736
-
737
- <example name="polling-with-threshold-alert-shape">
738
- _____react
739
- function REPLACE_WITH_RELEVANT_NAME() {
740
- const [value, setValue] = React.useState(null);
741
- const [threshold, setThreshold] = React.useState(0 /* REPLACE with relevant default */);
742
- const [alerted, setAlerted] = React.useState(false);
743
- React.useEffect(() => {
744
- const tick = async () => {
745
- const res = await titan.fetch('REPLACE_WITH_REAL_API_URL');
746
- const data = await res.json();
747
- const v = data?.REPLACE_WITH_PATH;
748
- setValue(v);
749
- if (v != null && v < threshold && !alerted) {
750
- setAlerted(true);
751
- await titan.api.call('/api/message', { content: \`REPLACE_WITH_ALERT_PROMPT — value is \${v}, threshold \${threshold}.\` });
752
- }
753
- };
754
- tick();
755
- const id = setInterval(tick, 30000);
756
- return () => clearInterval(id);
757
- }, [threshold, alerted]);
758
- return (
759
- <div style={{ padding: 20, fontFamily: 'system-ui', color: '#e4e4e7' }}>
760
- <div style={{ fontSize: 36, fontWeight: 600 }}>{value != null ? value.toLocaleString() : 'Loading…'}</div>
761
- <div style={{ fontSize: 12, color: '#71717a' }}>REPLACE_WITH_LABEL</div>
762
- </div>
763
- );
764
- }
765
- </example>
766
-
767
- 2. SERVER-SIDE schedule (survives page reload, runs in the gateway daemon):
768
- For "every hour post my schedule to Slack" or "every Monday 9am run a security scan" — use the cron skill via \`titan.api.call('/api/message', { content: 'schedule a recurring task: <cron expression> <task description>' })\`. The widget can show the cron job's status and history by polling \`/api/cron\`.
769
-
770
- 3. EVENT triggers (server-side reactive, survives reload):
771
- The event_triggers skill lets you set up "when X happens, do Y" rules. Use this for "when a new email arrives in inbox X, summarize and post to Slack" or "when a new GitHub PR is opened in repo Y, run code review."
772
-
773
- ## Widget Repair Rules
774
- When the user asks you to "fix", "update", "change", or "make it blue":
775
- 1. If you know the widget id from the Current Canvas Widgets list above, update it directly.
776
- 2. If you're unsure which widget, use _____javascript with \`titan.canvas.listWidgets()\` to discover it, then fix it in the next turn.
777
- 3. NEVER create a duplicate — always update the existing one.
778
-
779
- ## Rules
780
- - ALWAYS use execution gates for browser work. Never just describe what you would do.
781
- - One short staging sentence before the gate. Example: "Fetching weather data."
782
- - The gate must be on its own line with NO other text.
783
- - After the gate, everything is code until the next gate or message end.
784
- - Do not ask for permission for obvious safe actions.
785
- - Be concise. Keep responses focused.
786
- - If a task requires multiple steps, use multiple turns with gates.
787
- - Never emit raw code as prose. Use the gate or don't show code at all.
788
- - DEFAULT to _____react for visual/interactive requests. Use _____javascript only when you need to fetch data or run scripts first.
789
-
790
- REMINDER — BASE LAW:
791
- 1. The user is NOT technical. Do NOT use jargon. Do NOT ask technical questions.
792
- 2. If the user asks for ANYTHING visual or interactive, BUILD IT IMMEDIATELY. Do not ask permission.
793
- 3. USE AN EXECUTION GATE for all browser work.
794
- 4. One staging sentence, then the gate.
795
- 5. Update existing widgets by id — never create duplicates.`}function vl({space:t,onClose:e,onMascotState:s}){const[r,i]=w.useState([]),[a,d]=w.useState(""),[l,c]=w.useState(!1),[f,b]=w.useState([]),u=8,[p,m]=w.useState(null),y=w.useRef(null),_=w.useRef(null),R=w.useRef(null),k=w.useRef(null),I=w.useRef(t);w.useEffect(()=>{I.current=t},[t]);const g=w.useCallback(S=>{const T=I.current;if(S.type==="render_widget"){const P=S.widget,M=Number.isFinite(P.w)?Number(P.w):4,F=Number.isFinite(P.h)?Number(P.h):4,V=Number.isFinite(P.x)&&Number.isFinite(P.y)?{x:Number(P.x),y:Number(P.y)}:gs(T.widgets||[],M,F),Y=ve.addWidget(T.id,{name:P.name||"Widget",format:P.format||"react",source:P.source,x:V.x,y:V.y,w:M,h:F});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:T.id}})),Y.id}return S.type==="update_widget"?(ve.updateWidget(T.id,S.widgetId,S.patch||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:T.id}})),S.widgetId):S.type==="remove_widget"?(ve.removeWidget(T.id,S.widgetId),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:T.id}})),S.widgetId):S.type==="set_runtime_state"?(localStorage.setItem(`titan:runtime:${T.id}:${S.key}`,JSON.stringify(S.value)),S.key):S.type==="emit_event"?(window.dispatchEvent(new CustomEvent(S.eventName,{detail:S.detail})),S.eventName):null},[]),j=w.useCallback(S=>{var T,P;g({type:"render_widget",widget:{name:S.templateName,format:S.format,source:S.source,w:((T=S.defaultSize)==null?void 0:T.w)??4,h:((P=S.defaultSize)==null?void 0:P.h)??4}})},[g]);w.useEffect(()=>{var S;(S=y.current)==null||S.scrollIntoView({behavior:"smooth"})},[r]),w.useEffect(()=>{const S=P=>{var F;const M=(F=P.detail)==null?void 0:F.text;typeof M=="string"&&A(M)},T=P=>{const M=P.detail;M!=null&&M.source&&j(M)};return window.addEventListener("titan:chat:prompt",S),window.addEventListener("titan:gallery:run-template",T),()=>{window.removeEventListener("titan:chat:prompt",S),window.removeEventListener("titan:gallery:run-template",T)}},[j]),w.useEffect(()=>{if(!R.current||k.current)return;const S=new yl(R.current,{onLog:T=>console.log("[Sandbox]",T)});return S.setMessageHandler(T=>{var M,F,V,Y;const P=I.current;if(T.type==="canvas"&&((M=T.payload)==null?void 0:M.action)==="createWidget"){const q=T.payload.def;if(!q)return{ok:!1,error:"createWidget requires a `def` object"};const ye=Number.isFinite(q.w)?q.w:4,Z=Number.isFinite(q.h)?q.h:4,ge=Number.isFinite(q.x)&&Number.isFinite(q.y)?{x:q.x,y:q.y}:gs(P.widgets||[],ye,Z);try{const he=ve.addWidget(P.id,{name:q.name||"Agent Widget",format:q.format||"react",source:q.source||"",x:ge.x,y:ge.y,w:ye,h:Z});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0,widgetId:he.id}}catch(he){return{ok:!1,error:he.message}}}if(T.type==="canvas"&&((F=T.payload)==null?void 0:F.action)==="updateWidget"){const{id:q,patch:ye}=T.payload;return q?(ve.updateWidget(P.id,q,ye||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0,id:q}):{ok:!1,error:"updateWidget requires an `id`"}}if(T.type==="canvas"&&((V=T.payload)==null?void 0:V.action)==="listWidgets")return{ok:!0,widgets:P.widgets||[]};if(T.type==="canvas"&&((Y=T.payload)==null?void 0:Y.action)==="removeWidget"){const q=T.payload.id;return q?(ve.removeWidget(P.id,q),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}}),k.current=S,()=>{S.destroy(),k.current=null}},[]);const v=w.useCallback(async(S,T)=>{const P=k.current;if(!P)return{status:"error",logs:[{level:"error",text:"Sandbox not ready"}],resultText:"",runId:Date.now(),error:{message:"Sandbox not ready",name:"SandboxError",stack:"",text:"Sandbox not ready"}};if(S==="_____javascript")try{const M=await P.execute(T);return{status:M.status==="success"?"success":"error",logs:M.logs||[],result:M.result,resultText:M.resultText||String(M.result??""),runId:Date.now(),error:M.error?{message:M.error.message||String(M.error),name:"ExecutionError",stack:"",text:String(M.error)}:void 0}}catch(M){return{status:"error",logs:[{level:"error",text:M.message||String(M)}],resultText:"",runId:Date.now(),error:{message:M.message||String(M),name:"ExecutionError",stack:"",text:String(M)}}}if(S==="_____react"){let M=4,F=4;const V=T.match(/\/\/\s*__WIDGET_META__\s+w=(\d+)\s+h=(\d+)/);V&&(M=parseInt(V[1],10)||4,F=parseInt(V[2],10)||4);try{const Y=g({type:"render_widget",widget:{name:"React Widget",format:"react",source:T,w:M,h:F}});return{status:"success",logs:[{level:"info",text:`Created widget ${Y}`}],result:{widgetId:Y},resultText:`Created widget ${Y}`,runId:Date.now()}}catch(Y){return{status:"error",logs:[{level:"error",text:Y.message||String(Y)}],resultText:"",runId:Date.now(),error:{message:Y.message||String(Y),name:"WidgetError",stack:"",text:String(Y)}}}}if(S==="_____widget"){const M=wl({gate:"_____widget",code:T,leadingText:""});if(!M)return{status:"error",logs:[{level:"error",text:"Invalid widget payload"}],resultText:"",runId:Date.now(),error:{message:"Invalid widget payload",name:"WidgetError",stack:"",text:"Invalid widget payload"}};try{const F=g(M),V=M.type==="update_widget"?"Updated":"Created";return{status:"success",logs:[{level:"info",text:`${V} widget ${F}`}],result:F?{widgetId:F}:void 0,resultText:`${V} widget ${F??""}`.trim(),runId:Date.now()}}catch(F){return{status:"error",logs:[{level:"error",text:F.message||String(F)}],resultText:"",runId:Date.now(),error:{message:F.message||String(F),name:"WidgetError",stack:"",text:String(F)}}}}if(S==="_____canvas"){const M=dp(T);if(M.length===0)return{status:"error",logs:[{level:"error",text:"Empty or invalid _____canvas payload (expected JSON array of {action, ...})"}],resultText:"",runId:Date.now(),error:{message:"Invalid canvas payload",name:"CanvasFenceError",stack:"",text:"Empty or invalid _____canvas payload"}};const F=[],V=[];for(const q of M)try{if(q.action==="create_widget"){if(!q.source){V.push("create_widget: missing source");continue}const ye=g({type:"render_widget",widget:{name:q.name||"Widget",title:q.title,format:q.format||"react",source:q.source,w:q.w,h:q.h,x:q.x,y:q.y,metadata:q.metadata}});F.push(`created ${ye}`)}else if(q.action==="update_widget"){if(!q.id){V.push("update_widget: missing id");continue}const ye=q.patch??{};g({type:"update_widget",widgetId:q.id,patch:ye}),F.push(`updated ${q.id}`)}else if(q.action==="remove_widget"){if(!q.id){V.push("remove_widget: missing id");continue}g({type:"remove_widget",widgetId:q.id}),F.push(`removed ${q.id}`)}else V.push(`unknown action: ${String(q.action)}`)}catch(ye){V.push(ye.message||String(ye))}const Y=V.length===0?"success":F.length===0?"error":"success";return{status:Y,logs:[...F.map(q=>({level:"info",text:q})),...V.map(q=>({level:"error",text:q}))],resultText:F.length?F.join("; "):"No actions applied",runId:Date.now(),...Y==="error"?{error:{message:V.join("; "),name:"CanvasFenceError",stack:"",text:V.join("; ")}}:{}}}return S==="_____tool"?{status:"error",logs:[{level:"error",text:"_____tool gate not supported in Canvas chat"}],resultText:"",runId:Date.now(),error:{message:"_____tool gate not supported",name:"NotSupported",stack:"",text:"_____tool gate not supported in Canvas chat"}}:{status:"error",logs:[{level:"error",text:`Unknown gate: ${S}`}],resultText:"",runId:Date.now(),error:{message:`Unknown gate: ${S}`,name:"UnknownGate",stack:"",text:`Unknown gate: ${S}`}}},[]),A=w.useCallback(async S=>{var V;const T=S.trim();if(!T)return;if(l){b(Y=>Y.length>=u?Y:[...Y,T]),d("");return}const P={role:"user",content:T,timestamp:Date.now()};i(Y=>[...Y,P]),d(""),c(!0),m(null),s==null||s("thinking");const M=new AbortController;_.current=M;let F="";try{const Y=gp(I.current),q=`canvas-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await da(T,q,ge=>{if(ge.type==="token")F+=ge.data,i(he=>{const se=he[he.length-1];return se&&se.role==="assistant"?[...he.slice(0,-1),{...se,content:F}]:[...he,{role:"assistant",content:F,timestamp:Date.now()}]});else if(ge.type==="widget"){const he=ge.widgetMode||"create",se=ge.widget||{},ie=I.current;try{if(he==="remove"&&se.id)ve.removeWidget(ie.id,se.id);else if(he==="update"&&se.id){const Q={};typeof se.name=="string"&&se.name&&(Q.name=se.name),typeof se.title=="string"&&(Q.title=se.title),typeof se.source=="string"&&se.source&&(Q.source=se.source),typeof se.format=="string"&&(Q.format=se.format),typeof se.w=="number"&&(Q.w=se.w),typeof se.h=="number"&&(Q.h=se.h),ve.updateWidget(ie.id,se.id,Q)}else if(se.source){const Q=typeof se.w=="number"?se.w:4,xe=typeof se.h=="number"?se.h:4,$=typeof se.x=="number"&&typeof se.y=="number"?{x:se.x,y:se.y}:gs(ie.widgets||[],Q,xe);ve.addWidget(ie.id,{name:se.name||"Widget",title:se.title,format:se.format||"react",source:se.source,x:$.x,y:$.y,w:Q,h:xe,metadata:se.metadata})}window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:ie.id}}))}catch(Q){console.error("[ChatWidget] widget side-channel handler failed",Q)}}else if(ge.type==="done"){const he=ge.data||F;F=he,i(se=>{const ie=se[se.length-1];return ie&&ie.role==="assistant"?[...se.slice(0,-1),{...ie,content:he}]:[...se,{role:"assistant",content:he,timestamp:Date.now()}]})}else ge.type==="error"&&m(ge.data)},M.signal,{systemPromptAppendix:Y});const Z=up(F).filter(ge=>ge.gate!=="_____transient"&&ge.gate!=="_____framework");if(Z.length>0){s==null||s("executing");const ge=[];for(const ie of Z){const Q=mp(`${ie.gate}
796
- ${ie.code}`);if(!Q.valid){ge.push({status:"error",logs:[{level:"error",text:Q.error||"Invalid execution"}],resultText:"",runId:Date.now(),error:{message:Q.error||"Invalid execution",name:"ValidationError",stack:"",text:Q.error||""}});continue}const xe=await v(ie.gate,ie.code);ge.push(xe)}const he=fp(ge);i(ie=>[...ie,he]);const se=ge.find(ie=>ie.status==="error");se&&m(((V=se.error)==null?void 0:V.text)||"Execution failed")}}catch(Y){Y.name!=="AbortError"&&m(Y.message||"Request failed")}finally{c(!1),_.current=null,s==null||s("idle")}},[l,s,v]),E=w.useCallback(()=>{var S;(S=_.current)==null||S.abort(),_.current=null,c(!1),b([]),s==null||s("idle")},[s]);w.useEffect(()=>{if(l||f.length===0)return;const[S,...T]=f;b(T),A(S)},[l,f,A]);const N=w.useCallback(S=>{b(T=>T.filter((P,M)=>M!==S))},[]),D=w.useCallback(S=>{S.key==="Enter"&&!S.shiftKey&&(S.preventDefault(),A(a))},[a,A]);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:[n.jsx("iframe",{ref:R,style:{position:"absolute",width:0,height:0,border:0,visibility:"hidden"},sandbox:"allow-scripts"}),n.jsxs("div",{style:{flex:1,overflowY:"auto",padding:12},children:[r.map((S,T)=>n.jsxs("div",{style:{marginBottom:8,padding:8,borderRadius:8,background:S.role==="user"?"rgba(59,130,246,0.15)":S.role==="framework"?"rgba(245,158,11,0.1)":"rgba(255,255,255,0.05)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[n.jsx("div",{style:{fontSize:10,opacity:.6,marginBottom:4,textTransform:"uppercase"},children:S.role}),n.jsx("div",{style:{fontSize:13,lineHeight:1.5},children:S.content}),S.executions&&S.executions.length>0&&n.jsx("div",{style:{marginTop:4,fontSize:11,opacity:.7},children:S.executions.map((P,M)=>n.jsxs("span",{style:{marginRight:8},children:[P.status==="success"?"✓":"✗"," execution ",M+1]},M))})]},T)),l&&n.jsx("div",{style:{fontSize:12,opacity:.5,padding:8},children:"Thinking…"}),p&&n.jsx("div",{style:{color:"#ef4444",fontSize:12,padding:8,background:"rgba(239,68,68,0.1)",borderRadius:6},children:p}),n.jsx("div",{ref:y})]}),f.length>0&&n.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid rgba(255,255,255,0.08)",display:"flex",flexWrap:"wrap",gap:6,background:"rgba(99,102,241,0.06)"},children:[n.jsxs("span",{style:{fontSize:10,opacity:.7,alignSelf:"center",textTransform:"uppercase",letterSpacing:.5},children:["Queued (",f.length,")"]}),f.map((S,T)=>n.jsxs("span",{title:S,style:{fontSize:11,padding:"3px 8px",background:"rgba(99,102,241,0.18)",border:"1px solid rgba(99,102,241,0.4)",borderRadius:999,color:"#e0e7ff",display:"inline-flex",alignItems:"center",gap:6,maxWidth:220},children:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S}),n.jsx("button",{onClick:()=>N(T),title:"Remove from queue",style:{border:"none",background:"transparent",color:"#c7d2fe",cursor:"pointer",padding:0,fontSize:12,lineHeight:1},children:"×"})]},T))]}),n.jsxs("div",{style:{padding:12,borderTop:"1px solid rgba(255,255,255,0.08)",display:"flex",gap:8},children:[n.jsx("input",{type:"text",value:a,onChange:S=>d(S.target.value),onKeyDown:D,placeholder:l?f.length>=u?`Queue full (${u}) — wait for TITAN to catch up…`:"TITAN is thinking — type to steer or queue a follow-up…":"Ask TITAN to create an agent, run a task, or build a widget…",style:{flex:1,background:"rgba(255,255,255,0.06)",border:l?"1px solid rgba(99,102,241,0.4)":"1px solid rgba(255,255,255,0.1)",borderRadius:8,padding:"8px 12px",color:"#fff",fontSize:13,outline:"none"}}),l?n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>A(a),disabled:!a.trim()||f.length>=u,title:"Queue this message for after the current turn",style:{padding:"8px 14px",borderRadius:8,border:"none",background:a.trim()&&f.length<u?"#6366f1":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:a.trim()&&f.length<u?"pointer":"not-allowed"},children:"Queue"}),n.jsx("button",{onClick:E,title:"Stop the current turn and clear the queue",style:{padding:"8px 14px",borderRadius:8,border:"none",background:"#ef4444",color:"#fff",fontSize:13,cursor:"pointer"},children:"Stop"})]}):n.jsx("button",{onClick:()=>A(a),disabled:!a.trim(),style:{padding:"8px 14px",borderRadius:8,border:"none",background:a.trim()?"#3b82f6":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:a.trim()?"pointer":"not-allowed"},children:"Send"})]})]})}const Tr="titan2:chat-dock:hidden-edge";function yp(t=e=>typeof localStorage>"u"?null:localStorage.getItem(e)){try{const e=t(Tr);if(e==="left"||e==="right"||e==="top"||e==="bottom")return e;if(e==="visible")return null}catch{}return"right"}function bp(t,e=(s,r)=>{typeof localStorage>"u"||localStorage.setItem(s,r)}){try{t?e(Tr,t):e(Tr,"visible")}catch{}}const _l="titan2:chat-dock:pos",kl="titan2:chat-dock:size",Sl="titan2:chat-dock:hint-shown",xp=4,et=116,ht=et*1.38,Fs=14,wp=320,vp=360,_p=960,kp=900,Sp=420,jp=560,jl=640,ir=8,Ep=20,Np=64,Cp="transform 280ms cubic-bezier(0.22, 1, 0.36, 1)",Tp="transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)",Ap=400,Rp=180,Ip=1800,Lp=1e4,Dp=28,Mp=260,Op=2e3,Pp=3500;function Wp(){try{const t=localStorage.getItem(kl);if(t){const e=JSON.parse(t);if(typeof(e==null?void 0:e.w)=="number"&&typeof(e==null?void 0:e.h)=="number")return Ar(e)}}catch{}return{w:Sp,h:jp}}function Up(t){try{localStorage.setItem(kl,JSON.stringify(t))}catch{}}function Ar(t){return{w:Math.max(wp,Math.min(t.w,_p)),h:Math.max(vp,Math.min(t.h,kp))}}function Bp(){try{const t=localStorage.getItem(_l);if(t){const e=JSON.parse(t);if(typeof(e==null?void 0:e.x)=="number"&&typeof(e==null?void 0:e.y)=="number")return e}}catch{}return Fp()}function Fp(){const t=typeof window<"u"?window.innerWidth:1280,e=typeof window<"u"?window.innerHeight:800,s=t<=jl;return{x:t-et,y:s?Math.max(220,e-ht-96):e-ht-32}}function $p(t){try{localStorage.setItem(_l,JSON.stringify(t))}catch{}}let El=!1;function Qi(){try{return localStorage.getItem(Sl)==="1"}catch{return El}}function ar(){try{localStorage.setItem(Sl,"1")}catch{El=!0}}function $s(t){const e=window.innerWidth,s=window.innerHeight;return{x:Math.max(0,Math.min(t.x,e-et)),y:Math.max(0,Math.min(t.y,s-ht))}}function zp(){return typeof window<"u"&&window.innerWidth<=jl}function Hp(t,e){if(!e)return t;const s=window.innerWidth,r=window.innerHeight,i=Math.max(0,Math.min(t.y,r-ht)),a=Math.max(0,Math.min(t.x,s-et));switch(e){case"left":return{x:0,y:i};case"right":return{x:s-et,y:i};case"bottom":return{x:a,y:r-ht};case"top":return{x:a,y:0};default:return t}}function ea(t){const e=window.innerWidth,s=window.innerHeight;return t.x<=ir?"left":t.x>=e-et-ir?"right":t.y>=s-ht-ir?"bottom":null}function Vp(t,e){if(!t)return"";const s=et-Ep,r=e?Np:0;switch(t){case"left":return`translate3d(${-(s-r)}px, 0, 0)`;case"right":return`translate3d(${s-r}px, 0, 0)`;case"top":return`translate3d(0, ${-(s-r)}px, 0)`;case"bottom":return`translate3d(0, ${s-r}px, 0)`;default:return""}}function Gp(t){switch(t){case"left":return 90;case"right":return-90;case"top":return 180;case"bottom":return 0;default:return 0}}function Yp(t){return t.x>window.innerWidth/2}function qp(t){const e=t.trim().split(/\s+/).filter(Boolean).length,s=Ip+t.length*Dp+e*Mp;return Math.min(s,Lp)}function Kp(t,e){const s=window.innerWidth,r=window.innerHeight,i=s-(t.x+et),a=r-(t.y+ht),d=i>=e.w+Fs?"right":"left",l=a>=e.h+Fs?"below":"above",c=d==="right"?t.x+et+Fs:t.x-e.w-Fs,f=l==="below"?t.y:t.y+ht-e.h;return{left:Math.max(8,Math.min(c,s-e.w-8)),top:Math.max(8,Math.min(f,r-e.h-8)),side:d,vertical:l}}function Jp({space:t,somaActive:e,defaultExpanded:s=!1,hideMascot:r=!1}){const[i,a]=w.useState(!1),d=e??i;w.useEffect(()=>{let H=!1;ue("/api/config").then(X=>X.ok?X.json():null).then(X=>{var O;H||a(!!((O=X==null?void 0:X.organism)!=null&&O.enabled))}).catch(()=>{});const K=X=>{const O=X.detail;typeof(O==null?void 0:O.enabled)=="boolean"&&a(O.enabled)};return window.addEventListener("titan:soma:changed",K),()=>{H=!0,window.removeEventListener("titan:soma:changed",K)}},[]),w.useEffect(()=>{const H=K=>{const X=K.detail;typeof(X==null?void 0:X.open)=="boolean"?p(X.open):p(O=>!O)};return window.addEventListener("titan:chat:toggle",H),()=>window.removeEventListener("titan:chat:toggle",H)},[]);const[l,c]=w.useState(()=>$s(Bp())),[f,b]=w.useState(()=>Wp()),[u,p]=w.useState(s),[m,y]=w.useState(!1),[_,R]=w.useState(!1),[k,I]=w.useState("idle"),[g,j]=w.useState(()=>yp()),[v,A]=w.useState(!1),[E,N]=w.useState(!1),[D,S]=w.useState(null),T=w.useRef({}),P=w.useRef(null),M=w.useRef(null),F=w.useRef(!1);w.useEffect(()=>{$p(l)},[l]),w.useEffect(()=>{Up(f)},[f]),w.useEffect(()=>{bp(g)},[g]),w.useEffect(()=>{const H=window.matchMedia("(prefers-reduced-motion: reduce)");N(H.matches);const K=X=>N(X.matches);return H.addEventListener("change",K),()=>H.removeEventListener("change",K)},[]),w.useEffect(()=>{let H,K;const X=()=>{clearTimeout(K),K=window.setTimeout(()=>{c(z=>{const ee=g?Hp($s(z),g):$s(z),C=ea(ee);return j(C),ee}),b(z=>Ar(z))},50)},O=()=>{clearTimeout(H),H=window.setTimeout(X,100)};window.addEventListener("resize",O),document.addEventListener("visibilitychange",X),window.addEventListener("focus",X),window.addEventListener("pageshow",X);const U=window.setInterval(X,2e3);return()=>{window.removeEventListener("resize",O),document.removeEventListener("visibilitychange",X),window.removeEventListener("focus",X),window.removeEventListener("pageshow",X),clearTimeout(H),clearTimeout(K),clearInterval(U)}},[g]),w.useEffect(()=>()=>{clearTimeout(T.current.enter),clearTimeout(T.current.exit),clearTimeout(T.current.hide)},[]),w.useEffect(()=>{if(Qi())return;if(zp()||g){ar();return}let H,K;return H=window.setTimeout(()=>{Y("Drag me, tap me."),ar(),K=window.setTimeout(()=>{q()},Pp),T.current.hide=K},Op),()=>{clearTimeout(H),clearTimeout(K)}},[g]);const V=w.useCallback(()=>{clearTimeout(T.current.enter),clearTimeout(T.current.exit),clearTimeout(T.current.hide),T.current={}},[]),Y=w.useCallback(H=>{V(),S({text:H,phase:"entering"}),T.current.enter=window.setTimeout(()=>{S(X=>X&&X.text===H?{...X,phase:"visible"}:X);const K=qp(H);T.current.hide=window.setTimeout(()=>{q()},K)},Ap)},[V]),q=w.useCallback(()=>{V(),S(H=>H?(T.current.exit=window.setTimeout(()=>{S(null)},Rp),{...H,phase:"leaving"}):null)},[V]),ye=k==="thinking"?"thinking…":k==="executing"?"working on it":null;w.useEffect(()=>{ye?Y(ye):S(H=>H?((H.text==="thinking…"||H.text==="working on it")&&q(),H):null)},[ye]);const Z=w.useCallback(H=>{var K,X;H.button===0&&((X=(K=H.target).setPointerCapture)==null||X.call(K,H.pointerId),P.current={pointer:{x:H.clientX,y:H.clientY},pos:l,moved:!1},y(!0),Qi()||ar())},[l]),ge=w.useCallback(H=>{const K=P.current;if(!K)return;const X=H.clientX-K.pointer.x,O=H.clientY-K.pointer.y;!K.moved&&Math.hypot(X,O)<xp||(K.moved=!0,g&&j(null),c($s({x:K.pos.x+X,y:K.pos.y+O})))},[g]),he=w.useCallback(H=>{var X,O;const K=P.current;if((O=(X=H.target).releasePointerCapture)==null||O.call(X,H.pointerId),P.current=null,y(!1),K&&K.moved){const U=ea(l);j(U||null)}else K&&!K.moved&&(g&&j(null),p(U=>!U))},[l,g]),se=w.useCallback(()=>{g&&A(!0)},[g]),ie=w.useCallback(()=>{A(!1)},[]),Q=w.useCallback(H=>{if(H.ctrlKey||m)return;let K=H.target;for(;K&&K!==document.body;){const X=window.getComputedStyle(K),O=K.scrollHeight>K.clientHeight,U=X.overflowY;if(O&&(U==="auto"||U==="scroll")){K.scrollTop+=H.deltaY,H.preventDefault();return}K=K.parentElement}window.scrollBy({top:H.deltaY,left:H.deltaX,behavior:"auto"}),H.preventDefault()},[m]),xe=Kp(l,f),$=(D==null?void 0:D.text)??null,G=(D==null?void 0:D.phase)??null,J=w.useCallback(H=>{var K,X;H.button===0&&(H.stopPropagation(),(X=(K=H.target).setPointerCapture)==null||X.call(K,H.pointerId),M.current={pointer:{x:H.clientX,y:H.clientY},size:f,anchorSide:xe.side,anchorVertical:xe.vertical},R(!0))},[f,xe.side,xe.vertical]),le=w.useCallback(H=>{const K=M.current;if(!K)return;const X=H.clientX-K.pointer.x,O=H.clientY-K.pointer.y,U=K.anchorSide==="right"?X:-X,z=K.anchorVertical==="below"?O:-O;b(Ar({w:K.size.w+U,h:K.size.h+z}))},[]),be=w.useCallback(H=>{var K,X;(X=(K=H.target).releasePointerCapture)==null||X.call(K,H.pointerId),M.current=null,R(!1)},[]),Ee=Vp(g,v);return n.jsxs(n.Fragment,{children:[!r&&n.jsx("div",{style:{position:"fixed",left:l.x,top:l.y,width:et,height:ht,zIndex:2147482e3,cursor:m?"grabbing":g?"pointer":"grab",touchAction:"none",userSelect:"none",animation:E||g?void 0:"titan-dock-in 220ms ease-out both",transform:Ee,transition:m?"none":`${Cp}, ${Tp}`},onPointerDown:Z,onPointerMove:ge,onPointerUp:he,onPointerCancel:he,onPointerEnter:se,onPointerLeave:ie,onWheel:Q,title:u?"Click to minimize TITAN chat — drag to move":"Click to open TITAN chat — drag to move",children:n.jsx(ua,{state:k,size:et,quip:$,bubblePhase:G,somaActive:d,followCursor:!m,edgeRotate:Gp(g),faceFlip:Yp(l),edgeHidden:!!g})}),u&&n.jsxs("div",{style:{position:"fixed",left:xe.left,top:xe.top,width:f.w,height:f.h,zIndex:2147481999,pointerEvents:"auto",borderRadius:14,border:"1px solid rgba(255,255,255,0.08)",background:"rgba(11,11,14,0.72)",backdropFilter:"blur(18px) saturate(1.08)",WebkitBackdropFilter:"blur(18px) saturate(1.08)",boxShadow:"0 18px 44px rgba(0,0,0,0.24)",animation:_||F.current||E?void 0:"titan-dock-panel-in 180ms cubic-bezier(0.2, 0.9, 0.25, 1) both",transformOrigin:`${xe.side==="right"?"left":"right"} ${xe.vertical==="below"?"top":"bottom"}`},children:[n.jsx(vl,{space:t,onClose:()=>p(!1),onMascotState:I}),n.jsx("div",{onPointerDown:J,onPointerMove:le,onPointerUp:be,onPointerCancel:be,title:"Drag to resize",style:{position:"absolute",[xe.vertical==="below"?"bottom":"top"]:0,[xe.side==="right"?"right":"left"]:0,width:18,height:18,cursor:xe.side==="right"?"nwse-resize":"nesw-resize",touchAction:"none",background:"transparent",zIndex:2},children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 18 18",style:{display:"block",opacity:_?1:.55},children:xe.side==="right"?n.jsxs("g",{stroke:"#6366f1",strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[n.jsx("line",{x1:"5",y1:"14",x2:"14",y2:"14"}),n.jsx("line",{x1:"9",y1:"10",x2:"14",y2:"10"}),n.jsx("line",{x1:"14",y1:"14",x2:"14",y2:"5"})]}):n.jsxs("g",{stroke:"#6366f1",strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[n.jsx("line",{x1:"4",y1:"14",x2:"13",y2:"14"}),n.jsx("line",{x1:"4",y1:"10",x2:"9",y2:"10"}),n.jsx("line",{x1:"4",y1:"14",x2:"4",y2:"5"})]})})})]}),n.jsx("style",{children:`
797
- @keyframes titan-dock-in {
798
- from { opacity: 0; transform: translate3d(0, 4px, 0); }
799
- to { opacity: 1; transform: translate3d(0, 0, 0); }
800
- }
801
- @keyframes titan-dock-panel-in {
802
- from { opacity: 0; transform: translate3d(0, 12px, 0) scale(0.968); }
803
- to { opacity: 1; transform: translate3d(0, 0, 0) scale(1); }
804
- }
805
- @media (prefers-reduced-motion: reduce) {
806
- .titan-dock-root, .titan-dock-panel {
807
- animation: none !important;
808
- transition: none !important;
809
- }
810
- }
811
- `})]})}const Xp=3e4,Zp=3e4;function Qp(){const[t,e]=w.useState(null),s=w.useRef(null),r=w.useRef(new Set),i=w.useRef(null);if(w.useEffect(()=>{let d=!1;const l=async()=>{var f;try{const b=await ue("/api/soma/advisories?limit=5");if(!b.ok)return;const u=await b.json();if(d||!((f=u.advisories)!=null&&f.length))return;for(const p of u.advisories)if(!r.current.has(p.at)&&!(s.current&&p.at<=s.current)){if(s.current===null){s.current=u.advisories[0].at;return}s.current=p.at,e(p),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>e(null),Zp);return}}catch{}};l();const c=setInterval(l,Xp);return()=>{d=!0,clearInterval(c),i.current&&clearTimeout(i.current)}},[]),!t)return null;const a=()=>{r.current.add(t.at),e(null),i.current&&clearTimeout(i.current)};return n.jsx("div",{className:"titan-toast-surface",style:{position:"fixed",bottom:100,right:24,maxWidth:340,padding:"12px 14px",borderRadius:10,borderLeft:"3px solid var(--theme-accent)",fontSize:12,zIndex:60},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.8,color:"var(--theme-accent)",marginBottom:4,fontFamily:"var(--theme-font-mono)"},children:"TITAN noticed"}),n.jsx("div",{style:{lineHeight:1.45,color:"var(--theme-ink)"},children:t.rationale}),n.jsxs("div",{style:{fontSize:10,color:"var(--theme-ink-soft)",marginTop:6,textTransform:"uppercase",letterSpacing:.5,fontFamily:"var(--theme-font-mono)"},children:["suggestion: ",t.action]})]}),n.jsx("button",{onClick:a,"aria-label":"Dismiss",className:"titan-close-btn",style:{fontSize:16,lineHeight:1,marginTop:-2},children:"×"})]})})}function ta(){try{const t=JSON.parse(localStorage.getItem("titan-home-mascot-pos")||"");if(t&&t.x>=.02&&t.x<=.98&&t.y>=.02&&t.y<=.95)return t}catch{}return{x:.78,y:.24}}function em(){const[t,e]=w.useState("idle"),[s,r]=w.useState(null),[i,a]=w.useState(!1),[d,l]=w.useState(0),[c,f]=w.useState(!1),[b,u]=w.useState(ta),[p,m]=w.useState(ta),[y,_]=w.useState(!1),R=w.useRef(null),k=w.useRef(!1),I=w.useRef(!1);w.useEffect(()=>{I.current=window.matchMedia("(prefers-reduced-motion: reduce)").matches},[]),w.useEffect(()=>{const A=new Date,E=A.getHours(),N=E<5?"Burning the midnight oil?":E<12?"Morning.":E<18?"Afternoon.":"Evening.";A.getMonth()===6&&A.getDate()===4?r("Happy Independence Day! 🎆 Your AI, your hardware — fireworks on me."):r(`${N} What are we building?`),ue("/api/health",{headers:{"Content-Type":"application/json"}}).then(D=>D.json()).then(D=>{(D==null?void 0:D.onboarded)===!1&&(f(!0),r("Hi, I’m TITAN. I need a brain before we build — tap the wrench below."))}).catch(()=>{}),ue("/api/missions/recent?hours=48",{headers:{"Content-Type":"application/json"}}).then(D=>D.json()).then(D=>{const S=((D==null?void 0:D.missions)||[]).filter(T=>T.phase==="done");if(S.length>0){const T=String(S[0].title||"").slice(0,60);r(`${N} While you were gone I finished “${T}”. Want to see, or are we building something new?`)}}).catch(()=>{});try{const D=new Date().toISOString().slice(0,10),S=JSON.parse(localStorage.getItem("titan-streak")||"{}");let T=S.count||0;if(S.last!==D){const P=new Date(Date.now()-864e5).toISOString().slice(0,10);T=S.last===P?T+1:1,localStorage.setItem("titan-streak",JSON.stringify({last:D,count:T}))}l(T)}catch{}},[]),w.useEffect(()=>{let A=!1;const E=async()=>{try{const S=await(await ue("/api/heartbeat/latest",{headers:{"Content-Type":"application/json"}})).json();if(A||!S.note||k.current||localStorage.getItem("titan-heartbeat-seen")===S.note.at)return;localStorage.setItem("titan-heartbeat-seen",S.note.at),r(S.note.message),e("listening"),setTimeout(()=>{!A&&!k.current&&e("idle")},4e3)}catch{}};E();const N=setInterval(E,6e4);return()=>{A=!0,clearInterval(N)}},[]),w.useEffect(()=>{const A=N=>{const D=N.detail||{};D.state&&(e(D.state),k.current=D.state==="thinking"||D.state==="executing"),D.quip!==void 0&&r(D.quip)},E=()=>{e("idle"),k.current=!1,a(!0),r("Done ✨"),setTimeout(()=>a(!1),3200)};return window.addEventListener("titan:mascot:say",A),window.addEventListener("titan:mascot:celebrate",E),()=>{window.removeEventListener("titan:mascot:say",A),window.removeEventListener("titan:mascot:celebrate",E)}},[]),w.useEffect(()=>{if(y||I.current)return;const E=setInterval(()=>{if(k.current){m(b);return}m({x:Math.min(.95,Math.max(.05,b.x+(Math.random()-.5)*.14)),y:Math.min(.9,Math.max(.06,b.y+(Math.random()-.5)*.1))})},9e3+Math.random()*5e3);return()=>clearInterval(E)},[b,y]);const g=w.useCallback(A=>{var E,N;A.preventDefault(),(N=(E=A.currentTarget).setPointerCapture)==null||N.call(E,A.pointerId),R.current={id:A.pointerId,moved:!1},_(!0)},[]),j=w.useCallback(A=>{!R.current||R.current.id!==A.pointerId||(R.current.moved=!0,m({x:Math.min(.97,Math.max(.03,A.clientX/window.innerWidth)),y:Math.min(.95,Math.max(.03,A.clientY/window.innerHeight))}))},[]),v=w.useCallback(A=>{if(!R.current||R.current.id!==A.pointerId)return;const E=R.current.moved;R.current=null,_(!1),E?m(N=>{u(N);try{localStorage.setItem("titan-home-mascot-pos",JSON.stringify(N))}catch{}return N}):window.dispatchEvent(new CustomEvent("titan:chat:toggle",{detail:{open:!0}}))},[]);return n.jsxs("div",{"data-free-mascot":!0,onPointerDown:g,onPointerMove:j,onPointerUp:v,className:"fixed z-[70] flex flex-col items-center select-none",style:{left:`${p.x*100}vw`,top:`${p.y*100}vh`,transform:"translate(-50%, -50%)",transition:y?"none":"left 2.8s cubic-bezier(0.45, 0, 0.25, 1), top 2.8s cubic-bezier(0.45, 0, 0.25, 1)",cursor:y?"grabbing":"grab",touchAction:"none"},"aria-label":"TITAN — drag to place anywhere",title:"Drag me anywhere — I'll stay",children:[n.jsx(ua,{className:"relative",state:t,mood:i?"excited":"neutral",somaPoll:!i,size:116,quip:s,bubblePhase:"visible"}),d>1&&n.jsxs("div",{className:"mt-0.5 text-[11px] tabular-nums",style:{color:"var(--theme-accent)",fontFamily:"var(--theme-font-mono, monospace)"},title:`You've shown up ${d} days in a row`,children:["🔥 day ",d]}),c&&n.jsx("button",{onClick:()=>{window.location.href="/setup"},onPointerDown:A=>A.stopPropagation(),className:"mt-1.5 px-3 py-1.5 rounded-lg text-xs font-medium shadow-md",style:{background:"var(--theme-metal)",color:"var(--theme-bolt, #201406)"},children:"Set up TITAN (2 min)"})]})}function tm(t){switch(t){case"write_file":case"edit_file":case"apply_patch":return"writing it down…";case"read_file":case"list_files":return"reading through files…";case"shell":case"run_command":return"running a command…";case"web_search":case"web_fetch":case"web_browser":return"looking it up on the web…";case"gallery_search":case"widget_gallery":return"flipping through widget designs…";case"create_widget":case"update_widget":return"building it onto your desk…";case"weather":return"checking the weather…";case"memory_search":case"memory_map":return"remembering…";default:return t?`working (${t.replace(/_/g," ")})…`:"working…"}}function or(t,e){window.dispatchEvent(new CustomEvent("titan:mascot:say",{detail:{quip:t,state:e}}))}function sm(){try{let t=localStorage.getItem("titan-home-session");return t||(t=`home-${Math.random().toString(36).slice(2,10)}`,localStorage.setItem("titan-home-session",t)),t}catch{return"home-default"}}function nm(){const[t,e]=w.useState(""),[s,r]=w.useState([]),[i,a]=w.useState(!1),d=w.useRef(null),l=w.useRef(null),c=w.useRef(sm()),f=w.useCallback(()=>{const b=t.trim();if(!b||i)return;e(""),a(!0),or("thinking…","thinking"),r(m=>[...m.slice(-3),{ask:b,reply:"",pending:!0}]);const u=new AbortController;d.current=u;let p="";da(b,c.current,m=>{m.type==="token"?(p+=m.data,r(y=>y.map((_,R)=>R===y.length-1?{..._,reply:p}:_))):m.type==="tool_start"?or(tm(m.toolName),"executing"):m.type==="tool_end"?or(m.toolSuccess===!1?"hmm, trying another way…":"done with that — continuing…","executing"):m.type==="done"?!p&&m.data&&(p=m.data,r(y=>y.map((_,R)=>R===y.length-1?{..._,reply:p}:_))):m.type==="error"&&r(y=>y.map((_,R)=>R===y.length-1?{..._,reply:_.reply||`Something went wrong: ${m.errorMessage||m.data}. Try again?`}:_))},u.signal).catch(m=>{(m==null?void 0:m.name)!=="AbortError"&&r(y=>y.map((_,R)=>R===y.length-1?{..._,reply:_.reply||`I hit a snag: ${m.message}`}:_))}).finally(()=>{var m;a(!1),r(y=>y.map((_,R)=>R===y.length-1?{..._,pending:!1}:_)),window.dispatchEvent(new CustomEvent("titan:mascot:celebrate")),(m=l.current)==null||m.focus()})},[t,i]);return n.jsxs("div",{className:"flex flex-col h-full p-3 gap-3 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-2 rounded-xl border px-3 py-2.5 shadow-sm shrink-0",style:{background:"var(--theme-paper, var(--color-bg-secondary))",borderColor:"var(--theme-metal, var(--color-border))"},children:[n.jsx("input",{ref:l,value:t,onChange:b=>e(b.target.value),onKeyDown:b=>{b.key==="Enter"&&f()},placeholder:"Ask for anything — “make me a weather widget”, “research X and brief me”…",className:"flex-1 bg-transparent outline-none text-[14px]",style:{color:"var(--theme-ink, var(--color-text))",fontFamily:"var(--theme-font-display, inherit)"},"aria-label":"Ask TITAN"}),i?n.jsx("button",{onClick:()=>{var b;return(b=d.current)==null?void 0:b.abort()},"aria-label":"Stop",className:"p-1.5 rounded-lg",style:{color:"var(--theme-accent)"},children:n.jsx(ec,{size:16})}):n.jsx("button",{onClick:f,disabled:!t.trim(),"aria-label":"Send",className:"p-1.5 rounded-lg disabled:opacity-35",style:{background:"var(--theme-metal)",color:"var(--theme-bolt, #201406)"},children:n.jsx(hc,{size:16})})]}),n.jsxs("div",{className:"flex-1 overflow-auto space-y-2.5 min-h-0",children:[s.length===0&&n.jsx("p",{className:"text-xs opacity-60 px-1",style:{color:"var(--theme-ink-soft, var(--color-text-muted))"},children:"Whatever I build lands on this desk — and stays."}),[...s].reverse().map((b,u)=>n.jsxs("div",{className:"rounded-lg border px-3.5 py-2.5 shadow-sm",style:{background:"var(--theme-paper, var(--color-bg-secondary))",borderColor:"var(--theme-paper-line, var(--color-border))",color:"var(--theme-ink, var(--color-text))"},children:[n.jsxs("div",{className:"text-[10px] mb-1 opacity-60",style:{fontFamily:"var(--theme-font-mono, monospace)"},children:["you · ",b.ask]}),n.jsx("div",{className:"text-[13px] leading-relaxed whitespace-pre-wrap",style:{fontFamily:"var(--theme-font-display, inherit)"},children:b.reply||(b.pending?"…":"")})]},s.length-1-u))]})]})}const Nl="titan-sidebar-collapsed",Cl="titan-sidebar-canvas-pin";function Tl(t){return t==="/"||/^\/space\/[^/]+\/?$/.test(t)}function sa(t,e=s=>typeof localStorage>"u"?null:localStorage.getItem(s)){try{if(Tl(t))return e(Cl)!=="1";const s=e(Nl);if(s!==null)return s==="1"}catch{}return!1}function rm(t,e,s=(r,i)=>{typeof localStorage>"u"||localStorage.setItem(r,i)}){try{Tl(e)?s(Cl,t?"0":"1"):s(Nl,t?"1":"0")}catch{}}function im(){const t=typeof localStorage<"u"?localStorage.getItem("titan-token"):null;return t?{Authorization:`Bearer ${t}`}:{}}async function ds(t,e){const s=await fetch(t,{...e,headers:{"Content-Type":"application/json",...im(),...(e==null?void 0:e.headers)||{}}});if(!s.ok)throw new Error(`${s.status} ${s.statusText}`);return s.json()}function am(){const t=ha(),e=Pl(),{logout:s}=Wl(),[r,i]=w.useState([]),[a,d]=w.useState(null),[l,c]=w.useState([]),[f,b]=w.useState(!1),[u,p]=w.useState(!1),[m,y]=w.useState(null),[_,R]=w.useState(()=>sa(typeof window<"u"?window.location.pathname:"/"));w.useEffect(()=>{R(sa(e.pathname))},[e.pathname]);const k=w.useCallback(()=>{R(E=>{const N=!E;return rm(N,typeof window<"u"?window.location.pathname:"/"),N})},[]),I=w.useCallback(async()=>{try{const E=await ds("/api/spaces");i(E.spaces),d(E.activeSpaceId),y(null)}catch(E){y(E.message)}},[]);w.useEffect(()=>{I(),ds("/api/spaces/presets").then(N=>c(N.presets)).catch(()=>{});const E=()=>I();return window.addEventListener("titan:spaces:refresh",E),()=>window.removeEventListener("titan:spaces:refresh",E)},[I]);const g=w.useCallback(async E=>{try{await ds(`/api/spaces/${E}/activate`,{method:"POST"}),d(E),t(`/space/${E}`)}catch(N){y(N.message)}},[t]),j=w.useCallback(async E=>{p(!0);try{const N=E.preset?l.find(S=>S.id===E.preset):void 0,D=await ds("/api/spaces",{method:"POST",body:JSON.stringify({name:E.name||(N==null?void 0:N.name)||"New Space",icon:N==null?void 0:N.icon,color:N==null?void 0:N.color,makeActive:!0})});await I(),t(`/space/${D.space.id}`),b(!1)}catch(N){y(N.message)}finally{p(!1)}},[t,l,I]),v=w.useCallback(async E=>{if(window.confirm("Archive this Space? Widgets will be preserved and you can restore it later."))try{await ds(`/api/spaces/${E}`,{method:"DELETE"}),await I()}catch(N){y(N.message)}},[I]);if(!e.pathname.startsWith("/space")&&!e.pathname.startsWith("/mission")&&e.pathname!=="/")return null;const A=e.pathname.startsWith("/mission");return _?n.jsx("aside",{className:"w-3 bg-[#0a0e1a] border-r border-[#1f2937] relative flex-shrink-0",title:"Spaces sidebar — collapsed",children:n.jsx("button",{type:"button",onClick:k,className:"absolute top-3 left-full -translate-x-1/2 z-50 w-6 h-12 rounded-r-md bg-[#1f2937] border border-[#27272a] border-l-0 text-[#a1a1aa] hover:text-white hover:bg-[#27272a] flex items-center justify-center text-sm shadow-lg",title:"Show the spaces sidebar","aria-label":"Show sidebar",children:"›"})}):n.jsxs("aside",{className:"w-60 flex flex-col relative flex-shrink-0",style:{background:"var(--theme-menu-bg-solid, #0a0e1a)",borderRight:"1px solid var(--theme-menu-border, #1f2937)",color:"var(--theme-ink, #d4d4d8)",fontFamily:"var(--theme-font-display, ui-sans-serif, system-ui)"},children:[n.jsxs("div",{className:"px-4 pt-4 pb-3 flex items-center justify-between",style:{borderBottom:"1px solid var(--theme-menu-border, #1f2937)"},children:[n.jsxs("button",{type:"button",onClick:()=>t("/space/home"),className:"flex items-center gap-2 group",title:"TITAN home",children:[n.jsx("span",{className:"w-7 h-7 rounded-md flex items-center justify-center text-[14px] font-bold leading-none",style:{background:"var(--theme-metal, #c4a35a)",color:"var(--theme-bolt, #2a1808)",boxShadow:"0 1px 2px var(--theme-shadow, rgba(0,0,0,0.3))",fontFamily:"var(--theme-font-display, serif)"},children:"T"}),n.jsx("span",{className:"text-[15px] tracking-[0.18em] font-semibold leading-none",style:{color:"var(--theme-ink, #e8e8ff)"},children:"TITAN"})]}),n.jsx("button",{type:"button",onClick:k,className:"w-6 h-6 rounded-md flex items-center justify-center text-base transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},title:"Hide sidebar","aria-label":"Hide sidebar",children:"‹"})]}),n.jsxs("nav",{className:"flex-1 overflow-y-auto py-3 px-2",children:[n.jsxs("div",{className:"mb-5",children:[n.jsx(na,{children:"Missions"}),n.jsx(ra,{onClick:()=>t("/mission"),active:A&&e.pathname==="/mission",icon:"✶",label:"New Mission",title:"Start a new mission or pick a template"}),n.jsx(ra,{onClick:()=>t("/mission/library"),active:e.pathname==="/mission/library",icon:"❑",label:"Library",title:"Every mission you've run"})]}),n.jsxs("div",{className:"mb-2 flex items-center justify-between px-2",children:[n.jsx(na,{inline:!0,children:"Workspaces"}),n.jsx("button",{type:"button",onClick:()=>b(!0),className:"w-5 h-5 rounded flex items-center justify-center text-sm leading-none transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:E=>{E.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",E.currentTarget.style.color="var(--theme-ink, #fff)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent",E.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},title:"Create a new Workspace","aria-label":"Create a new Workspace",children:"+"})]}),m&&n.jsx("div",{className:"mx-1 my-1 px-2 py-2 text-[11px] rounded",style:{color:"var(--theme-accent, #ef4444)",background:"rgba(239,68,68,0.08)"},children:m}),r.length===0&&!m&&n.jsxs("div",{className:"px-2 py-3 text-[11px] leading-relaxed italic",style:{color:"var(--theme-ink-soft, #71717a)"},children:["No Workspaces yet. Tap + above, or ask TITAN",n.jsx("br",{}),'"make me a workspace for…"']}),r.map(E=>{const N=E.id===a;return n.jsxs("button",{type:"button",onClick:()=>g(E.id),onContextMenu:D=>{D.preventDefault(),v(E.id)},className:"w-full text-left px-2 py-1.5 rounded text-[13px] flex items-center gap-2 transition-colors",style:{background:N?"var(--theme-menu-active-bg, #1f2937)":"transparent",color:N?"var(--theme-menu-active-fg, #fff)":"var(--theme-ink, #d4d4d8)"},onMouseEnter:D=>{N||(D.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))")},onMouseLeave:D=>{N||(D.currentTarget.style.background="transparent")},title:`${E.name} · right-click to archive`,children:[E.icon&&n.jsx("span",{className:"text-base leading-none",children:E.icon}),n.jsx("span",{className:"flex-1 truncate",children:E.name}),E.widgets.length>0&&n.jsx("span",{className:"text-[10px] tabular-nums px-1.5 rounded-full",style:{color:"var(--theme-ink-soft, #71717a)",background:"var(--theme-menu-hover, rgba(244,215,145,0.10))"},children:E.widgets.length})]},E.id)})]}),n.jsxs("div",{className:"px-2 py-2 flex flex-col gap-0.5",style:{borderTop:"1px solid var(--theme-menu-border, #1f2937)"},children:[n.jsxs("a",{href:"/command-post",className:"px-2 py-1.5 rounded text-[12px] flex items-center gap-2 transition-colors no-underline",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:E=>{E.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",E.currentTarget.style.color="var(--theme-ink, #fff)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent",E.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},children:[n.jsx("span",{"aria-hidden":!0,children:"⚙"}),n.jsx("span",{children:"Admin"})]}),n.jsxs("button",{type:"button",onClick:()=>{s(),window.location.assign("/")},className:"w-full text-left px-2 py-1.5 rounded text-[12px] flex items-center gap-2 transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:E=>{E.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",E.currentTarget.style.color="var(--theme-accent, #ef4444)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent",E.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},title:"Sign out — mints a fresh token next login",children:[n.jsx("span",{"aria-hidden":!0,children:"⇥"}),n.jsx("span",{children:"Sign out"})]})]}),f&&n.jsx(om,{presets:l,creating:u,onCreate:j,onClose:()=>b(!1)})]})}function om(t){const{presets:e,creating:s,onCreate:r,onClose:i}=t,[a,d]=w.useState(""),[l,c]=w.useState(void 0);return n.jsx("div",{className:"fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4",onClick:i,children:n.jsxs("div",{className:"bg-[#0a0e1a] border border-[#1f2937] rounded-lg p-5 w-full max-w-md",onClick:f=>f.stopPropagation(),children:[n.jsx("div",{className:"text-sm font-medium text-white mb-4",children:"New Space"}),n.jsx("label",{className:"block text-[11px] text-[#a1a1aa] mb-1",children:"Starter preset (optional)"}),n.jsx("div",{className:"grid grid-cols-2 gap-2 mb-4",children:e.map(f=>n.jsxs("button",{type:"button",onClick:()=>{c(f.id),a||d(f.name)},className:`text-left px-3 py-2 rounded border ${l===f.id?"border-[#3b82f6] bg-[#0f172a]":"border-[#1f2937] hover:border-[#374151]"}`,title:f.tagline,children:[n.jsxs("div",{className:"text-sm flex items-center gap-2 text-white",children:[n.jsx("span",{children:f.icon}),n.jsx("span",{children:f.name})]}),n.jsx("div",{className:"text-[10px] text-[#71717a] mt-0.5 line-clamp-1",children:f.tagline})]},f.id))}),n.jsx("label",{className:"block text-[11px] text-[#a1a1aa] mb-1",children:"Name"}),n.jsx("input",{type:"text",value:a,onChange:f=>d(f.target.value),placeholder:"My Workspace",className:"w-full bg-[#0d1117] border border-[#1f2937] rounded px-3 py-2 text-sm text-white mb-4",autoFocus:!0}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:i,className:"px-3 py-1.5 text-sm text-[#a1a1aa] hover:text-white",children:"Cancel"}),n.jsx("button",{type:"button",onClick:()=>r({name:a.trim(),preset:l}),disabled:s||!a.trim()&&!l,className:"px-3 py-1.5 bg-[#3b82f6] hover:bg-[#2563eb] disabled:opacity-50 text-white text-sm rounded",children:s?"Creating…":"Create"})]})]})})}function na({children:t,inline:e=!1}){return n.jsx("div",{className:`${e?"":"px-2 mb-1.5"} text-[10px] uppercase tracking-[0.18em] font-semibold`,style:{color:"var(--theme-metal, #c4a35a)"},children:t})}function ra({active:t,icon:e,label:s,title:r,onClick:i}){return n.jsxs("button",{type:"button",onClick:i,className:"w-full text-left px-2 py-1.5 rounded text-[13px] flex items-center gap-2 transition-colors",style:{background:t?"var(--theme-menu-active-bg, #1f2937)":"transparent",color:t?"var(--theme-menu-active-fg, #fff)":"var(--theme-ink, #d4d4d8)"},onMouseEnter:a=>{t||(a.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))")},onMouseLeave:a=>{t||(a.currentTarget.style.background="transparent")},title:r,children:[n.jsx("span",{className:"w-5 text-center leading-none",style:{color:t?"var(--theme-menu-active-fg, #fff)":"var(--theme-metal, #c4a35a)"},"aria-hidden":!0,children:e}),n.jsx("span",{className:"flex-1 truncate",children:s})]})}const lr=4e3,lm=[{label:"Focused research partner",body:"You are in the research space. Prefer brief answers with citations. When the user asks a question, default to summarising authoritative sources over generating widgets. Suggest a follow-up question at the end of each response."},{label:"Hands-on builder",body:"You are in the build space. Prefer writing + iterating on widgets over explanation. Keep prose to under 2 sentences per reply. Generate widgets with `canvas.createWidget` whenever the user describes a tool they want."},{label:"Ops / monitoring",body:"You are in the ops space. Prioritise live data — API calls, log tails, health checks. Use titan.api.call and titan.fetch liberally. Surface numbers in tables or small stat widgets."},{label:"Casual / playful",body:"You are in the play space. Relaxed tone, emojis welcome, riff on user ideas, generate fun widgets. Explain trade-offs only if asked."}];function cm({space:t,open:e,onClose:s,onSaved:r}){const[i,a]=w.useState(t.agentInstructions??""),[d,l]=w.useState(!1),[c,f]=w.useState(null),b=w.useRef(null);w.useEffect(()=>{if(e){a(t.agentInstructions??""),f(null);const p=setTimeout(()=>{var m;return(m=b.current)==null?void 0:m.focus()},50);return()=>clearTimeout(p)}},[e,t.id,t.agentInstructions]),w.useEffect(()=>{if(!e)return;const p=m=>{m.key==="Escape"&&s(),m.key==="Enter"&&(m.metaKey||m.ctrlKey)&&u()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e]);const u=w.useCallback(async()=>{if(i.length>lr){f(`Instructions must be ${lr} characters or fewer.`);return}l(!0),f(null);try{const p=i.trim(),m={...t,agentInstructions:p||void 0,updatedAt:new Date().toISOString()};ve.save(m),r==null||r(p),s()}catch(p){f(p.message)}finally{l(!1)}},[i,t,r,s]);return e?n.jsx("div",{className:"fixed inset-0 z-[2147483100] flex items-center justify-center p-4",style:{background:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(4px)"},onClick:s,children:n.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-[#27272a] bg-[#0c0c10] shadow-2xl flex flex-col max-h-[85vh]",onClick:p=>p.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ys,{className:"w-4 h-4 text-[#6366f1]"}),n.jsxs("h3",{className:"font-semibold text-white text-sm",children:["Agent instructions — ",n.jsx("span",{style:{color:t.color||"#6366f1"},children:t.name})]})]}),n.jsx("button",{onClick:s,className:"p-1 rounded hover:bg-[#27272a] text-[#71717a] hover:text-white transition-colors",title:"Close (Esc)",children:n.jsx(Ts,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"p-5 flex-1 overflow-auto space-y-3",children:[n.jsx("p",{className:"text-[11px] text-[#a1a1aa] leading-relaxed",children:"These instructions are injected into the chat’s system prompt whenever this space is active. Use them to give the agent a persona, a rule set, or a focus area — the chat will behave differently here vs. other spaces."}),n.jsx("textarea",{ref:b,value:i,onChange:p=>a(p.target.value),placeholder:"e.g. You're in the research space — prefer concise, sourced answers over widget generation.",spellCheck:!1,className:"w-full h-48 p-3 rounded-lg border border-[#27272a] bg-[#09090c] text-[13px] text-[#e4e4e7] leading-relaxed font-mono resize-y focus:outline-none focus:border-[#6366f1]/60"}),n.jsxs("div",{className:"flex items-center justify-between text-[10px] text-[#71717a]",children:[n.jsxs("span",{children:[i.length.toLocaleString()," / ",lr.toLocaleString()," characters"]}),n.jsx("span",{children:"⌘/Ctrl + Enter to save"})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-[#71717a] mb-2",children:"Quick presets"}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:lm.map(p=>n.jsxs("button",{onClick:()=>a(p.body),className:"text-left p-3 rounded-lg border border-[#27272a] bg-[#18181b]/60 hover:border-[#6366f1]/50 hover:bg-[#18181b] transition-colors",children:[n.jsx("div",{className:"text-[11px] font-medium text-white mb-1",children:p.label}),n.jsx("div",{className:"text-[10px] text-[#a1a1aa] line-clamp-2 leading-relaxed",children:p.body})]},p.label))})]}),c&&n.jsx("div",{className:"text-[11px] text-[#ef4444] bg-[#ef4444]/10 border border-[#ef4444]/30 rounded p-2",children:c})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-[#27272a]",children:[n.jsx("button",{onClick:s,className:"px-3 py-1.5 rounded-lg text-[12px] text-[#a1a1aa] hover:text-white hover:bg-[#18181b] transition-colors",children:"Cancel"}),n.jsxs("button",{onClick:()=>{u()},disabled:d,className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-lg bg-[#6366f1] hover:bg-[#4f46e5] disabled:opacity-60 text-white text-[12px] font-medium transition-colors",children:[n.jsx(wn,{className:"w-3.5 h-3.5"}),d?"Saving…":"Save"]})]})]})}):null}const dm=12,um=["react","vanilla","html"];function hm({widget:t,spaceId:e,open:s,onClose:r,onSaved:i}){const[a,d]=w.useState(t.source),[l,c]=w.useState(t.format),[f,b]=w.useState(t.name),[u,p]=w.useState(!1),[m,y]=w.useState(null),[_,R]=w.useState(!1),[k,I]=w.useState(""),[g,j]=w.useState(!1),[v,A]=w.useState(null),E=w.useRef(null);w.useEffect(()=>{if(s){d(t.source),c(t.format),b(t.name),y(null),R(!1);const M=setTimeout(()=>{var F;return(F=E.current)==null?void 0:F.focus()},50);return()=>clearTimeout(M)}},[s,t.id,t.source,t.format,t.name]),w.useEffect(()=>{if(!s)return;const M=F=>{F.key==="Escape"&&r(),F.key==="Enter"&&(F.metaKey||F.ctrlKey)&&N()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[s]);const N=w.useCallback(async()=>{p(!0),y(null);try{const M=a!==t.source||l!==t.format,F=Array.isArray(t.versions)?t.versions:[],V=M?[...F,{source:t.source,format:t.format,savedAt:t.updatedAt}].slice(-dm):F,Y={name:f.trim()||t.name,source:a,format:l,versions:V};ve.updateWidget(e,t.id,Y),i==null||i({...t,...Y,updatedAt:Date.now()}),r()}catch(M){y(M.message)}finally{p(!1)}},[a,l,f,t,e,i,r]),D=w.useCallback(M=>{d(M.source),c(M.format),R(!1)},[]),S=w.useCallback(async()=>{const M=k.trim();if(!(!M||g)){j(!0),A(null),y(null),Ul("Editing your widget…");try{const F=await ue("/api/widget/assist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:a,format:l,name:f,instruction:M})}).then(V=>V.json());F&&typeof F.source=="string"&&F.source.trim()?(d(F.source),A("✨ Updated from your request — review below, then Save. (History can undo.)"),I("")):y((F==null?void 0:F.message)||"The AI couldn't edit the widget — try rephrasing your request.")}catch(F){y(F.message)}finally{j(!1),Bl()}}},[k,g,a,l,f]);if(!s)return null;const T=Array.isArray(t.versions)?t.versions:[],P=[...T].reverse();return n.jsx("div",{className:"fixed inset-0 z-[2147483200] flex items-center justify-center p-4",style:{background:"rgba(0, 0, 0, 0.66)",backdropFilter:"blur(4px)"},onClick:r,children:n.jsxs("div",{className:"w-full max-w-4xl rounded-2xl border border-[#27272a] bg-[#0c0c10] shadow-2xl flex flex-col",style:{height:"min(720px, 85vh)"},onClick:M=>M.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(sc,{className:"w-4 h-4 text-[#6366f1] shrink-0"}),n.jsx("input",{value:f,onChange:M=>b(M.target.value),className:"bg-transparent text-white text-sm font-semibold outline-none border-b border-transparent focus:border-[#6366f1]/60 min-w-0 flex-1"}),n.jsx("span",{className:"text-[10px] font-mono text-[#52525b] shrink-0",children:t.id.slice(0,14)})]}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[n.jsx("button",{onClick:()=>R(M=>!M),disabled:T.length===0,className:`p-1.5 rounded text-[#a1a1aa] hover:bg-[#18181b] hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${_?"bg-[#18181b] text-white":""}`,title:T.length===0?"No history yet":`${T.length} prior version${T.length===1?"":"s"}`,children:n.jsx(Nc,{className:"w-4 h-4"})}),n.jsx("button",{onClick:r,className:"p-1.5 rounded text-[#71717a] hover:bg-[#18181b] hover:text-white transition-colors",title:"Close (Esc)",children:n.jsx(Ts,{className:"w-4 h-4"})})]})]}),n.jsxs("div",{className:"flex items-center gap-3 px-5 py-2 border-b border-[#27272a] text-[11px]",children:[n.jsxs("label",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-[#71717a]",children:"format"}),n.jsx("select",{value:l,onChange:M=>c(M.target.value),className:"bg-[#18181b] border border-[#27272a] rounded px-2 py-0.5 text-[#e4e4e7] focus:outline-none focus:border-[#6366f1]/60",children:um.map(M=>n.jsx("option",{value:M,children:M},M))})]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("span",{className:"text-[#71717a]",children:["updated ",n.jsx("span",{className:"text-[#a1a1aa]",children:new Date(t.updatedAt).toLocaleString()})]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("span",{className:"text-[#71717a]",children:[t.w," × ",t.h," grid cells"]}),n.jsx("div",{className:"ml-auto text-[10px] text-[#52525b]",children:"⌘/Ctrl + Enter to save"})]}),n.jsxs("div",{className:"flex items-center gap-2 px-5 py-2.5 border-b border-[#27272a] bg-[#0e0b16]",children:[n.jsx(qt,{className:"w-4 h-4 text-[#a855f7] shrink-0"}),n.jsx("input",{value:k,onChange:M=>I(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.shiftKey&&(M.preventDefault(),S())},disabled:g,placeholder:"Ask the AI to change this widget — e.g. “make the background a warm gradient and the text bigger”",className:"flex-1 bg-transparent text-[12.5px] text-[#e4e4e7] placeholder:text-[#6b6b76] outline-none disabled:opacity-60"}),n.jsxs("button",{onClick:()=>{S()},disabled:g||!k.trim(),className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[#a855f7]/15 text-[#c084fc] border border-[#a855f7]/30 text-[11px] font-medium hover:bg-[#a855f7]/25 disabled:opacity-50 transition-colors shrink-0",children:[n.jsx(qt,{className:"w-3.5 h-3.5"}),g?"AI is editing…":"Ask AI"]})]}),v&&n.jsx("div",{className:"px-5 py-1.5 text-[11px] text-[#c084fc] border-b border-[#27272a] bg-[#0e0b16]",children:v}),n.jsxs("div",{className:"flex-1 flex min-h-0",children:[n.jsx("textarea",{ref:E,value:a,onChange:M=>d(M.target.value),spellCheck:!1,className:"flex-1 p-4 bg-[#09090c] text-[12.5px] text-[#e4e4e7] leading-relaxed font-mono resize-none focus:outline-none border-r border-[#27272a]",placeholder:fm[l]}),_&&n.jsxs("div",{className:"w-72 flex flex-col border-l border-[#27272a] bg-[#0a0a0e]",children:[n.jsxs("div",{className:"px-3 py-2 border-b border-[#27272a] text-[10px] uppercase tracking-wider text-[#71717a]",children:["History (",T.length,")"]}),n.jsxs("div",{className:"flex-1 overflow-auto",children:[P.length===0&&n.jsx("div",{className:"p-3 text-[11px] text-[#52525b]",children:"No prior versions yet — save to start tracking."}),P.map((M,F)=>n.jsxs("div",{className:"px-3 py-2 border-b border-[#18181b] hover:bg-[#18181b]/40 transition-colors",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[n.jsx("div",{className:"text-[10px] font-mono text-[#a1a1aa]",children:new Date(M.savedAt).toLocaleString()}),n.jsxs("button",{onClick:()=>D(M),className:"inline-flex items-center gap-1 text-[10px] text-[#6366f1] hover:text-[#a5b4fc] transition-colors",title:"Load this version into the editor",children:[n.jsx(ba,{className:"w-3 h-3"}),"revert"]})]}),n.jsxs("div",{className:"text-[10px] text-[#71717a] font-mono",children:["format: ",M.format]}),n.jsxs("div",{className:"text-[10px] text-[#52525b] truncate mt-1",title:M.source.slice(0,280),children:[M.source.slice(0,80),M.source.length>80?"…":""]}),F===0&&n.jsx("div",{className:"text-[9px] text-[#6366f1] mt-1",children:"most recent before current"})]},M.savedAt))]})]})]}),n.jsxs("div",{className:"flex items-center justify-between gap-2 px-5 py-3 border-t border-[#27272a]",children:[n.jsx("div",{className:"text-[10px] text-[#71717a]",children:m?n.jsxs("span",{className:"text-[#ef4444]",children:["Error: ",m]}):a!==t.source||l!==t.format||f!==t.name?"Unsaved changes":"Up to date"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:r,className:"px-3 py-1.5 rounded-lg text-[12px] text-[#a1a1aa] hover:text-white hover:bg-[#18181b] transition-colors",children:"Cancel"}),n.jsxs("button",{onClick:()=>{N()},disabled:u,className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-lg bg-[#6366f1] hover:bg-[#4f46e5] disabled:opacity-60 text-white text-[12px] font-medium transition-colors",children:[n.jsx(wn,{className:"w-3.5 h-3.5"}),u?"Saving…":"Save widget"]})]})]})]})})}const fm={react:`// Return a React component named "Widget". titan.* APIs are
812
- // available for fetch/api/state. Example:
813
- function Widget({ titan }) {
814
- const [n, setN] = React.useState(0);
815
- return <button onClick={() => setN(n + 1)}>Clicked {n} times</button>;
816
- }`,vanilla:`// Export a function (container, titan) => cleanup | void.
817
- // Called once to mount; return a cleanup function if needed.
818
- (container, titan) => {
819
- container.innerHTML = '<button>Hello</button>';
820
- const btn = container.querySelector('button');
821
- btn.addEventListener('click', () => btn.textContent = 'Clicked!');
822
- }`,html:`<!-- Raw HTML. No scripts run. -->
823
- <div style="padding:16px;color:#e4e4e7">Hello, widget!</div>`,iframe:"",system:""};function pm(t){return String(t||"").startsWith("system:")?"system":"react"}const mm={productivity:"#a78bfa",finance:"#34d399","health-fitness":"#f472b6","music-dj":"#c084fc",creative:"#fb923c",travel:"#60a5fa",gaming:"#f87171",social:"#38bdf8",cooking:"#fbbf24",vehicle:"#94a3b8",homelab:"#a3e635","ml-ai":"#818cf8",research:"#2dd4bf",document:"#f9a8d4",devops:"#fcd34d","e-commerce":"#fda4af",lifestyle:"#86efac",web:"#67e8f9",data:"#d8b4fe","multi-modal":"#fdba74",automation:"#facc15","smart-home":"#bef264",agents:"#e879f9","software-builder":"#7dd3fc",utilities:"#a5b4fc",media:"#fca5a5",communication:"#5eead4",education:"#c4b5fd",misc:"#9ca3af"};function gm(t){return t.split(/[-_/]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function ym({open:t,onClose:e}){const[s,r]=w.useState([]),[i,a]=w.useState([]),[d,l]=w.useState("All"),[c,f]=w.useState(""),[b,u]=w.useState(null),[p,m]=w.useState(!1),[y,_]=w.useState(null);w.useEffect(()=>{t&&(m(!0),ue("/api/widget-gallery").then(g=>g.json()).then(g=>{r(g.templates||[]),a(g.categories||[]),m(!1)}).catch(g=>{_(g.message),m(!1)}))},[t]),w.useEffect(()=>{if(!t)return;const g=j=>{j.key==="Escape"&&e()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t,e]);const R=w.useMemo(()=>{const g=d==="All"?s:s.filter(v=>v.category===d),j=c.trim().toLowerCase();return j?g.filter(v=>[v.name,v.description,v.category,...v.tags||[],...v.triggers||[]].join(" ").toLowerCase().includes(j)):g},[d,c,s]);if(!t)return null;const k=async g=>{var j,v,A,E;u(g.id),_(null);try{const N=await ue(`/api/widget-gallery/${encodeURIComponent(g.id)}`);if(!N.ok)throw new Error(`Could not load template (${N.status})`);const D=await N.json(),S={templateId:g.id,templateName:D.name||g.name,source:D.source,format:pm(D.source),defaultSize:{w:((j=D.defaultSize)==null?void 0:j.w)??((v=g.defaultSize)==null?void 0:v.w)??4,h:((A=D.defaultSize)==null?void 0:A.h)??((E=g.defaultSize)==null?void 0:E.h)??4}};window.dispatchEvent(new CustomEvent("titan:gallery:run-template",{detail:S})),e()}catch(N){_(N.message)}finally{u(null)}},I=["All",...i.map(g=>g.category)];return n.jsx("div",{className:"fixed inset-0 z-[2147483150] flex items-center justify-center p-3 sm:p-4 titan-menu-overlay",onClick:e,children:n.jsxs("div",{className:"w-full max-w-5xl titan-widget-gallery-window flex flex-col",style:{height:"min(760px, 92vh)"},onClick:g=>g.stopPropagation(),children:[n.jsxs("div",{className:"titan-widget-gallery-titlebar",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"titan-window-dot"}),n.jsx("span",{className:"titan-window-dot titan-window-dot--dim"}),n.jsx("span",{className:"titan-window-dot titan-window-dot--dim"}),n.jsx(qt,{className:"w-4 h-4 ml-1",style:{color:"var(--theme-accent)"}}),n.jsx("h3",{className:"font-semibold text-sm",style:{color:"var(--theme-ink)",fontFamily:"var(--theme-font-display)"},children:"Widget gallery"}),n.jsx("span",{className:"text-[10px]",style:{color:"var(--theme-ink-soft)"},children:p?"Loading…":`${s.length} templates`})]}),n.jsx("button",{onClick:e,className:"titan-close-btn",title:"Close (Esc)","aria-label":"Close",children:n.jsx(Ts,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"titan-widget-gallery-category-row",children:I.map(g=>{var j;return n.jsxs("button",{onClick:()=>l(g),className:`titan-widget-gallery-category ${d===g?"titan-widget-gallery-category--active":""}`,children:[gm(g),g!=="All"&&n.jsx("span",{className:"ml-1.5 text-[9px] opacity-70",children:((j=i.find(v=>v.category===g))==null?void 0:j.count)??0})]},g)})}),n.jsx("div",{className:"px-4 sm:px-5 py-2 border-b",style:{borderColor:"var(--theme-menu-border)"},children:n.jsxs("label",{className:"titan-widget-gallery-search",children:[n.jsx(xa,{className:"w-3.5 h-3.5"}),n.jsx("input",{value:c,onChange:g=>f(g.target.value),placeholder:"Search templates...",className:"flex-1 bg-transparent text-xs outline-none"})]})}),n.jsxs("div",{className:"flex-1 overflow-auto p-4",children:[p&&n.jsx("div",{className:"flex items-center justify-center h-full text-sm",style:{color:"var(--theme-ink-soft)"},children:"Loading templates…"}),y&&n.jsxs("div",{className:"flex items-center justify-center h-full text-sm",style:{color:"var(--color-error)"},children:["Error: ",y]}),!p&&!y&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:R.map(g=>n.jsxs("button",{onClick:()=>k(g),disabled:b!==null,className:"titan-widget-gallery-card group",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{background:mm[g.category]??"#9ca3af"}}),n.jsx("span",{className:"text-[12px] font-medium truncate",style:{color:"var(--theme-ink)"},children:g.name})]}),n.jsx(wa,{className:"w-3 h-3 transition-colors shrink-0"})]}),n.jsx("div",{className:"text-[11px] leading-relaxed line-clamp-2",style:{color:"var(--theme-ink-soft)"},children:b===g.id?"Adding to canvas...":g.description}),g.tags&&g.tags.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:g.tags.slice(0,3).map(j=>n.jsx("span",{className:"titan-widget-gallery-tag",children:j},j))})]},g.id))}),R.length===0&&n.jsx("div",{className:"flex items-center justify-center h-40 text-sm",style:{color:"var(--theme-ink-soft)"},children:"No templates in this category."})]}),n.jsxs("div",{className:"titan-widget-gallery-note",children:[n.jsx(Ea,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),n.jsxs("div",{className:"text-[11px] leading-relaxed",children:["Don’t see what you want? Open the chat (click the mascot) and describe your widget in plain English. TITAN can build anything that runs inside a sandboxed iframe with access to ",n.jsx("span",{className:"font-mono",children:"titan.fetch"}),","," ",n.jsx("span",{className:"font-mono",children:"titan.api.call"}),", and"," ",n.jsx("span",{className:"font-mono",children:"titan.state"}),"."]})]})]})]})})}const bm=[{type:"widget",source:"system:nav",name:"Nav Widget",w:3,h:4,icon:n.jsx(Ea,{className:"w-4 h-4"})},{type:"widget",source:"system:chat",name:"Chat Widget",w:4,h:5,icon:n.jsx(vn,{className:"w-4 h-4"})},{type:"widget",source:"system:soma",name:"SOMA",w:6,h:6,icon:n.jsx(bt,{className:"w-4 h-4"})},{type:"widget",source:"system:command-post",name:"Command Post",w:8,h:6,icon:n.jsx(ya,{className:"w-4 h-4"})},{type:"widget",source:"system:intelligence",name:"Intelligence",w:6,h:5,icon:n.jsx(ga,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-graph",name:"Memory Graph",w:8,h:7,icon:n.jsx(bc,{className:"w-4 h-4"})},{type:"widget",source:"system:voice",name:"Voice",w:5,h:5,icon:n.jsx(va,{className:"w-4 h-4"})},{type:"widget",source:"system:infra",name:"Infrastructure",w:6,h:4,icon:n.jsx(Or,{className:"w-4 h-4"})},{type:"widget",source:"system:tools",name:"Tools",w:5,h:4,icon:n.jsx(Rr,{className:"w-4 h-4"})},{type:"widget",source:"system:settings",name:"Settings",w:5,h:5,icon:n.jsx(Mr,{className:"w-4 h-4"})},{type:"widget",source:"system:files",name:"Files",w:4,h:6,icon:n.jsx(xn,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-wiki",name:"Memory Wiki",w:6,h:6,icon:n.jsx(ys,{className:"w-4 h-4"})},{type:"widget",source:"system:autoresearch",name:"Autoresearch",w:6,h:6,icon:n.jsx(_a,{className:"w-4 h-4"})},{type:"widget",source:"system:self-proposals",name:"Self-Proposals",w:6,h:6,icon:n.jsx(Xs,{className:"w-4 h-4"})},{type:"widget",source:"system:muscle-memory",name:"Muscle Memory",w:6,h:7,icon:n.jsx(Xs,{className:"w-4 h-4"})},{type:"widget",source:"system:overview",name:"Overview",w:6,h:5,icon:n.jsx(fa,{className:"w-4 h-4"})},{type:"widget",source:"system:sessions",name:"Sessions",w:6,h:5,icon:n.jsx(bs,{className:"w-4 h-4"})},{type:"widget",source:"system:watch",name:"Watch",w:8,h:7,icon:n.jsx(Kt,{className:"w-4 h-4"})},{type:"widget",source:"system:backup",name:"Backup Manager",w:6,h:6,icon:n.jsx(ka,{className:"w-4 h-4"})},{type:"widget",source:"system:training",name:"Training Dashboard",w:6,h:6,icon:n.jsx(bt,{className:"w-4 h-4"})},{type:"widget",source:"system:recipes",name:"Recipe Kitchen",w:6,h:6,icon:n.jsx(ys,{className:"w-4 h-4"})},{type:"widget",source:"system:vram",name:"VRAM Monitor",w:6,h:6,icon:n.jsx(Ir,{className:"w-4 h-4"})},{type:"widget",source:"system:teams",name:"Team Hub",w:6,h:6,icon:n.jsx(Lr,{className:"w-4 h-4"})},{type:"widget",source:"system:cron",name:"Cron Scheduler",w:6,h:6,icon:n.jsx(bs,{className:"w-4 h-4"})},{type:"widget",source:"system:checkpoints",name:"Checkpoints",w:6,h:5,icon:n.jsx(wn,{className:"w-4 h-4"})},{type:"widget",source:"system:organism",name:"Organism Monitor",w:6,h:6,icon:n.jsx(Dr,{className:"w-4 h-4"})},{type:"widget",source:"system:fleet",name:"Fleet Router",w:6,h:5,icon:n.jsx(Sa,{className:"w-4 h-4"})},{type:"widget",source:"system:browser",name:"Browser Tools",w:6,h:5,icon:n.jsx(pa,{className:"w-4 h-4"})},{type:"widget",source:"system:eval",name:"Test Lab",w:6,h:6,icon:n.jsx(ja,{className:"w-4 h-4"})}];function Al({currentSpaceId:t,onSpaceSelect:e,onAction:s,onClose:r}){const[i,a]=w.useState(""),[d,l]=w.useState(0),c=w.useRef(null),f=ve.list(),b=w.useMemo(()=>{const u=i.toLowerCase(),p=f.filter(y=>y.id!==t&&y.name.toLowerCase().includes(u)).map(y=>({type:"space",id:y.id,name:y.name,color:y.color})),m=bm.filter(y=>y.name.toLowerCase().includes(u)).map(y=>({type:"action",action:y,name:y.name}));return[...p,...m]},[i,f,t]);return w.useEffect(()=>{var u;(u=c.current)==null||u.focus()},[]),w.useEffect(()=>{l(0)},[i]),w.useEffect(()=>{const u=p=>{if((p.metaKey||p.ctrlKey)&&p.key.toLowerCase()==="k"){p.preventDefault(),r();return}if(p.key==="Escape"){r();return}if(p.key==="ArrowDown"){p.preventDefault(),l(m=>Math.min(m+1,b.length-1));return}if(p.key==="ArrowUp"){p.preventDefault(),l(m=>Math.max(m-1,0));return}if(p.key==="Enter"){p.preventDefault();const m=b[d];if(!m)return;m.type==="space"&&e(m.id),m.type==="action"&&s(m.action)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[b,d,e,s,r]),n.jsx("div",{className:"fixed inset-0 z-[2147483200] flex items-start justify-center pt-[20vh]",onClick:r,children:n.jsxs("div",{className:"w-full max-w-lg bg-[#18181b]/98 backdrop-blur-xl border border-[#27272a]/60 rounded-2xl shadow-2xl shadow-black/60 overflow-hidden",onClick:u=>u.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#27272a]/40",children:[n.jsx(xa,{className:"w-4 h-4 text-[#3f3f46]"}),n.jsx("input",{ref:c,value:i,onChange:u=>a(u.target.value),placeholder:"Search spaces, widgets, actions...",className:"flex-1 bg-transparent text-sm text-[#e4e4e7] placeholder:text-[#3f3f46] outline-none"}),n.jsx("button",{onClick:r,className:"text-[#3f3f46] hover:text-[#71717a]",children:n.jsx(Ts,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"max-h-[50vh] overflow-auto py-1",children:[b.length===0&&n.jsxs("div",{className:"px-4 py-6 text-center text-xs text-[#52525b]",children:['No results for "',i,'"']}),b.map((u,p)=>n.jsxs("button",{onClick:()=>{u.type==="space"&&e(u.id),u.type==="action"&&s(u.action)},className:`w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors ${p===d?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#a1a1aa] hover:bg-[#27272a]/30"}`,children:[u.type==="space"?n.jsx("div",{className:"w-4 h-4 rounded-full",style:{background:u.color||"#52525b"}}):n.jsx("span",{className:"text-[#6366f1]/60",children:u.action.icon}),n.jsx("span",{className:"text-sm",children:u.name}),n.jsx("span",{className:"ml-auto text-[10px] text-[#3f3f46] uppercase tracking-wider",children:u.type==="space"?"Space":"Widget"})]},u.type==="space"?u.id:u.action.source))]}),n.jsxs("div",{className:"px-4 py-2 border-t border-[#27272a]/40 flex items-center gap-3 text-[10px] text-[#3f3f46]",children:[n.jsx("span",{children:"↑↓ Navigate"}),n.jsx("span",{children:"↵ Select"}),n.jsx("span",{children:"ESC Close"})]})]})})}const xm=re.lazy(()=>ae(()=>import("./SomaView-DLzApZVW.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]))),Ae={bgBase:"var(--theme-bg-base, var(--color-bg, #09090b))",surface:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-secondary, #18181b)) 82%, transparent)",surfaceSoft:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-tertiary, #27272a)) 62%, transparent)",border:"color-mix(in srgb, var(--theme-metal-dark, var(--color-border, #3f3f46)) 66%, transparent)",ink:"var(--theme-paper-fg, var(--color-text, #fafafa))",inkSoft:"color-mix(in srgb, var(--theme-paper-fg, var(--color-text-secondary, #a1a1aa)) 72%, transparent)",paperFg:"var(--theme-paper-fg, var(--color-text-secondary, #a1a1aa))",accent:"var(--theme-accent, var(--color-accent, #6366f1))",success:"var(--color-success, #22c55e)",error:"var(--color-error, #ef4444)"},cr={background:Ae.bgBase,color:Ae.ink};function Rl(){const[t,e]=w.useState(null),[s,r]=w.useState(!1),[i,a]=w.useState(null),d=w.useCallback(async()=>{var f;try{const b=await ue("/api/config");if(!b.ok)throw new Error(`HTTP ${b.status}`);const u=await b.json();e(!!((f=u==null?void 0:u.organism)!=null&&f.enabled)),a(null)}catch(b){a(b.message),e(!1)}},[]);w.useEffect(()=>{d()},[d]);const l=w.useRef(0),c=w.useCallback(async f=>{const b=++l.current;r(!0),a(null);try{const u=await ue("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:{enabled:f}})});if(b!==l.current)return;if(!u.ok)throw new Error(`HTTP ${u.status}`);e(f),window.dispatchEvent(new CustomEvent("titan:soma:changed",{detail:{enabled:f}}))}catch(u){if(b!==l.current)return;a(u.message)}finally{b===l.current&&r(!1)}},[]);return t===null?n.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs",style:{...cr,color:Ae.paperFg},children:"Loading Soma…"}):t?n.jsxs("div",{className:"w-full h-full overflow-auto flex flex-col",style:cr,children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b",style:{background:Ae.surface,borderColor:Ae.border},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full animate-pulse",style:{background:Ae.success}}),n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:Ae.success},children:"Soma active"})]}),n.jsxs("button",{onClick:()=>c(!1),disabled:s,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[10px] disabled:opacity-60 transition-colors",style:{borderColor:Ae.border,color:Ae.inkSoft,background:Ae.surfaceSoft},title:"Disable Soma",children:[n.jsx(wi,{className:"w-3 h-3"}),s?"saving…":"disable"]})]}),n.jsx("div",{className:"flex-1 overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs",style:{color:Ae.paperFg},children:"Loading Soma dashboard…"}),children:n.jsx(xm,{})})})]}):n.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-4 p-6 text-center",style:cr,children:[n.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center",style:{background:"color-mix(in srgb, var(--theme-accent, var(--color-accent, #6366f1)) 18%, transparent)",border:`1px solid ${Ae.border}`},children:n.jsx(Kt,{className:"w-7 h-7",style:{color:Ae.accent}})}),n.jsxs("div",{className:"space-y-1 max-w-md",children:[n.jsx("h3",{className:"text-lg font-semibold",style:{color:Ae.ink},children:"Soma is off"}),n.jsx("p",{className:"text-xs leading-relaxed",style:{color:Ae.inkSoft},children:"TITAN’s homeostatic drive layer. When enabled, TITAN has a sense of its own state — purpose, curiosity, hunger, safety, social, rest — and will propose work when those drives drift. Every proposal still requires your approval."})]}),n.jsxs("button",{onClick:()=>c(!0),disabled:s,className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-full disabled:opacity-60 disabled:cursor-not-allowed text-sm font-medium transition-colors",style:{background:Ae.accent,color:"var(--theme-bg-base, var(--color-bg, #09090b))"},children:[n.jsx(wi,{className:"w-4 h-4"}),s?"Enabling…":"Enable Soma"]}),i&&n.jsx("p",{className:"text-xs",style:{color:Ae.error},children:i}),n.jsx("p",{className:"text-[10px]",style:{color:Ae.paperFg},children:"You can turn this off anytime from the same button."})]})}const wm={calm:{primary:"#6366f1",glow:"rgba(99,102,241,0.4)",pulse:"rgba(99,102,241,0.15)"},focused:{primary:"#10b981",glow:"rgba(16,185,129,0.4)",pulse:"rgba(16,185,129,0.15)"},excited:{primary:"#f59e0b",glow:"rgba(245,158,11,0.4)",pulse:"rgba(245,158,11,0.15)"},concerned:{primary:"#ef4444",glow:"rgba(239,68,68,0.4)",pulse:"rgba(239,68,68,0.15)"},dreaming:{primary:"#8b5cf6",glow:"rgba(139,92,246,0.4)",pulse:"rgba(139,92,246,0.15)"}},je={surface:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-secondary, #18181b)) 90%, transparent)",surfaceSoft:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-tertiary, #27272a)) 62%, transparent)",overlay:"color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 56%, transparent)",border:"color-mix(in srgb, var(--theme-metal-dark, var(--color-border, #3f3f46)) 66%, transparent)",metal:"var(--theme-metal, var(--color-border-light, #52525b))",ink:"var(--theme-paper-fg, var(--color-text, #fafafa))",accent:"var(--theme-accent, var(--color-accent, #6366f1))",warning:"var(--color-warning, #f59e0b)"};function vm(t,e,s){if(!s)return{emotion:"dreaming",intensity:.25,activity:"Dormant"};const r=e[0],i=Math.min(1,t/2);switch(r){case"purpose":return{emotion:"focused",intensity:.4+i*.4,activity:"Pursuing purpose"};case"curiosity":return{emotion:"excited",intensity:.4+i*.5,activity:"Exploring"};case"hunger":return{emotion:"focused",intensity:.5+i*.3,activity:"Satiating"};case"safety":return{emotion:"concerned",intensity:.5+i*.4,activity:"Securing"};case"social":return{emotion:"calm",intensity:.3+i*.3,activity:"Connecting"};case"rest":return{emotion:"dreaming",intensity:.2+i*.2,activity:"Recuperating"};default:return t>.5?{emotion:"focused",intensity:i,activity:"Processing"}:{emotion:"calm",intensity:.3,activity:"Observing"}}}function _m(){const[t,e]=w.useState(!1),[s,r]=w.useState({emotion:"calm",intensity:.3,activity:"Observing"}),[i,a]=w.useState(!1),[d,l]=w.useState(()=>km()),[c,f]=w.useState(!1),b=w.useRef({x:0,y:0}),u=w.useRef(null);w.useEffect(()=>{let k=!1;const I=async()=>{try{const j=await ue("/api/soma/state");if(!j.ok||k)return;const v=await j.json();if(k)return;r(vm(Number((v==null?void 0:v.totalPressure)??0),Array.isArray(v==null?void 0:v.dominantDrives)?v.dominantDrives:[],!!(v!=null&&v.enabled)))}catch{}};I();const g=setInterval(I,15e3);return()=>{k=!0,clearInterval(g)}},[]),w.useEffect(()=>{const k=I=>{var g;(g=u.current)!=null&&g.contains(I.target)||a(!1)};return window.addEventListener("mousedown",k),()=>window.removeEventListener("mousedown",k)},[]);const p=k=>{k.button===0&&(b.current={x:k.clientX-d.x,y:k.clientY-d.y},f(!0))},m=k=>{c&&l({x:k.clientX-b.current.x,y:k.clientY-b.current.y})},y=()=>{f(!1)},_=wm[s.emotion],R=s.activity==="Dormant"?je.metal:je.accent;return n.jsxs(n.Fragment,{children:[t&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center backdrop-blur-sm",style:{background:je.overlay},onClick:()=>e(!1),children:n.jsxs("div",{className:"border rounded-2xl shadow-2xl overflow-hidden",style:{width:"min(900px, 90vw)",height:"min(600px, 80vh)",background:je.surface,borderColor:je.border,color:je.ink,boxShadow:"0 24px 64px color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 72%, transparent)"},onClick:k=>k.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b",style:{borderColor:je.border},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(bt,{className:"w-4 h-4",style:{color:R}}),n.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",style:{color:je.ink},children:"SOMA Consciousness"})]}),n.jsx("button",{onClick:()=>e(!1),className:"p-1",style:{color:je.metal},children:n.jsx(Ts,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"h-[calc(100%-40px)]",children:n.jsx(Rl,{})})]})}),n.jsxs("div",{ref:u,className:"fixed z-50 select-none",style:{left:d.x,top:d.y},onMouseDown:p,onMouseMove:m,onMouseUp:y,onMouseLeave:y,children:[i&&n.jsxs("div",{className:"absolute bottom-full left-0 mb-2 backdrop-blur-xl border rounded-xl shadow-2xl overflow-hidden min-w-[160px] py-1",style:{background:je.surface,borderColor:je.border,boxShadow:"0 18px 40px color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 70%, transparent)"},children:[n.jsxs("button",{onClick:()=>{e(!0),a(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:je.ink,background:"transparent"},children:[n.jsx(bt,{className:"w-3.5 h-3.5",style:{color:R}}),"Open SOMA"]}),n.jsxs("button",{onClick:()=>{a(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:je.ink,background:"transparent"},children:[n.jsx(qt,{className:"w-3.5 h-3.5",style:{color:je.warning}}),"Summarize Canvas"]}),n.jsxs("button",{onClick:()=>{a(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:je.ink,background:"transparent"},children:[n.jsx(Fl,{className:"w-3.5 h-3.5",style:{color:je.accent}}),"Run Self-Check"]})]}),n.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>!c&&e(!0),onContextMenu:k=>{k.preventDefault(),a(!0)},children:[n.jsx("div",{className:"absolute inset-0 rounded-full animate-ping opacity-20",style:{background:_.pulse,animationDuration:`${3-s.intensity*2}s`}}),n.jsx("div",{className:"absolute -inset-2 rounded-full opacity-30 blur-md transition-all duration-1000",style:{background:_.glow}}),n.jsx("div",{className:"relative w-12 h-12 rounded-full flex items-center justify-center transition-all duration-500 hover:scale-110",style:{background:`radial-gradient(circle at 30% 30%, ${R}, ${je.metal})`,boxShadow:`0 0 ${20+s.intensity*30}px ${_.glow}, inset 0 0 10px color-mix(in srgb, var(--theme-ink, var(--color-text, #fafafa)) 12%, transparent)`},children:n.jsx(bt,{className:"w-5 h-5",style:{color:je.ink}})}),n.jsx("div",{className:"absolute -bottom-5 left-1/2 -translate-x-1/2 whitespace-nowrap",children:n.jsx("span",{className:"text-[9px] font-medium uppercase tracking-wider px-1.5 py-0.5 rounded border",style:{color:je.ink,background:je.surfaceSoft,borderColor:je.border},children:s.activity})})]})]})]})}function km(){if(typeof window>"u")return{x:280,y:80};const t=window.innerWidth<640;return{x:t?Math.max(16,window.innerWidth-96):280,y:t?220:80}}const Sm=re.lazy(()=>ae(()=>import("./CommandPostHub-B_L1CAss.js"),__vite__mapDeps([8,1,2,3,4,5,9,10,11,12,13,6,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29])));function jm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-2",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Command Post..."}),children:n.jsx(Sm,{})})})}const Em=re.lazy(()=>ae(()=>import("./IntelligenceView-DxD78qfP.js"),__vite__mapDeps([30,1,2,4])));function Nm(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Intelligence..."}),children:n.jsx(Em,{})})})}const Cm=re.lazy(()=>ae(()=>import("./MemoryGraphPanel-BnD5jRqf.js"),__vite__mapDeps([31,1,2,13,9,4,3,32,33,25,29,34])));function Tm(){return n.jsx("div",{className:"w-full h-full overflow-auto bg-[#09090b]",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"h-full flex items-center justify-center",children:n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-[#6366f1]/20 border-t-[#6366f1] animate-spin mx-auto mb-3"}),n.jsx("p",{className:"text-[11px] text-[#52525b]",children:"Loading memory graph..."})]})}),children:n.jsx("div",{className:"p-4",children:n.jsx(Cm,{})})})})}function Am(){const[t,e]=w.useState(!1);return t?n.jsx(nc,{onClose:()=>e(!1)}):n.jsx("div",{className:"w-full h-full flex flex-col items-center justify-center bg-[#09090b]",children:n.jsxs("button",{onClick:()=>e(!0),className:"group relative flex flex-col items-center gap-4",children:[n.jsxs("div",{className:"relative w-20 h-20 rounded-full flex items-center justify-center transition-all duration-300 group-hover:scale-110",children:[n.jsx("div",{className:"absolute inset-0 rounded-full bg-[#6366f1]/20 animate-pulse"}),n.jsx("div",{className:"absolute inset-0 rounded-full bg-gradient-to-br from-[#6366f1]/30 to-[#4f46e5]/10 border border-[#6366f1]/30"}),n.jsx(va,{className:"w-8 h-8 text-[#818cf8] relative z-10"})]}),n.jsxs("div",{className:"text-center",children:[n.jsx("p",{className:"text-sm font-medium text-[#a1a1aa]",children:"Tap to speak"}),n.jsx("p",{className:"text-[10px] text-[#52525b] mt-1",children:"F5-TTS · Voice Cloning"})]})]})})}const Rm=re.lazy(()=>ae(()=>import("./InfraView-Jmqhg_Yc.js"),__vite__mapDeps([35,1,2,4])));function Im(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Infrastructure..."}),children:n.jsx(Rm,{})})})}const Lm=re.lazy(()=>ae(()=>import("./ToolsView-CG1mZdiy.js"),__vite__mapDeps([36,1,2,4])));function Dm(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Tools..."}),children:n.jsx(Lm,{})})})}const Mm=re.lazy(()=>ae(()=>import("./SettingsView-zgqkDDBJ.js"),__vite__mapDeps([37,1,2,4])));function Om(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Settings..."}),children:n.jsx(Mm,{})})})}function Pm(){const[t,e]=w.useState([]),[s,r]=w.useState("/"),[i,a]=w.useState(!1),[d,l]=w.useState(null),c=async()=>{a(!0),l(null);try{const f=await ue(`/api/files?path=${encodeURIComponent(s)}`);if(f.ok){const b=await f.json();e(b.files||[])}else e([]),l(`Couldn't load files (HTTP ${f.status})`)}catch(f){e([]),l(`Couldn't reach /api/files — ${f.message}`)}finally{a(!1)}};return w.useEffect(()=>{c()},[s]),n.jsxs("div",{className:"w-full h-full flex flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-[#27272a]/40",children:[n.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-[#71717a]",children:[n.jsx("span",{className:"text-[#6366f1]",children:"~"}),n.jsx(rc,{className:"w-3 h-3"}),n.jsx("span",{children:s})]}),n.jsx("button",{onClick:c,className:"p-1 text-[#3f3f46] hover:text-[#71717a]",children:n.jsx(_n,{className:`w-3 h-3 ${i?"animate-spin":""}`})})]}),n.jsxs("div",{className:"flex-1 overflow-auto",children:[d&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#ef4444]/80",children:d}),!d&&!i&&t.length===0&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#52525b]",children:"No files"}),t.map(f=>n.jsxs("button",{onClick:()=>f.type==="directory"&&r(f.path),className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-[#27272a]/20 transition-colors",children:[f.type==="directory"?n.jsx(ic,{className:"w-3.5 h-3.5 text-[#f59e0b]"}):n.jsx(xn,{className:"w-3.5 h-3.5 text-[#6366f1]"}),n.jsx("span",{className:"text-[12px] text-[#a1a1aa]",children:f.name})]},f.path))]})]})}const Wm=re.lazy(()=>ae(()=>import("./SettingsPanel-BbwPu1i7.js"),__vite__mapDeps([38,1,2,3,4,5,39,15,6,40,41,25,42,43,44,45])));function Um(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Wm,{})})})}const Bm=re.lazy(()=>ae(()=>import("./SecurityPanel-BCq3Fzbr.js"),__vite__mapDeps([46,1,2,39,15,47])));function Fm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Bm,{})})})}const $m=re.lazy(()=>ae(()=>import("./AuditPanel-Bu71N5Er.js"),__vite__mapDeps([48,1,2,39,15,25,49,50])));function zm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx($m,{})})})}const ia={researcher:"#60a5fa",engineer:"#f87171",manager:"#a78bfa",ceo:"#fbbf24",general:"#9ca3af"},Hm={Recommended:"bg-[#10b981]/15 text-[#10b981] border-[#10b981]/30",Reasoning:"bg-[#8b5cf6]/15 text-[#8b5cf6] border-[#8b5cf6]/30",Fast:"bg-[#0ea5e9]/15 text-[#0ea5e9] border-[#0ea5e9]/30",Light:"bg-[#f59e0b]/15 text-[#f59e0b] border-[#f59e0b]/30","Long Context":"bg-[#6366f1]/15 text-[#6366f1] border-[#6366f1]/30","High Output":"bg-[#ec4899]/15 text-[#ec4899] border-[#ec4899]/30","Needs Key":"bg-[#ef4444]/15 text-[#ef4444] border-[#ef4444]/30"};function Vm(){const[t,e]=w.useState(null),[s,r]=w.useState({}),[i,a]=w.useState({}),[d,l]=w.useState(null),[c,f]=w.useState({}),[b,u]=w.useState(!0),p=w.useCallback(async()=>{l(null);try{const[_,R]=await Promise.all([ue("/api/specialists"),ue("/api/models")]);if(!_.ok)throw new Error(`Specialists request failed: ${_.status}`);if(!R.ok)throw new Error(`Models request failed: ${R.status}`);const k=await _.json(),I=await R.json();e(k),r(I);const g={};await Promise.all(k.map(async j=>{try{const v=await ue(`/api/specialists/${encodeURIComponent(j.id)}/recommendations`);if(v.ok){const A=await v.json();A.recommendations&&(g[j.id]=A.recommendations)}}catch{}})),a(g)}catch(_){l(_.message)}finally{u(!1)}},[]);w.useEffect(()=>{p()},[p]);const m=w.useCallback(_=>{const R=i[_];if(R&&R.length)return R.map(I=>I.id);const k=new Set;if(s&&typeof s=="object")for(const I of Object.keys(s)){const g=s[I];if(Array.isArray(g))for(const j of g)typeof j=="string"?k.add(j):j&&typeof j=="object"&&"id"in j&&typeof j.id=="string"&&k.add(j.id)}if(Array.isArray(t))for(const I of t)I!=null&&I.activeModel&&k.add(I.activeModel),I!=null&&I.defaultModel&&k.add(I.defaultModel);return Array.from(k).sort((I,g)=>I.localeCompare(g))},[i,s,t]),y=w.useCallback(async(_,R)=>{f(k=>({...k,[_]:"saving"}));try{const k=await ue(`/api/specialists/${encodeURIComponent(_)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:R})});if(!k.ok){const g=await k.text().catch(()=>"");throw new Error(`PATCH failed (${k.status}): ${g||k.statusText}`)}const I=await k.json();e(g=>(g==null?void 0:g.map(j=>j.id===_?{...j,activeModel:I.activeModel??j.defaultModel,overridden:(I.activeModel??j.defaultModel)!==j.defaultModel}:j))??null),f(g=>({...g,[_]:"saved"})),setTimeout(()=>{f(g=>{if(g[_]!=="saved")return g;const j={...g};return delete j[_],j})},1500)}catch(k){f(I=>({...I,[_]:"error"})),l(`${_}: ${k.message}`)}},[]);return b&&!t?n.jsx("div",{className:"h-full w-full flex items-center justify-center text-xs text-[#52525b]",children:"Loading specialists…"}):n.jsxs("div",{className:"w-full h-full flex flex-col bg-[#0a0a0f] text-[#e4e4e7] text-sm",children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-[#27272a]/60",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Lr,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("h3",{className:"font-semibold",children:"Specialist Models"}),n.jsxs("span",{className:"text-[10px] text-[#52525b]",children:[(t==null?void 0:t.length)??0," sub-agents"]})]}),n.jsxs("button",{onClick:()=>{u(!0),p()},className:"flex items-center gap-1 px-2 py-1 rounded text-[11px] text-[#71717a] hover:text-[#e4e4e7] hover:bg-[#27272a]/60 transition-colors",title:"Refresh from server",children:[n.jsx(_n,{className:`w-3 h-3 ${b?"animate-spin":""}`}),"Refresh"]})]}),d&&n.jsxs("div",{className:"mx-4 mt-3 flex items-start gap-2 px-3 py-2 rounded bg-[#7f1d1d]/20 border border-[#7f1d1d]/40 text-[11px] text-[#fca5a5]",children:[n.jsx(bn,{className:"w-3 h-3 mt-0.5 shrink-0"}),n.jsx("span",{className:"font-mono",children:d})]}),n.jsxs("div",{className:"flex-1 overflow-auto px-4 py-3 space-y-3",children:[(t==null?void 0:t.length)===0&&n.jsx("div",{className:"text-xs text-[#52525b] italic",children:"No specialists registered."}),t==null?void 0:t.map(_=>n.jsx(Gm,{row:_,models:m(_.id),recommendations:i[_.id]??[],state:c[_.id]??"idle",onChange:R=>y(_.id,R),onReset:()=>y(_.id,null)},_.id))]}),n.jsxs("div",{className:"px-4 py-2 border-t border-[#27272a]/60 text-[10px] text-[#52525b]",children:["Overrides write to ",n.jsx("span",{className:"font-mono text-[#71717a]",children:"config.specialists.overrides"}),". Top-scored models are recommended per specialist role."]})]})}function Gm({row:t,models:e,recommendations:s,state:r,onChange:i,onReset:a}){var u;const d=ia[t.role]??ia.general,l=s.find(p=>p.id===t.activeModel),c=s[0]??null,[f,b]=w.useState(!1);return n.jsxs("div",{className:"rounded-lg border border-[#27272a]/60 bg-[#18181b]/70 hover:border-[#3f3f46]/80 transition-colors",children:[n.jsxs("div",{className:"px-3 py-2 flex items-center gap-3",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-[180px]",children:[n.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:d},title:t.role}),n.jsxs("div",{className:"flex flex-col min-w-0",children:[n.jsx("div",{className:"text-sm font-medium truncate",children:t.name}),n.jsx("div",{className:"text-[10px] text-[#52525b] truncate",children:t.title})]})]}),n.jsxs("div",{className:"flex-1 flex items-center gap-2 min-w-0",children:[n.jsx("select",{value:t.activeModel,onChange:p=>i(p.target.value),disabled:r==="saving",className:"flex-1 min-w-0 px-2 py-1 rounded bg-[#0a0a0f] border border-[#27272a] text-xs font-mono focus:outline-none focus:border-[#6366f1] disabled:opacity-50",title:`default: ${t.defaultModel}`,children:e.map(p=>{const m=s.find(R=>R.id===p),y=(m==null?void 0:m.badges)??[],_=y.length?`${p} [${y.join(", ")}]`:p;return n.jsx("option",{value:p,children:_},p)})}),l&&l.badges.length>0&&n.jsx("div",{className:"hidden sm:flex items-center gap-1 shrink-0",children:l.badges.slice(0,3).map(p=>n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${Hm[p]??"bg-[#27272a] text-[#a1a1aa] border-[#27272a]"}`,children:p},p))}),t.overridden&&n.jsxs("button",{onClick:a,disabled:r==="saving",className:"flex items-center gap-1 px-2 py-1 rounded text-[10px] text-[#fbbf24] border border-[#fbbf24]/30 hover:bg-[#fbbf24]/10 transition-colors disabled:opacity-50",title:`Reset to default: ${t.defaultModel}`,children:[n.jsx(ba,{className:"w-3 h-3"}),"Reset"]}),n.jsx("button",{onClick:()=>b(p=>!p),className:"flex items-center justify-center w-6 h-6 rounded hover:bg-[#27272a]/60 text-[#52525b] hover:text-[#a1a1aa] transition-colors",title:"Show recommendation details",children:n.jsx(bi,{className:"w-3.5 h-3.5"})}),n.jsxs("div",{className:"w-5 h-5 flex items-center justify-center shrink-0",children:[r==="saving"&&n.jsx(_n,{className:"w-3.5 h-3.5 animate-spin text-[#6366f1]"}),r==="saved"&&n.jsx(vi,{className:"w-3.5 h-3.5 text-[#10b981]"}),r==="error"&&n.jsx(bn,{className:"w-3.5 h-3.5 text-[#ef4444]"})]})]})]}),f&&n.jsxs("div",{className:"px-3 pb-3 space-y-1.5",children:[l&&n.jsxs("div",{className:"flex items-start gap-2 text-[11px] text-[#a1a1aa]",children:[n.jsx(bi,{className:"w-3 h-3 mt-0.5 shrink-0 text-[#6366f1]"}),n.jsx("span",{children:l.rationale})]}),c&&c.id!==t.activeModel&&n.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[#10b981]",children:[n.jsx(vi,{className:"w-3 h-3 shrink-0"}),n.jsxs("span",{children:["Recommended upgrade: ",n.jsx("span",{className:"font-mono",children:c.id})," (score ",c.score,"/100)",c.badges.length>0&&n.jsxs("span",{className:"ml-1 text-[#71717a]",children:["[",c.badges.join(", "),"]"]})]})]}),l&&n.jsxs("div",{className:"grid grid-cols-3 gap-2 text-[10px] text-[#52525b]",children:[n.jsxs("div",{children:["Capability: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[l.breakdown.capabilityScore,"/40"]})]}),n.jsxs("div",{children:["Fit: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[l.breakdown.specialistFit,"/40"]})]}),n.jsxs("div",{children:["Availability: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[l.breakdown.availability,"/20"]})]})]})]}),n.jsxs("div",{className:"px-3 pb-2 flex items-center gap-2 text-[10px] text-[#52525b]",children:[n.jsxs("span",{children:["id: ",n.jsx("span",{className:"font-mono text-[#71717a]",children:t.id})]}),n.jsx("span",{children:"•"}),n.jsxs("span",{children:["role: ",n.jsx("span",{className:"font-mono",style:{color:d},children:t.role})]}),((u=t.templateMatches)==null?void 0:u.length)>0&&n.jsxs(n.Fragment,{children:[n.jsx("span",{children:"•"}),n.jsxs("span",{className:"truncate",children:["templates: ",n.jsx("span",{className:"font-mono text-[#71717a]",children:t.templateMatches.join(", ")})]})]})]})]})}function Ym(){const[t,e]=w.useState(null),[s,r]=w.useState(null),[i,a]=w.useState(null),[d,l]=w.useState(!1),[c,f]=w.useState(null),[b,u]=w.useState(null),p=w.useCallback(async()=>{f(null);try{const[R,k,I]=await Promise.all([ue("/api/telemetry/consent").then(g=>g.ok?g.json():Promise.reject(new Error(`consent ${g.status}`))),ue("/api/analytics/profile").then(g=>g.ok?g.json():null),ue("/api/telemetry/status").then(g=>g.ok?g.json():null)]);e(R),r(k),I!=null&&I.remote&&a(I.remote)}catch(R){f(R.message)}},[]);w.useEffect(()=>{const R=setInterval(()=>{ue("/api/telemetry/status").then(k=>k.ok?k.json():null).then(k=>{k!=null&&k.remote&&a(k.remote)}).catch(()=>{})},15e3);return()=>clearInterval(R)},[]),w.useEffect(()=>{p()},[p]);const m=w.useCallback(async R=>{l(!0),f(null);try{const k=await ue("/api/telemetry/consent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(R)});if(!k.ok)throw new Error(`save failed: ${k.status}`);const I=await k.json();e(g=>g?{...g,...I,consentedAt:I.enabled?new Date().toISOString():void 0}:null),u(Date.now()),setTimeout(()=>u(null),2e3)}catch(k){f(k.message)}finally{l(!1)}},[]),y=!!(t!=null&&t.enabled),_=!!(t!=null&&t.crashReports);return n.jsxs("div",{className:"w-full h-full overflow-auto bg-[#0a0a0f] text-[#e4e4e7] text-sm p-4",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[y?n.jsx(ac,{className:"w-5 h-5 text-[#10b981]"}):n.jsx(Dr,{className:"w-5 h-5 text-[#71717a]"}),n.jsx("h3",{className:"font-semibold text-base",children:"Privacy & Telemetry"}),n.jsx("span",{className:`ml-2 text-[10px] px-2 py-0.5 rounded-full border ${y?"border-[#10b981]/40 bg-[#10b981]/10 text-[#10b981]":"border-[#3f3f46] bg-[#18181b] text-[#71717a]"}`,children:y?"ENABLED":"OFF"}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[b&&n.jsxs("span",{className:"text-[11px] text-[#10b981] flex items-center gap-1",children:[n.jsx($l,{className:"w-3 h-3"})," Saved"]}),c&&n.jsxs("span",{className:"text-[11px] text-[#ef4444] flex items-center gap-1",children:[n.jsx(zl,{className:"w-3 h-3"})," ",c]}),n.jsxs("button",{onClick:()=>{p()},className:"flex items-center gap-1 px-2 py-1 rounded text-[11px] text-[#71717a] hover:text-[#e4e4e7] hover:bg-[#27272a]/60 transition-colors",children:[n.jsx(_n,{className:"w-3 h-3"})," Refresh"]})]})]}),n.jsx("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/70",children:n.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:y,disabled:d,onChange:R=>m({enabled:R.target.checked,crashReports:_}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"font-medium",children:"Send anonymous usage stats"}),n.jsx("div",{className:"text-xs text-[#a1a1aa] mt-1 leading-relaxed",children:"OS, Node version, CPU/GPU model + VRAM, RAM, TITAN version, and install method. A heartbeat every 5 minutes so we see uptime + concurrent-session counts. Never sends: prompts, file contents, credentials, IP address, or conversations."}),(t==null?void 0:t.consentedAt)&&n.jsxs("div",{className:"text-[10px] text-[#71717a] mt-2",children:["Consented ",n.jsx("span",{className:"font-mono",children:new Date(t.consentedAt).toLocaleString()}),t.consentedVersion&&n.jsxs(n.Fragment,{children:[" on TITAN v",n.jsx("span",{className:"font-mono",children:t.consentedVersion})]})]})]})]})}),n.jsx("div",{className:`mb-4 p-4 rounded-lg border transition-opacity ${y?"border-[#27272a]/60 bg-[#18181b]/70":"border-[#27272a]/30 bg-[#18181b]/30 opacity-60"}`,children:n.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:_,disabled:d||!y,onChange:R=>m({enabled:y,crashReports:R.target.checked}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("div",{className:"font-medium",children:"Send crash reports"}),n.jsxs("div",{className:"text-xs text-[#a1a1aa] mt-1 leading-relaxed",children:["When TITAN throws an uncaught exception or unhandled promise rejection, send the error class, message, and stack trace. ",n.jsxs("span",{className:"text-[#fbbf24]",children:["Your $HOME path is replaced with the string ",n.jsx("span",{className:"font-mono",children:'"$HOME"'})," before sending."]})]})]})]})}),n.jsxs("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/40",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(bn,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("div",{className:"text-sm font-medium",children:"What would be sent right now"})]}),s?n.jsxs("dl",{className:"grid grid-cols-[160px_1fr] gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-[#71717a]",children:"installId"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.installId.slice(0,32),"…"]}),n.jsx("dt",{className:"text-[#71717a]",children:"os / arch"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.os," / ",s.arch," (",s.osRelease,")"]}),n.jsx("dt",{className:"text-[#71717a]",children:"cpu"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.cpuModel," · ",s.cpuCores,"c"]}),n.jsx("dt",{className:"text-[#71717a]",children:"ram"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[(s.ramTotalMB/1024).toFixed(1)," GB"]}),n.jsx("dt",{className:"text-[#71717a]",children:"gpu"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.gpuVendor,"/",s.gpuName," · ",(s.gpuVramMB/1024).toFixed(1)," GB VRAM"]}),n.jsx("dt",{className:"text-[#71717a]",children:"disk"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.diskTotalGB," GB"]}),n.jsx("dt",{className:"text-[#71717a]",children:"version / node"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.version," · ",s.nodeVersion]}),n.jsx("dt",{className:"text-[#71717a]",children:"install method"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7]",children:s.installMethod})]}):n.jsx("div",{className:"text-xs text-[#71717a]",children:"Loading profile preview…"})]}),n.jsxs("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/50",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(wa,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("div",{className:"text-sm font-medium",children:"Delivery status"}),(i==null?void 0:i.lastSuccessAt)&&!i.lastError&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#10b981]/40 bg-[#10b981]/10 text-[#10b981]",children:"FLOWING"}),(i==null?void 0:i.lastError)&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#ef4444]/40 bg-[#ef4444]/10 text-[#ef4444]",children:"ERROR"}),!(i!=null&&i.configured)&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#71717a]/40 bg-[#71717a]/10 text-[#71717a]",children:"NO REMOTE"})]}),i?n.jsxs("dl",{className:"grid grid-cols-[160px_1fr] gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-[#71717a]",children:"remote URL"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7] break-all",children:i.remoteUrl||"—"}),n.jsx("dt",{className:"text-[#71717a]",children:"sent / failed"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[n.jsx("span",{className:"text-[#10b981]",children:i.sentCount})," / ",n.jsx("span",{className:i.failedCount>0?"text-[#ef4444]":"text-[#71717a]",children:i.failedCount}),i.lastEventType&&n.jsxs("span",{className:"text-[#71717a]",children:[" · last event: ",n.jsx("span",{className:"text-[#a1a1aa]",children:i.lastEventType})]})]}),n.jsx("dt",{className:"text-[#71717a]",children:"last attempt"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7] flex items-center gap-1",children:[n.jsx(bs,{className:"w-3 h-3 text-[#71717a]"}),i.lastAttemptAt?new Date(i.lastAttemptAt).toLocaleString():"—"]}),n.jsx("dt",{className:"text-[#71717a]",children:"last success"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7]",children:i.lastSuccessAt?new Date(i.lastSuccessAt).toLocaleString():"—"}),i.lastError&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-[#ef4444]",children:"last error"}),n.jsx("dd",{className:"font-mono text-[#fca5a5] break-all",children:i.lastError})]})]}):n.jsx("div",{className:"text-xs text-[#71717a]",children:"Checking collector reachability…"})]}),n.jsxs("div",{className:"mb-4 p-3 rounded-lg border border-[#27272a]/60 bg-[#0a0a0f]",children:[n.jsx("div",{className:"text-[10px] text-[#71717a] uppercase tracking-wider mb-1",children:"Collector"}),n.jsx("div",{className:"font-mono text-[11px] text-[#a1a1aa] break-all",children:(t==null?void 0:t.remoteUrl)||"—"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[n.jsxs("a",{href:"https://github.com/Djtony707/TITAN/blob/main/PRIVACY.md",target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-[#6366f1] hover:underline",children:[n.jsx(_i,{className:"w-3 h-3"})," Read the full PRIVACY.md"]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("a",{href:"https://github.com/Djtony707/TITAN/blob/main/src/analytics/collector.ts",target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-[#6366f1] hover:underline",children:[n.jsx(_i,{className:"w-3 h-3"})," See the collector source"]})]})]})}const qm=re.lazy(()=>ae(()=>import("./AutopilotPanel-Cj8oKxWv.js"),__vite__mapDeps([51,1,2,39,15])));function Km(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(qm,{})})})}const Jm=re.lazy(()=>ae(()=>import("./WorkflowsPanel-zsFqsLdn.js"),__vite__mapDeps([52,1,2,39,15,3,4,5,10,11,12,13,9,25,28,44,17,29,21,53,54])));function Xm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Jm,{})})})}const Zm=re.lazy(()=>ae(()=>import("./LearningPanel-C_JzSbJU.js"),__vite__mapDeps([55,1,2,39,15,25,54,56,57,33,13,9,4,3,58,28,23,59,60,32,24,45,12,61,34,27,22,41,62,21,63,64,65,66,67,68,11,47,69,16,42,20,70,29])));function Qm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Zm,{})})})}const eg=re.lazy(()=>ae(()=>import("./SelfImprovePanel-YE3hT8jK.js"),__vite__mapDeps([71,1,2,39,15,25,40,21,72,57,16,59,44,24,64,29])));function tg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(eg,{})})})}const sg=re.lazy(()=>ae(()=>import("./PersonasPanel-CMMQ3nh3.js"),__vite__mapDeps([73,1,2])));function ng(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(sg,{})})})}const rg=re.lazy(()=>ae(()=>import("./PersonaProfilesPanel-CKER-EU5.js"),__vite__mapDeps([74,1,2,39,15,25,11,17,67,21])));function ig(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(rg,{})})})}const ag=re.lazy(()=>ae(()=>import("./DreamPanel-BNAcCLBB.js"),__vite__mapDeps([75,1,2,39,15,25])));function og(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(ag,{})})})}const lg=re.lazy(()=>ae(()=>import("./HomelabPanel-BRfKRYe7.js"),__vite__mapDeps([76,1,2,39,15,77,78,4,25,21,22,60,20,32,40,42,18])));function cg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(lg,{})})})}const dg=re.lazy(()=>ae(()=>import("./NvidiaPanel-DdG13OX4.js"),__vite__mapDeps([79,1,2,39,15,25,45,40,69,34])));function ug(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(dg,{})})})}const hg=re.lazy(()=>ae(()=>import("./FilesPanel-CeC6YUSd.js"),__vite__mapDeps([80,1,2,28,25,15,81,21,12,29,45,43,11,23,59,33,13,9,4,3,58,60,32,24,54,61,34,27,22,41,62,63,64,65,66,67,68,47,69,16,42,20,70])));function fg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(hg,{})})})}const pg=re.lazy(()=>ae(()=>import("./LogsPanel-CpinKwaZ.js"),__vite__mapDeps([82,1,2,39,15,25])));function mg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(pg,{})})})}const gg=re.lazy(()=>ae(()=>import("./TelemetryPanel-dVr3yQQr.js"),__vite__mapDeps([83,1,2,77,21,19,20,60])));function yg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(gg,{})})})}const bg=re.lazy(()=>ae(()=>import("./SkillsPanel-BjEOBMRo.js"),__vite__mapDeps([84,1,2,39,15,13,9,4,3,34,29,43])));function xg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(bg,{})})})}const wg=re.lazy(()=>ae(()=>import("./McpPanel-D-MqN_f-.js"),__vite__mapDeps([85,1,2,39,15,13,9,4,3,25,28,60,86,65,29])));function vg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(wg,{})})})}const _g=re.lazy(()=>ae(()=>import("./IntegrationsPanel-DQL-7Ec6.js"),__vite__mapDeps([87,1,2,39,15,40,86,45])));function kg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(_g,{})})})}const Sg=re.lazy(()=>ae(()=>import("./ChannelsPanel-BnaTOeyf.js"),__vite__mapDeps([88,1,2,39,15,25,40,45])));function jg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Sg,{})})})}const Eg=re.lazy(()=>ae(()=>import("./MeshPanel-C-mRJpr0.js"),__vite__mapDeps([89,1,2,90,39,15,25,47])));function Ng(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Eg,{})})})}const Cg=re.lazy(()=>ae(()=>import("./MemoryWikiPanel-Dn3XZHL0.js"),__vite__mapDeps([91,1,2,39,15,81,70,21,34,54])));function Tg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Cg,{})})})}const Ag=re.lazy(()=>ae(()=>import("./AutoresearchPanel-3s8pjm6Z.js"),__vite__mapDeps([92,1,2,39,15,44,17,25,62,72,57,21])));function Rg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Ag,{})})})}const Ig=re.lazy(()=>ae(()=>import("./SelfProposalsPanel-DXuqBM6p.js"),__vite__mapDeps([93,1,2,39,15,13,9,4,3,21,33,58,28,23,59,60,32,24,54,45,12,61,34,27,22,41,62,63,64,65,66,67,25,68,11,47,69,16,42,20,70,29])));function Lg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Ig,{})})})}const Dg=re.lazy(()=>ae(()=>import("./OverviewPanel-B45ZYhJV.js"),__vite__mapDeps([94,1,2,77,39,15,78,4,21,22,60,95])));function Mg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Dg,{})})})}const Og=re.lazy(()=>ae(()=>import("./SessionsPanel-DORz5goR.js"),__vite__mapDeps([96,1,2,39,15,3,4,5,90,10,11,12,34,29])));function Pg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Og,{})})})}const Wg=re.lazy(()=>ae(()=>import("./WatchView-TNU6Ns1Q.js"),__vite__mapDeps([97,1,2,9,4])));function Ug(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Wg,{})})})}const Bg=re.lazy(()=>ae(()=>import("./BackupPanel-EUQJMJE7.js"),__vite__mapDeps([98,1,2,39,15,28,25,63,40])));function Fg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Bg,{})})})}const $g=re.lazy(()=>ae(()=>import("./TrainingPanel-CT5R4HWm.js"),__vite__mapDeps([99,1,2,39,15,25,43])));function zg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx($g,{})})})}const Hg=re.lazy(()=>ae(()=>import("./RecipesPanel-DzMcxpJJ.js"),__vite__mapDeps([100,1,2,39,15,101,3,4,13,9,25,54,44,29])));function Vg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Hg,{})})})}const Gg=re.lazy(()=>ae(()=>import("./VramPanel-CdnJYytg.js"),__vite__mapDeps([102,1,2,39,15,25])));function Yg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Gg,{})})})}const qg=re.lazy(()=>ae(()=>import("./TeamsPanel-uIIKoU7I.js"),__vite__mapDeps([103,1,2,39,15,13,9,4,3,25,29])));function Kg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(qg,{})})})}const Jg=re.lazy(()=>ae(()=>import("./CronPanel-BwMrrZ5d.js"),__vite__mapDeps([104,1,2,39,15,101,3,4,13,9,25,21,53,29])));function Xg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Jg,{})})})}const Zg=re.lazy(()=>ae(()=>import("./CheckpointsPanel-C62naE4U.js"),__vite__mapDeps([105,1,2,39,15,13,9,4,3,25,45,29])));function Qg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Zg,{})})})}const ey=re.lazy(()=>ae(()=>import("./OrganismPanel-xZWUJKyr.js"),__vite__mapDeps([106,1,2,39,15,25,40])));function ty(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(ey,{})})})}const sy=re.lazy(()=>ae(()=>import("./FleetPanel-EyWF7l3W.js"),__vite__mapDeps([107,1,2,39,15,25,64])));function ny(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(sy,{})})})}const ry=re.lazy(()=>ae(()=>import("./BrowserPanel-Beo4F5Ar.js"),__vite__mapDeps([108,1,2,39,15])));function iy(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(ry,{})})})}const ay=re.lazy(()=>ae(()=>import("./EvalPanel-CW-SSjtg.js"),__vite__mapDeps([109,1,2,39,15,25,44])));function oy(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(ay,{})})})}function ly(t){const e=Date.now()-new Date(t).getTime();if(!Number.isFinite(e)||e<0)return t;const s=Math.floor(e/1e3);if(s<60)return`${s}s ago`;const r=Math.floor(s/60);if(r<60)return`${r}m ago`;const i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function cy(t){const e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e>=0?t.slice(e+1):t}function dy(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,a]=w.useState(""),[d,l]=w.useState(null),[c,f]=w.useState(""),[b,u]=w.useState(!1),[p,m]=w.useState(null),[y,_]=w.useState(null),[R,k]=w.useState(null),I=w.useCallback(async()=>{r(!0),m(null);try{const N=await ue("/api/time-travel/checkpoints?limit=100");if(!N.ok)throw new Error(`${N.status} ${N.statusText}`);const D=await N.json();e(D.checkpoints||[])}catch(N){m(N.message||"Failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{I()},[I]);const g=w.useCallback((N,D)=>{k({kind:N,message:D}),setTimeout(()=>k(null),4e3)},[]),j=w.useCallback(async N=>{l(N),f(""),u(!0);try{const D=await ue(`/api/time-travel/diff/${encodeURIComponent(N)}`);if(!D.ok)throw new Error(`${D.status} ${D.statusText}`);const S=await D.json();f(S.diff||"(no diff returned)")}catch(D){f(`Failed to load diff: ${D.message}`)}finally{u(!1)}},[]),v=w.useCallback(N=>{_(N)},[]),A=w.useCallback(async()=>{if(!y)return;const N=y;_(null);try{const D=await ue(`/api/time-travel/restore/${encodeURIComponent(N)}`,{method:"POST"});if(!D.ok)throw new Error(`${D.status} ${D.statusText}`);const S=await D.json();S.ok?(g("ok",S.message||`Restored to ${N.slice(0,8)}.`),I()):g("err",S.message||"Restore failed.")}catch(D){g("err",D.message||"Restore failed.")}},[y,I,g]),E=w.useMemo(()=>{const N=i.trim().toLowerCase();return N?t.filter(D=>D.filePath.toLowerCase().includes(N)||D.toolName.toLowerCase().includes(N)||D.id.toLowerCase().includes(N)):t},[t,i]);return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",fontSize:12,background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Time Travel"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," file checkpoints · newest first"]})]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("input",{type:"text",value:i,onChange:N=>a(N.target.value),placeholder:"Filter by file or tool…",style:{background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:6,color:"#fff",fontSize:11,padding:"4px 8px",outline:"none",width:180}}),n.jsx("button",{onClick:I,disabled:s,title:"Refresh checkpoint list",style:{background:"rgba(99,102,241,0.15)",border:"1px solid rgba(99,102,241,0.35)",borderRadius:6,color:"#c7d2fe",fontSize:11,padding:"4px 10px",cursor:s?"wait":"pointer"},children:s?"…":"Refresh"})]})]}),R&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,background:R.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${R.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:R.kind==="ok"?"#86efac":"#fca5a5",fontSize:11},children:R.message}),p&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.3)",color:"#fca5a5",fontSize:11},children:p}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[n.jsx("div",{style:{flex:1,overflow:"auto",borderRight:"1px solid rgba(255,255,255,0.06)"},children:s&&t.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)"},children:"Loading checkpoints…"}):E.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)"},children:i?"No matches for that filter.":"No file checkpoints yet. They're created automatically whenever TITAN writes or edits a file."}):E.map(N=>n.jsxs("div",{onClick:()=>j(N.id),style:{padding:"8px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",cursor:"pointer",background:d===N.id?"rgba(99,102,241,0.08)":"transparent",borderLeft:d===N.id?"2px solid #818cf8":"2px solid transparent"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[n.jsx("span",{style:{fontSize:11,fontFamily:"ui-monospace, monospace",color:"#a5b4fc"},children:N.commitHash.slice(0,8)}),n.jsx("span",{style:{fontSize:10,color:"rgba(255,255,255,0.5)"},children:ly(N.timestamp)})]}),n.jsx("div",{style:{fontSize:12,color:"#e2e8f5",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:N.filePath,children:cy(N.filePath)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:4},children:[n.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:["before ",n.jsx("code",{style:{color:"#fbbf24"},children:N.toolName})]}),n.jsx("button",{onClick:D=>{D.stopPropagation(),v(N.id)},title:"Restore this file to the state it was in at this checkpoint",style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"rgba(34,197,94,0.12)",border:"1px solid rgba(34,197,94,0.3)",color:"#86efac",cursor:"pointer"},children:"Restore"})]})]},N.id))}),n.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:d?b?n.jsx("div",{style:{color:"rgba(255,255,255,0.4)"},children:"Loading diff…"}):n.jsx("pre",{style:{margin:0,fontFamily:'ui-monospace, "SF Mono", Menlo, monospace',fontSize:11,lineHeight:1.5,color:"#e2e8f5",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:(c||"").split(`
824
- `).map((N,D)=>{let S="rgba(255,255,255,0.7)";return N.startsWith("+")&&!N.startsWith("+++")?S="#86efac":N.startsWith("-")&&!N.startsWith("---")?S="#fca5a5":N.startsWith("@@")?S="#a5b4fc":(N.startsWith("diff")||N.startsWith("index")||N.startsWith("+++")||N.startsWith("---"))&&(S="rgba(255,255,255,0.45)"),n.jsx("div",{style:{color:S},children:N||" "},D)})}):n.jsx("div",{style:{color:"rgba(255,255,255,0.4)"},children:"Select a checkpoint on the left to see its diff vs the current file."})})]}),y&&n.jsx("div",{onClick:()=>_(null),style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10},children:n.jsxs("div",{onClick:N=>N.stopPropagation(),style:{background:"#0d0f1d",border:"1px solid rgba(255,255,255,0.1)",borderRadius:10,padding:18,maxWidth:380,color:"#e2e8f5"},children:[n.jsx("div",{style:{fontSize:14,fontWeight:600,marginBottom:8},children:"Restore this checkpoint?"}),n.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.7)",marginBottom:12},children:["The file will be overwritten with its state at ",n.jsx("code",{children:y.slice(0,8)}),". A NEW checkpoint of the current state is taken first, so you can always come back."]}),n.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[n.jsx("button",{onClick:()=>_(null),style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.1)",color:"#e2e8f5",borderRadius:6,padding:"6px 12px",fontSize:12,cursor:"pointer"},children:"Cancel"}),n.jsx("button",{onClick:A,style:{background:"rgba(34,197,94,0.18)",border:"1px solid rgba(34,197,94,0.4)",color:"#86efac",borderRadius:6,padding:"6px 12px",fontSize:12,cursor:"pointer"},children:"Restore"})]})]})})]})}const aa=5e3,oa={planning:"#a5b4fc",delegating:"#60a5fa",observing:"#22d3ee",iterating:"#f59e0b",verifying:"#a78bfa",reporting:"#34d399",blocked:"#facc15",escalated:"#fb7185",done:"#34d399",failed:"#ef4444",cancelled:"#737373"};function uy(t){if(!Number.isFinite(t)||t<0)return"—";const e=Math.floor(t/1e3);if(e<60)return`${e}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),i=s%60;return`${r}h ${i}m`}function hy(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function fy(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,a]=w.useState(null),[d,l]=w.useState(!1),[c,f]=w.useState(""),[b,u]=w.useState(2),[p,m]=w.useState(!1),[y,_]=w.useState(null),R=w.useCallback(async()=>{try{const v=await ue("/api/missions/active");if(!v.ok)throw new Error(`${v.status} ${v.statusText}`);const A=await v.json();e(A.missions||[]),a(null)}catch(v){a(v.message||"failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{R();const v=setInterval(R,aa);return()=>clearInterval(v)},[R]);const k=w.useCallback((v,A)=>{_({kind:v,message:A}),setTimeout(()=>_(null),5e3)},[]),I=w.useCallback(async()=>{var A;const v=c.trim();if(v.length<10){k("err","Describe the mission (>=10 chars).");return}m(!0);try{const E=await ue("/api/mission/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:v,budgetUsd:b})});if(!E.ok)throw new Error(`${E.status} ${E.statusText}`);const N=await E.json();k("ok",N.message||`Mission "${((A=N.goal)==null?void 0:A.title)??"?"}" launched.`),f(""),l(!1),R()}catch(E){k("err",E.message||"launch failed")}finally{m(!1)}},[c,b,R,k]),g=w.useCallback(async v=>{try{const A=await ue(`/api/mission/${encodeURIComponent(v)}/cancel`,{method:"POST"});if(!A.ok)throw new Error(`${A.status} ${A.statusText}`);k("ok","Mission marked for cancellation."),R()}catch(A){k("err",A.message||"cancel failed")}},[R,k]),j=w.useMemo(()=>{const v={delegating:0,observing:1,iterating:2,verifying:3,planning:4,reporting:5,blocked:6,escalated:7};return[...t].sort((A,E)=>(v[A.phase]??99)-(v[E.phase]??99))},[t]);return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Mission Driver"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," active · polling every ",aa/1e3,"s"]})]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("button",{onClick:()=>l(v=>!v),title:"Launch a new autonomous mission",style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid rgba(99,102,241,0.4)",background:d?"rgba(99,102,241,0.25)":"rgba(99,102,241,0.12)",color:"#c7d2fe",cursor:"pointer"},children:d?"× Close":"+ New mission"}),n.jsx("button",{onClick:R,title:"Refresh",style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid rgba(255,255,255,0.1)",background:"rgba(255,255,255,0.04)",color:"#e2e8f5",cursor:"pointer"},children:"↻"})]})]}),y&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,fontSize:11,background:y.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${y.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:y.kind==="ok"?"#86efac":"#fca5a5"},children:y.message}),d&&n.jsxs("div",{style:{padding:12,borderBottom:"1px solid rgba(255,255,255,0.06)",background:"rgba(99,102,241,0.04)"},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.6,color:"#a5b4fc",marginBottom:6},children:"Describe the mission"}),n.jsx("textarea",{value:c,onChange:v=>f(v.target.value),placeholder:"e.g. 'Research the top 5 AI agent frameworks for 2026, summarize their differentiation in a markdown report, and save to ~/Documents/agent-research.md'",rows:3,style:{width:"100%",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:12,padding:"6px 10px",resize:"vertical",fontFamily:"inherit",boxSizing:"border-box"}}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:8,gap:8},children:[n.jsxs("label",{style:{fontSize:11,color:"rgba(255,255,255,0.6)"},children:["Budget cap: $",n.jsx("input",{type:"number",value:b,onChange:v=>u(Math.max(.05,Math.min(50,Number(v.target.value)||2))),step:"0.5",min:"0.05",max:"50",style:{width:60,marginLeft:4,background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:4,color:"#fff",fontSize:11,padding:"2px 6px"}})]}),n.jsx("button",{onClick:I,disabled:p||c.trim().length<10,style:{fontSize:12,padding:"6px 14px",borderRadius:6,border:"none",background:p?"rgba(255,255,255,0.05)":"rgba(34,197,94,0.18)",color:"#86efac",cursor:p?"wait":"pointer",fontWeight:600},children:p?"Decomposing…":"🚀 Launch"})]})]}),n.jsxs("div",{style:{flex:1,overflow:"auto",padding:8},children:[i&&n.jsx("div",{style:{padding:10,color:"#fca5a5",fontSize:11},children:i}),s&&t.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)",fontSize:12},children:"Loading missions…"}):j.length===0?n.jsxs("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:["No active missions.",n.jsx("br",{}),n.jsx("span",{style:{fontSize:11,color:"rgba(255,255,255,0.35)"},children:'Click "+ New mission" to launch one.'})]}):j.map(v=>{const A=oa[v.phase]??"#94a3b8",E=v.subtasks.total>0?Math.round(v.subtasks.completed/v.subtasks.total*100):0;return n.jsxs("div",{style:{padding:"10px 12px",marginBottom:6,borderRadius:8,background:"rgba(255,255,255,0.025)",border:`1px solid ${v.phase==="blocked"?"rgba(250,204,21,0.4)":"rgba(255,255,255,0.06)"}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[n.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#fafafa",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:v.title,children:v.title}),n.jsx("button",{onClick:()=>g(v.goalId),title:"Cancel this mission",style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.3)",color:"#fca5a5",cursor:"pointer",marginLeft:6},children:"Cancel"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:"rgba(255,255,255,0.7)"},children:[n.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 6px",borderRadius:4,background:`${A}22`,border:`1px solid ${A}55`,color:A,textTransform:"uppercase",letterSpacing:.5,fontWeight:600,fontSize:9},children:v.phase}),n.jsxs("span",{children:[v.subtasks.completed,"/",v.subtasks.total," subtasks (",E,"%)"]}),n.jsx("span",{children:"·"}),n.jsx("span",{children:hy(v.budget.costUsd)}),n.jsx("span",{children:"·"}),n.jsx("span",{children:uy(Date.now()-new Date(v.startedAt).getTime())})]}),v.blockedReason&&n.jsxs("div",{style:{marginTop:6,padding:"6px 8px",borderRadius:4,background:"rgba(250,204,21,0.08)",border:"1px solid rgba(250,204,21,0.25)",fontSize:11,color:"#fde68a"},children:[n.jsx("strong",{children:"Blocked:"})," ",v.blockedReason.question??"(no reason)"]}),v.lastHistory.length>0&&n.jsx("div",{style:{marginTop:6,fontSize:10,color:"rgba(255,255,255,0.45)",display:"flex",flexDirection:"column",gap:1},children:v.lastHistory.slice(-3).map((N,D)=>n.jsxs("div",{style:{display:"flex",gap:6,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n.jsx("span",{style:{color:oa[N.phase]??"rgba(255,255,255,0.6)",minWidth:70,fontFamily:"ui-monospace, monospace",fontSize:9},children:N.phase}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:N.note??""})]},D))})]},v.goalId)})]})]})}const py=6e4,my=[{label:"6h",hours:6},{label:"24h",hours:24},{label:"7d",hours:168}];function gy(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function yy(t){return t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(1)}k`:`${(t/1e6).toFixed(2)}M`}function by(){const[t,e]=w.useState(24),[s,r]=w.useState(null),[i,a]=w.useState(!0),[d,l]=w.useState(null),c=w.useCallback(async()=>{a(!0);try{const f=await ue(`/api/missions/digest?hours=${t}`);if(!f.ok)throw new Error(`${f.status} ${f.statusText}`);const b=await f.json();r(b),l(null)}catch(f){l(f.message||"failed")}finally{a(!1)}},[t]);return w.useEffect(()=>{c();const f=setInterval(c,py);return()=>clearInterval(f)},[c]),n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Daily digest"}),n.jsx("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:"what TITAN did while you were away"})]}),n.jsx("div",{style:{display:"flex",gap:4},children:my.map(f=>n.jsx("button",{onClick:()=>e(f.hours),style:{fontSize:10,padding:"3px 8px",borderRadius:4,border:"1px solid rgba(255,255,255,0.1)",background:t===f.hours?"rgba(99,102,241,0.25)":"rgba(255,255,255,0.03)",color:t===f.hours?"#c7d2fe":"rgba(255,255,255,0.65)",cursor:"pointer"},children:f.label},f.label))})]}),s&&n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:8},children:[n.jsx(zs,{label:"Done",value:s.stats.completed,color:"#34d399"}),n.jsx(zs,{label:"Failed",value:s.stats.failed,color:s.stats.failed>0?"#fca5a5":"rgba(255,255,255,0.5)"}),n.jsx(zs,{label:"Active",value:s.stats.active,color:"#60a5fa"}),n.jsx(zs,{label:"Blocked",value:s.stats.blocked,color:s.stats.blocked>0?"#facc15":"rgba(255,255,255,0.5)"})]}),s&&(s.stats.totalCostUsd>0||s.stats.totalTokens>0)&&n.jsxs("div",{style:{padding:"6px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:10,color:"rgba(255,255,255,0.55)",display:"flex",justifyContent:"space-between"},children:[n.jsxs("span",{children:["Spend: ",n.jsx("strong",{style:{color:"#e2e8f5"},children:gy(s.stats.totalCostUsd)})]}),n.jsxs("span",{children:["Tokens: ",n.jsx("strong",{style:{color:"#e2e8f5"},children:yy(s.stats.totalTokens)})]})]}),n.jsxs("div",{style:{flex:1,overflow:"auto",padding:14},children:[i&&!s&&n.jsx("div",{style:{color:"rgba(255,255,255,0.4)",fontSize:11},children:"Loading…"}),d&&n.jsx("div",{style:{color:"#fca5a5",fontSize:11},children:d}),s&&n.jsxs(n.Fragment,{children:[n.jsx("pre",{style:{margin:0,fontFamily:'ui-monospace, "SF Mono", Menlo, monospace',fontSize:11,lineHeight:1.55,color:"#e2e8f5",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s.summaryText||"(no activity in this window)"}),s.recentLessons.length>0&&n.jsxs("div",{style:{marginTop:16,paddingTop:12,borderTop:"1px solid rgba(255,255,255,0.06)"},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.6,color:"#a5b4fc",marginBottom:6},children:"Lessons learned (Reflexion)"}),s.recentLessons.map((f,b)=>n.jsxs("div",{style:{fontSize:11,color:"rgba(255,255,255,0.8)",padding:"4px 0",borderBottom:"1px dashed rgba(255,255,255,0.04)"},children:["• ",f]},b))]})]})]})]})}function zs({label:t,value:e,color:s}){return n.jsxs("div",{style:{textAlign:"center",padding:"6px 4px",borderRadius:6,background:"rgba(255,255,255,0.02)"},children:[n.jsx("div",{style:{fontSize:18,fontWeight:700,color:s,lineHeight:1},children:e}),n.jsx("div",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textTransform:"uppercase",letterSpacing:.5,marginTop:4},children:t})]})}const Hs={pending:"#737373",running:"#60a5fa",done:"#34d399",failed:"#ef4444",skipped:"#a78bfa"},la=6e3,kt=180,dr=64,ca=96,Vs=24;function xy(t){const e=new Map,s=new Map(t.map(i=>[i.id,i])),r=(i,a)=>{if(e.has(i))return e.get(i);if(a.has(i))return 0;const d=s.get(i);if(!d)return 0;a.add(i);const l=(d.dependsOn??[]).filter(f=>s.has(f)),c=l.length===0?0:Math.max(...l.map(f=>r(f,a)))+1;return a.delete(i),e.set(i,c),c};for(const i of t)r(i.id,new Set);return e}function wy(){const[t,e]=w.useState([]),[s,r]=w.useState(null),[i,a]=w.useState(null),[d,l]=w.useState(null),[c,f]=w.useState(null),b=w.useCallback(async()=>{try{const k=await ue("/api/missions/active");if(!k.ok)throw new Error(`${k.status} ${k.statusText}`);const g=(await k.json()).missions||[];e(g),!s&&g.length>0&&r(g[0].goalId)}catch(k){l(k.message||"failed")}},[s]),u=w.useCallback(async k=>{try{const I=await ue(`/api/mission/${encodeURIComponent(k)}`);if(!I.ok)throw new Error(`${I.status} ${I.statusText}`);const g=await I.json();a(g),l(null)}catch(I){l(I.message||"failed to load mission"),a(null)}},[]);w.useEffect(()=>{b();const k=setInterval(b,la);return()=>clearInterval(k)},[b]),w.useEffect(()=>{if(!s){a(null);return}u(s);const k=setInterval(()=>u(s),la);return()=>clearInterval(k)},[s,u]);const{layout:p,edges:m,viewBox:y}=w.useMemo(()=>{if(!(i!=null&&i.goal.subtasks))return{layout:[],edges:[],viewBox:"0 0 600 200"};const k=i.goal.subtasks,I=xy(k),g=new Map;for(const T of k){const P=I.get(T.id)??0;g.has(P)||g.set(P,[]),g.get(P).push(T)}const j=Array.from(g.keys()).sort((T,P)=>T-P),v=Math.max(...Array.from(g.values()).map(T=>T.length),1),A=Math.max(640,v*(kt+Vs)+Vs),E=j.length*ca+dr+40,N=new Map,D=[];for(const T of j){const P=g.get(T),M=P.length*kt+(P.length-1)*Vs,F=(A-M)/2,V=T*ca+20;for(let Y=0;Y<P.length;Y++){const q=F+Y*(kt+Vs);N.set(P[Y].id,{x:q,y:V}),D.push({...P[Y],x:q,y:V})}}const S=[];for(const T of k){const P=N.get(T.id);if(P)for(const M of T.dependsOn??[]){const F=N.get(M);F&&S.push({from:M,to:T.id,x1:F.x+kt/2,y1:F.y+dr,x2:P.x+kt/2,y2:P.y})}}return{layout:D,edges:S,viewBox:`0 0 ${A} ${E}`}},[i]),_=w.useMemo(()=>new Map(((i==null?void 0:i.goal.subtasks)??[]).map(k=>[k.id,k])),[i]),R=c?_.get(c):null;return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",gap:10},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Mission graph"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," active mission(s) · subtask DAG"]})]}),t.length>0&&n.jsx("select",{value:s??"",onChange:k=>r(k.target.value||null),style:{background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,padding:"4px 8px",maxWidth:240},children:t.map(k=>n.jsxs("option",{value:k.goalId,children:[k.title," [",k.phase,"]"]},k.goalId))})]}),d&&n.jsx("div",{style:{padding:10,color:"#fca5a5",fontSize:11},children:d}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[n.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:i?p.length===0?n.jsx("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:"This mission has no subtasks yet."}):n.jsxs("svg",{viewBox:y,style:{width:"100%",height:"auto"},role:"img","aria-label":"Mission subtask DAG",children:[n.jsx("defs",{children:n.jsx("marker",{id:"mg-arrow",viewBox:"0 0 10 10",refX:"10",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:n.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(255,255,255,0.35)"})})}),m.map((k,I)=>n.jsx("line",{x1:k.x1,y1:k.y1,x2:k.x2,y2:k.y2,stroke:"rgba(255,255,255,0.25)",strokeWidth:"1.4",markerEnd:"url(#mg-arrow)"},`e-${I}`)),p.map(k=>{var v;const I=((v=i.driver)==null?void 0:v.currentSubtaskId)===k.id,g=Hs[k.status],j=c===k.id;return n.jsxs("g",{transform:`translate(${k.x}, ${k.y})`,onClick:()=>f(k.id),style:{cursor:"pointer"},children:[n.jsx("rect",{width:kt,height:dr,rx:"8",fill:I?`${g}22`:"rgba(255,255,255,0.04)",stroke:j||I?g:`${g}55`,strokeWidth:I||j?2:1}),n.jsx("circle",{cx:14,cy:14,r:"5",fill:g,children:k.status==="running"&&n.jsx("animate",{attributeName:"r",values:"4;6;4",dur:"1.2s",repeatCount:"indefinite"})}),n.jsx("text",{x:28,y:18,fontSize:"11",fontWeight:"600",fill:"#fafafa",children:k.title.length>22?k.title.slice(0,21)+"…":k.title}),n.jsxs("text",{x:28,y:34,fontSize:"9",fill:"rgba(255,255,255,0.55)",letterSpacing:"0.5",style:{textTransform:"uppercase"},children:[k.status,k.retries>0?` · ${k.retries} retr${k.retries===1?"y":"ies"}`:""]}),n.jsxs("text",{x:14,y:52,fontSize:"9",fill:"rgba(255,255,255,0.45)",children:[(k.description||"").slice(0,30),(k.description||"").length>30?"…":""]}),I&&n.jsx("text",{x:kt-8,y:14,fontSize:"8",fill:g,textAnchor:"end",fontWeight:"700",children:"NOW"})]},k.id)})]}):n.jsx("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:t.length===0?"No active missions. Launch one via the Mission Driver widget.":"Select a mission to view its graph."})}),R&&n.jsxs("div",{style:{width:260,borderLeft:"1px solid rgba(255,255,255,0.06)",padding:14,overflow:"auto",fontSize:11},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:8},children:[n.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#fafafa",flex:1},children:R.title}),n.jsx("button",{onClick:()=>f(null),style:{background:"transparent",border:"none",color:"rgba(255,255,255,0.5)",cursor:"pointer",fontSize:14,padding:0,marginLeft:6},children:"×"})]}),n.jsxs("div",{style:{marginBottom:8},children:[n.jsx("span",{style:{padding:"2px 8px",borderRadius:4,fontSize:9,fontWeight:600,textTransform:"uppercase",letterSpacing:.5,background:`${Hs[R.status]}22`,border:`1px solid ${Hs[R.status]}55`,color:Hs[R.status]},children:R.status}),R.retries>0&&n.jsxs("span",{style:{marginLeft:6,color:"rgba(255,255,255,0.5)"},children:[R.retries," retries"]})]}),n.jsx("div",{style:{color:"rgba(255,255,255,0.85)",lineHeight:1.5,marginBottom:10},children:R.description}),R.dependsOn.length>0&&n.jsxs("div",{style:{color:"rgba(255,255,255,0.55)",fontSize:10,marginBottom:6},children:[n.jsx("strong",{children:"Depends on:"})," ",R.dependsOn.map(k=>{var I;return((I=_.get(k))==null?void 0:I.title)||k}).join(", ")]}),R.completedAt&&n.jsxs("div",{style:{color:"rgba(255,255,255,0.45)",fontSize:10},children:["Completed: ",new Date(R.completedAt).toLocaleString()]})]})]}),i&&n.jsxs("div",{style:{padding:"6px 14px",borderTop:"1px solid rgba(255,255,255,0.06)",display:"flex",justifyContent:"space-between",fontSize:10,color:"rgba(255,255,255,0.55)"},children:[n.jsxs("span",{children:[i.goal.subtasks.length," subtasks · ",i.goal.progress,"% progress"]}),i.driver&&n.jsxs("span",{children:[i.driver.phase," · $",i.driver.budget.costUsd.toFixed(2)," spent"]})]})]})}function vy(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,a]=w.useState(null),d=async()=>{try{const l=await fetch("/api/agents");if(!l.ok)throw new Error(`HTTP ${l.status}`);const c=await l.json();e(Array.isArray(c)?c:c.agents||[]),a(null)}catch(l){a(l.message)}finally{r(!1)}};return w.useEffect(()=>{d();const l=setInterval(d,1e4);return()=>clearInterval(l)},[]),s?n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(ma,{className:"w-4 h-4 text-[#6366f1] animate-spin"})}):i?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsxs("div",{className:"text-center",children:[n.jsx(bn,{className:"w-4 h-4 text-red-400 mx-auto mb-1"}),n.jsx("span",{className:"text-[10px] text-red-400",children:i})]})}):t.length===0?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsx("span",{className:"text-[10px] text-[#52525b]",children:"No active agents"})}):n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsx("div",{className:"space-y-2",children:t.map(l=>n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx(Pr,{className:`w-3.5 h-3.5 ${l.status==="busy"?"text-[#f59e0b]":l.status==="error"?"text-red-400":"text-[#6366f1]"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-[11px] text-[#a1a1aa] truncate",children:l.name}),n.jsxs("div",{className:"text-[10px] text-[#52525b] truncate",children:[l.role,l.model?` · ${l.model}`:""]})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${l.status==="busy"?"bg-[#f59e0b]/10 text-[#f59e0b]":l.status==="error"?"bg-red-400/10 text-red-400":"bg-[#6366f1]/10 text-[#818cf8]"}`,children:l.status})]},l.id))})})}function _y(){const[t,e]=w.useState(null),[s,r]=w.useState(!0),i=async()=>{try{const[d,l]=await Promise.allSettled([fetch("/api/health").then(b=>b.ok?b.json():null),fetch("/ollama/api/tags").then(b=>b.ok)]),c=d.status==="fulfilled"&&d.value,f=l.status==="fulfilled"&&l.value;e({gateway:c,ollama:f,version:(c==null?void 0:c.version)||"unknown",uptime:(c==null?void 0:c.uptime)||0})}catch{e({gateway:!1,ollama:!1,version:"unknown",uptime:0})}finally{r(!1)}};if(w.useEffect(()=>{i();const d=setInterval(i,3e4);return()=>clearInterval(d)},[]),s)return n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(ma,{className:"w-4 h-4 text-[#6366f1] animate-spin"})});const a=d=>{const l=Math.floor(d/3600),c=Math.floor(d%3600/60);return`${l}h ${c}m`};return n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[t!=null&&t.gateway?n.jsx(Hl,{className:"w-3.5 h-3.5 text-emerald-400"}):n.jsx(oc,{className:"w-3.5 h-3.5 text-red-400"}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa]",children:"TITAN Gateway"})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${t!=null&&t.gateway?"bg-emerald-400/10 text-emerald-400":"bg-red-400/10 text-red-400"}`,children:t!=null&&t.gateway?"Online":"Offline"})]}),n.jsxs("div",{className:"flex items-center justify-between px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Kt,{className:`w-3.5 h-3.5 ${t!=null&&t.ollama?"text-emerald-400":"text-red-400"}`}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa]",children:"Ollama"})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${t!=null&&t.ollama?"bg-emerald-400/10 text-emerald-400":"bg-red-400/10 text-red-400"}`,children:t!=null&&t.ollama?"Online":"Offline"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx("div",{className:"text-[9px] text-[#52525b] uppercase tracking-wider",children:"Version"}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] font-mono mt-0.5",children:t==null?void 0:t.version})]}),n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx("div",{className:"text-[9px] text-[#52525b] uppercase tracking-wider",children:"Uptime"}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] font-mono mt-0.5",children:a((t==null?void 0:t.uptime)||0)})]})]})]})})}const us={background:"var(--theme-paper, var(--color-bg-secondary))",borderColor:"var(--theme-metal, var(--color-border))",color:"var(--theme-ink, var(--color-text))"};function ky(t){if(!t.length)return 0;const e=[...t].sort((r,i)=>r-i),s=Math.floor(e.length/2);return e.length%2?e[s]:Math.round((e[s-1]+e[s])/2)}function Sy(){const[t,e]=w.useState(null),[s,r]=w.useState(""),[i,a]=w.useState(""),[d,l]=w.useState(!1),c=w.useCallback(async()=>{try{const m=await ue("/api/muscle");m.ok&&e(await m.json())}catch{}},[]);w.useEffect(()=>{c();const m=setInterval(c,2e4);return()=>clearInterval(m)},[c]);const f=async(m,y)=>{r(m);try{const _=await ue(`/api/muscle/${m}/${y}`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(_.ok)y==="adopt"&&window.dispatchEvent(new CustomEvent("titan:mascot:celebrate"));else{const R=await _.json().catch(()=>null);a((R==null?void 0:R.error)||`Couldn't ${y} that one — try refreshing.`)}await c()}finally{r("")}},b=async()=>{var m;if(!d){l(!0),a("Looking for repeated workflows… if I find one, I'll verify it with a real replay exam — that can take a couple of minutes.");try{const _=await(await ue("/api/muscle/scan",{method:"POST"})).json(),R={proposed:`Learned "${(m=_.skill)==null?void 0:m.name}"! 🎉 It passed its exam — adopt it below.`,"nothing-to-learn":"No repeated workflows yet — keep using TITAN and I'll spot them.","failed-exam":"Found a pattern, but it failed its replay exam — so I'm not showing it. (That's the trust part.)","pending-cap":"You have proposals waiting below — decide on those first.",disabled:"Muscle Memory is switched off in settings — turn it on and I'll start learning from your work.",cooldown:"I learned something recently — I pace myself to one new skill a day.","duplicate-race":"Already learned that one — refresh to see it."};a(R[_.action]||"Scan finished."),await c()}catch{a("Scan failed — is the gateway up?")}finally{l(!1)}}};if(!t)return n.jsx("div",{className:"p-4 text-xs opacity-60",children:"Loading Muscle Memory…"});const u=t.skills.filter(m=>m.status==="proposed"),p=t.skills.filter(m=>m.status==="adopted");return n.jsxs("div",{className:"w-full h-full overflow-auto p-4 space-y-4",style:{color:"var(--theme-ink, var(--color-text))"},children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:"💪 Muscle Memory"}),n.jsx("p",{className:"text-[11px] opacity-60",children:"TITAN turns your repeated workflows into skills — replay-verified before you ever see them."})]}),n.jsx("button",{onClick:b,disabled:d,className:"text-[11px] px-2.5 py-1.5 rounded-lg border shrink-0 disabled:opacity-50",style:{borderColor:"var(--theme-metal)",color:"var(--theme-accent)"},children:d?"Examining…":"Scan now"})]}),n.jsx("div",{className:`grid ${t.stats.medianSpeedupMs>0?"grid-cols-4":"grid-cols-3"} gap-2 text-center`,children:[{label:"skills learned",value:String(t.stats.learned)},{label:"adopted",value:String(t.stats.adopted)},{label:"skill runs",value:String(t.stats.totalRuns)},...t.stats.medianSpeedupMs>0?[{label:"saved per run",value:`~${Math.round(t.stats.medianSpeedupMs/1e3)}s`}]:[]].map(m=>n.jsxs("div",{className:"rounded-xl border py-2",style:us,children:[n.jsx("div",{className:"text-lg font-semibold",children:m.value}),n.jsx("div",{className:"text-[10px] opacity-60",children:m.label})]},m.label))}),i&&n.jsx("div",{className:"text-[11px] rounded-lg border px-3 py-2",style:us,children:i}),u.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-[11px] font-medium opacity-70 uppercase tracking-wide",children:"Waiting for you"}),u.map(m=>{var y;return n.jsxs("div",{className:"rounded-xl border p-3 space-y-2",style:us,children:[n.jsxs("div",{className:"flex items-start justify-between gap-2",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-[13px] font-semibold",children:[m.name," ",n.jsxs("span",{className:"font-mono text-[11px] opacity-60",children:["/",m.slashCommand]})]}),n.jsx("div",{className:"text-[11px] opacity-70",children:m.description})]}),n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-md border shrink-0",style:{borderColor:"#3f9142",color:"#5cb860"},children:"✓ exam passed"})]}),n.jsx("div",{className:"text-[10px] font-mono opacity-50",children:m.toolSequence.join(" → ")}),n.jsxs("div",{className:"text-[10px] opacity-60",children:["Learned from ",m.evidence.length," of your tasks, e.g. “",(y=m.evidence[0])==null?void 0:y.task.slice(0,80),"”"]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("button",{disabled:s===m.id,onClick:()=>f(m.id,"adopt"),className:"flex-1 text-[12px] font-semibold px-3 py-1.5 rounded-lg border disabled:opacity-50",style:{background:"var(--theme-accent)",color:"var(--theme-paper, #fff)",borderColor:"var(--theme-accent)"},children:s===m.id?"…":"Adopt"}),n.jsx("button",{disabled:s===m.id,onClick:()=>f(m.id,"dismiss"),className:"text-[12px] px-3 py-1.5 rounded-lg border disabled:opacity-50",style:{borderColor:"var(--theme-metal)"},children:"Not for me"})]})]},m.id)})]}),p.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("div",{className:"text-[11px] font-medium opacity-70 uppercase tracking-wide",children:"Adopted skills"}),p.map(m=>{var _;const y=((_=m.runs)==null?void 0:_.length)||0;return n.jsxs("div",{className:"rounded-xl border p-3 flex items-center justify-between gap-2",style:us,children:[n.jsxs("div",{children:[n.jsxs("div",{className:"text-[12px] font-semibold",children:[m.name," ",n.jsxs("span",{className:"font-mono text-[11px] opacity-60",children:["/",m.slashCommand]})]}),n.jsxs("div",{className:"text-[10px] opacity-60",children:[y," run",y===1?"":"s",m.baselineDurationMs&&y>0&&m.runs?` · ~${Math.max(0,Math.round((m.baselineDurationMs-ky(m.runs.map(R=>R.durationMs)))/1e3))}s faster than doing it manually`:""]})]}),n.jsx("span",{className:"text-lg",children:"💪"})]},m.id)})]}),u.length===0&&p.length===0&&n.jsx("div",{className:"text-[11px] opacity-60 rounded-xl border p-4 text-center",style:us,children:t.skills.some(m=>m.status==="failed-exam")?`I spotted ${t.skills.filter(m=>m.status==="failed-exam").length} repeated pattern${t.skills.filter(m=>m.status==="failed-exam").length===1?"":"s"} but couldn't verify ${t.skills.filter(m=>m.status==="failed-exam").length===1?"it":"them"} yet — I only show you skills that pass their exam.`:"Nothing learned yet. Use TITAN normally — when a workflow repeats a few times, it teaches itself and asks you here."})]})}function Gs({label:t,value:e,icon:s,color:r,unknown:i}){const a=Math.max(0,Math.min(100,Math.round(e)));return n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[s,n.jsx("span",{className:"text-[10px] text-[#52525b] uppercase tracking-wider",children:t})]}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa] font-mono",children:i?"—":`${a}%`})]}),n.jsx("div",{className:"h-1.5 rounded-full bg-[#27272a] overflow-hidden",children:n.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:i?"0%":`${a}%`,backgroundColor:r}})})]})}function jy(){const[t,e]=w.useState({cpu:0,memory:0,disk:0,load:0,loaded:!1,error:null,diskAvailable:!0});w.useEffect(()=>{let r=!1;async function i(){try{const d=await ue("/api/stats");if(!d.ok){const y=`HTTP ${d.status}`;r||e(_=>({..._,loaded:!0,error:y}));return}const l=await d.json();if(r)return;const c=l.host;if(!c){e(y=>({...y,loaded:!0,error:"no host metrics"}));return}const f=typeof c.cpuPercent=="number"?c.cpuPercent:0,b=typeof c.memPercent=="number"?c.memPercent:0,u=typeof c.diskPercent=="number"?c.diskPercent:0,p=c.cores||1,m=typeof c.loadAvg1=="number"?Math.min(100,c.loadAvg1/p*100):0;e({cpu:f,memory:b,disk:u,load:m,loaded:!0,error:null,diskAvailable:!c.diskError})}catch(d){r||e(l=>({...l,loaded:!0,error:d.message}))}}i();const a=setInterval(i,3e3);return()=>{r=!0,clearInterval(a)}},[]);const s=!t.loaded||!!t.error;return n.jsxs("div",{className:"w-full h-full p-3 overflow-auto",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx(Gs,{label:"CPU",value:t.cpu,icon:n.jsx(Ir,{className:"w-3 h-3 text-[#6366f1]"}),color:"#6366f1",unknown:s}),n.jsx(Gs,{label:"Memory",value:t.memory,icon:n.jsx(Vl,{className:"w-3 h-3 text-[#a78bfa]"}),color:"#a78bfa",unknown:s}),n.jsx(Gs,{label:"Disk",value:t.disk,icon:n.jsx(Gl,{className:"w-3 h-3 text-[#10b981]"}),color:"#10b981",unknown:s||!t.diskAvailable}),n.jsx(Gs,{label:"Load",value:t.load,icon:n.jsx(Kt,{className:"w-3 h-3 text-[#f59e0b]"}),color:"#f59e0b",unknown:s})]}),t.error&&n.jsx("div",{className:"mt-2 text-[10px] text-[#ef4444]/80",children:t.error})]})}const Ey=[{label:"Nav",source:"system:nav",w:3,h:4,icon:n.jsx(gc,{className:"w-3.5 h-3.5"})},{label:"Agents",source:"system:agents",w:3,h:4,icon:n.jsx(Pr,{className:"w-3.5 h-3.5"})},{label:"Health",source:"system:health",w:3,h:3,icon:n.jsx(Kt,{className:"w-3.5 h-3.5"})},{label:"Stats",source:"system:stats",w:3,h:4,icon:n.jsx(_c,{className:"w-3.5 h-3.5"})},{label:"Chat",source:"system:chat",w:4,h:5,icon:n.jsx(vn,{className:"w-3.5 h-3.5"})},{label:"Files",source:"system:files",w:4,h:6,icon:n.jsx(xn,{className:"w-3.5 h-3.5"})},{label:"Skills",source:"system:tools",w:5,h:4,icon:n.jsx(qt,{className:"w-3.5 h-3.5"})},{label:"Soma",source:"system:soma",w:6,h:6,icon:n.jsx(Yl,{className:"w-3.5 h-3.5"})},{label:"Intel",source:"system:intelligence",w:6,h:5,icon:n.jsx(bt,{className:"w-3.5 h-3.5"})},{label:"Infra",source:"system:infra",w:6,h:4,icon:n.jsx(Or,{className:"w-3.5 h-3.5"})},{label:"Tools",source:"system:tools",w:5,h:4,icon:n.jsx(Rr,{className:"w-3.5 h-3.5"})},{label:"Settings",source:"system:settings",w:4,h:6,icon:n.jsx(Mr,{className:"w-3.5 h-3.5"})},{label:"Wiki",source:"system:memory-wiki",w:5,h:5,icon:n.jsx(ys,{className:"w-3.5 h-3.5"})},{label:"Research",source:"system:autoresearch",w:5,h:5,icon:n.jsx(_a,{className:"w-3.5 h-3.5"})},{label:"Proposals",source:"system:self-proposals",w:5,h:5,icon:n.jsx(Xs,{className:"w-3.5 h-3.5"})},{label:"Muscle Memory",source:"system:muscle-memory",w:5,h:6,icon:n.jsx(Xs,{className:"w-3.5 h-3.5"})},{label:"Overview",source:"system:overview",w:5,h:4,icon:n.jsx(fa,{className:"w-3.5 h-3.5"})},{label:"Sessions",source:"system:sessions",w:5,h:4,icon:n.jsx(bs,{className:"w-3.5 h-3.5"})},{label:"Watch",source:"system:watch",w:6,h:5,icon:n.jsx(Kt,{className:"w-3.5 h-3.5"})},{label:"Backup",source:"system:backup",w:5,h:5,icon:n.jsx(ka,{className:"w-3.5 h-3.5"})},{label:"Training",source:"system:training",w:5,h:5,icon:n.jsx(bt,{className:"w-3.5 h-3.5"})},{label:"Recipes",source:"system:recipes",w:5,h:5,icon:n.jsx(ys,{className:"w-3.5 h-3.5"})},{label:"VRAM",source:"system:vram",w:5,h:5,icon:n.jsx(Ir,{className:"w-3.5 h-3.5"})},{label:"Teams",source:"system:teams",w:5,h:5,icon:n.jsx(Lr,{className:"w-3.5 h-3.5"})},{label:"Cron",source:"system:cron",w:5,h:5,icon:n.jsx(bs,{className:"w-3.5 h-3.5"})},{label:"Checkpoints",source:"system:checkpoints",w:5,h:5,icon:n.jsx(wn,{className:"w-3.5 h-3.5"})},{label:"Organism",source:"system:organism",w:5,h:5,icon:n.jsx(Dr,{className:"w-3.5 h-3.5"})},{label:"Fleet",source:"system:fleet",w:5,h:5,icon:n.jsx(Sa,{className:"w-3.5 h-3.5"})},{label:"Browser",source:"system:browser",w:5,h:5,icon:n.jsx(pa,{className:"w-3.5 h-3.5"})},{label:"Eval",source:"system:eval",w:5,h:5,icon:n.jsx(ja,{className:"w-3.5 h-3.5"})}];function Ny(){const t=(e,s,r)=>{window.dispatchEvent(new CustomEvent("titan:widget:add",{detail:{source:e,w:s,h:r}}))};return n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:Ey.map(e=>n.jsxs("button",{onClick:()=>t(e.source,e.w,e.h),className:"flex items-center gap-2 px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a] text-[#71717a] hover:text-[#a1a1aa] hover:border-[#3f3f46] hover:bg-[#27272a]/30 transition-all text-left",children:[n.jsx("span",{className:"text-[#6366f1]",children:e.icon}),n.jsx("span",{className:"text-[10px] font-medium",children:e.label})]},e.source))})})}class Cy extends re.Component{componentDidCatch(e){this.props.onError(e.message)}render(){return this.props.children}}function Ty({name:t,children:e}){const[s,r]=re.useState(null);return s?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsxs("span",{className:"text-xs text-red-400",children:[t,": ",s]})}):n.jsx(Cy,{onError:r,children:e})}const Ay=re.lazy(()=>ae(()=>import("./legacy-D21WSMF1.js"),__vite__mapDeps([110,1,2,4])).then(t=>({default:t.Responsive}))),Ry={"system:nav":op,"system:home-hero":nm,"system:chat":vl,"system:cmd":Al,"system:soma":Rl,"system:command-post":jm,"system:intelligence":Nm,"system:memory-graph":Tm,"system:voice":Am,"system:infra":Im,"system:tools":Dm,"system:settings":Om,"system:files":Pm,"system:settings-general":Um,"system:settings-security":Fm,"system:settings-audit":zm,"system:settings-specialists":Vm,"system:settings-privacy":Ym,"system:intelligence-autopilot":Km,"system:intelligence-workflows":Xm,"system:intelligence-learning":Qm,"system:intelligence-self-improve":tg,"system:intelligence-personas":ng,"system:intelligence-persona-profiles":ig,"system:intelligence-dream":og,"system:infra-homelab":cg,"system:infra-gpu":ug,"system:infra-files":fg,"system:infra-logs":mg,"system:infra-telemetry":yg,"system:tools-skills":xg,"system:tools-mcp":vg,"system:tools-integrations":kg,"system:tools-channels":jg,"system:tools-mesh":Ng,"system:agents":vy,"system:health":_y,"system:stats":jy,"system:quick-links":Ny,"system:memory-wiki":Tg,"system:autoresearch":Rg,"system:self-proposals":Lg,"system:muscle-memory":Sy,"system:overview":Mg,"system:sessions":Pg,"system:watch":Ug,"system:backup":Fg,"system:training":zg,"system:recipes":Vg,"system:vram":Yg,"system:teams":Kg,"system:cron":Xg,"system:checkpoints":Qg,"system:organism":ty,"system:fleet":ny,"system:browser":iy,"system:eval":oy,"system:time-travel":dy,"system:mission-driver":fy,"system:daily-digest":by,"system:mission-graph":wy},Iy={lg:12,md:10,sm:6,xs:4,xxs:2},Ly=60,Dy={lg:1200,md:996,sm:768,xs:480,xxs:0},My=[12,12],Oy=["se","sw","ne","nw","e","w","n","s"],Py=[{source:"system:nav",name:"Nav",w:3,h:4,label:"Navigation",icon:Ac},{source:"system:agents",name:"Agents",w:3,h:4,label:"Agents",icon:Pr},{source:"system:health",name:"Health",w:3,h:3,label:"Health",icon:jc},{source:"system:stats",name:"Stats",w:3,h:4,label:"Stats",icon:lc},{source:"system:quick-links",name:"Quick Links",w:3,h:4,label:"Links",icon:cc},{source:"system:chat",name:"Chat",w:4,h:5,label:"Chat",icon:vn}],Il=re.forwardRef(({widget:t,space:e,onRemove:s,style:r,className:i,onMouseDown:a,onMouseUp:d,onTouchStart:l,onTouchEnd:c,children:f},b)=>{const u=w.useCallback(()=>s(t.id),[t.id,s]);return n.jsxs("div",{ref:b,style:r,className:i,onMouseDown:a,onMouseUp:d,onTouchStart:l,onTouchEnd:c,children:[n.jsx(By,{widget:t,space:e,onRemove:u}),f]})});Il.displayName="MemoWidgetItem";const Wy=re.memo(Il);function Uy({widget:t,space:e,onRemove:s}){const r=w.useRef(null),i=w.useRef(null),a=w.useRef(e),[d,l]=w.useState(null),[c,f]=w.useState(!0);if(w.useEffect(()=>{a.current=e},[e]),w.useEffect(()=>{if(t.format==="system"||!r.current)return;if(!t.source||t.source.trim()===""){l("Empty widget — no source code"),f(!1);return}f(!0),l(null),i.current=new yl(r.current,{onLog:u=>console.log(`[Widget ${t.id}]`,u)}),i.current.setMessageHandler(u=>{var m,y,_,R;const p=a.current;if(u.type==="canvas"&&((m=u.payload)==null?void 0:m.action)==="createWidget"){const k=u.payload.def;if(!k)return{ok:!1,error:"createWidget requires a `def` object"};const I=Number.isFinite(k.w)?k.w:4,g=Number.isFinite(k.h)?k.h:4,j=Number.isFinite(k.x)&&Number.isFinite(k.y)?{x:k.x,y:k.y}:gs(p.widgets||[],I,g);try{const v=ve.addWidget(p.id,{name:k.name||"Agent Widget",format:k.format||"react",source:k.source||"",x:j.x,y:j.y,w:I,h:g});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:p.id}})),{ok:!0,widgetId:v.id}}catch(v){return{ok:!1,error:v.message}}}if(u.type==="canvas"&&((y=u.payload)==null?void 0:y.action)==="updateWidget"){const{id:k,patch:I}=u.payload;return k?(ve.updateWidget(p.id,k,I||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:p.id}})),{ok:!0,id:k}):{ok:!1,error:"updateWidget requires an `id`"}}if(u.type==="canvas"&&((_=u.payload)==null?void 0:_.action)==="listWidgets")return{ok:!0,widgets:p.widgets||[]};if(u.type==="canvas"&&((R=u.payload)==null?void 0:R.action)==="removeWidget"){const k=u.payload.id;return k?(ve.removeWidget(p.id,k),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:p.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}});const b=setTimeout(()=>{f(!1),l("Sandbox timeout: widget took longer than 30s to render. The widget source may have an infinite loop or an unhandled exception. Open DevTools (F12) → Console to see the iframe-side error.")},3e4);return i.current.render(t.format,t.source).then(()=>{clearTimeout(b),f(!1)}).catch(u=>{clearTimeout(b),f(!1),l(String(u))}),()=>{var u;clearTimeout(b),(u=i.current)==null||u.destroy()}},[t.format,t.source,t.id]),t.format==="system"){const b=Ry[t.source];return b?n.jsxs("div",{className:"w-full h-full rounded-xl overflow-hidden flex flex-col group transition-colors shadow-md",style:{background:"var(--color-desk-widget-bg)",border:"1px solid var(--color-desk-border)",boxShadow:"0 4px 12px var(--theme-shadow, rgba(60,40,15,0.15))"},children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b panel-drag-handle cursor-move",style:{borderColor:"var(--color-desk-border-light)",background:"var(--theme-leather, rgba(58,37,24,0.05))"},children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--color-desk-accent)"},children:t.name}),n.jsx("button",{onClick:s,className:"opacity-0 group-hover:opacity-100 text-xs px-1 transition-opacity",style:{color:"var(--color-desk-text-muted)"},children:"×"})]}),n.jsx("div",{className:"flex-1 overflow-auto relative",children:n.jsx(Ty,{name:t.name,children:n.jsx(b,{space:e,widget:t,onRemove:s})})})]}):n.jsxs("div",{className:"w-full h-full flex items-center justify-center text-xs text-red-400",children:["Unknown system widget: ",t.source]})}return n.jsxs("div",{className:"w-full h-full rounded-xl overflow-hidden flex flex-col shadow-md",style:{background:"var(--color-desk-widget-bg)",border:"1px solid var(--color-desk-border)",boxShadow:"0 4px 12px var(--theme-shadow, rgba(60,40,15,0.15))"},children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b panel-drag-handle cursor-move",style:{borderColor:"var(--color-desk-border-light)",background:"var(--theme-leather, rgba(58,37,24,0.05))"},children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--color-desk-accent)"},children:t.name}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("button",{onClick:b=>{b.stopPropagation(),window.dispatchEvent(new CustomEvent("titan:widget:edit",{detail:{spaceId:e.id,widgetId:t.id}}))},onMouseDown:b=>b.stopPropagation(),className:"px-1",style:{color:"var(--color-desk-text-muted)"},title:"Edit widget",children:n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 2 4 4-14 14H4v-4L18 2z"})})}),n.jsx("button",{onClick:s,className:"text-xs px-1",style:{color:"var(--color-desk-text-muted)"},children:"×"})]})]}),n.jsx("div",{className:"flex-1 relative",children:d?n.jsx("div",{className:"p-3 text-xs text-red-400 font-mono whitespace-pre-wrap",children:d}):n.jsxs(n.Fragment,{children:[n.jsx("iframe",{ref:r,className:"w-full h-full border-0",sandbox:"allow-scripts",title:t.name}),c&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-xs",style:{background:"var(--theme-paper, rgba(253,246,227,0.85))",color:"var(--color-desk-text-muted)",fontFamily:"var(--theme-font-display, 'Georgia', serif)"},children:n.jsx("span",{className:"animate-pulse",children:"Loading widget…"})})]})})]})}const By=re.memo(Uy);function Ft({label:t,onClick:e,children:s,variant:r="default",disabled:i}){return n.jsx("button",{type:"button",onClick:e,disabled:i,className:`titan-canvas-icon-button titan-canvas-icon-button--${r}`,title:t,"aria-label":t,children:s})}function Fy(){const{spaceId:t}=ql(),e=ha(),{toast:s}=Kl(),r=Xf(),[i,a]=w.useState(null),[d]=w.useState(!1),[l,c]=w.useState(!1),[f,b]=w.useState(null),[u,p]=w.useState(!1),[m,y]=w.useState(!1),[_,R]=w.useState(!1),[k,I]=w.useState(1200),g=w.useRef(null),j=w.useRef(null),{info:v,triggerUpdate:A,waitForReload:E}=sp(),[N,D]=w.useState(!1),[S,T]=w.useState(!1),[P,M]=w.useState(!1);w.useEffect(()=>{const $=t||"home",G=ve.get($);if(G){if($==="home"&&!G.widgets.some(J=>J.source==="system:home-hero")){let J=!1;try{J=localStorage.getItem("titan-home-hero-pinned")==="1"}catch{}if(!J){try{localStorage.setItem("titan-home-hero-pinned","1")}catch{}const le=gs(G.widgets,6,5);ve.addWidget($,{name:"Ask TITAN",format:"system",source:"system:home-hero",x:le.x,y:le.y,w:6,h:5}),a(ve.get($)??G);return}}a(G)}else e("/space/home",{replace:!0})},[t,e]),w.useEffect(()=>{const $=()=>{const le=j.current;if(!le)return null;const be=new ResizeObserver(Ee=>{for(const H of Ee)I(H.contentRect.width)});return be.observe(le),I(le.getBoundingClientRect().width||1200),be};let G=$();const J=setInterval(()=>{G||(G=$()),G&&clearInterval(J)},200);return()=>{G==null||G.disconnect(),clearInterval(J)}},[i==null?void 0:i.id]),w.useEffect(()=>{const $=G=>{(G.metaKey||G.ctrlKey)&&G.key==="k"&&(G.preventDefault(),y(J=>!J)),(G.metaKey||G.ctrlKey)&&G.key==="j"&&(G.preventDefault(),window.dispatchEvent(new CustomEvent("titan:chat:toggle")))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[]),np([{key:"?",action:()=>R(!0),description:"Show keyboard shortcuts help"},{key:"g",shift:!0,action:()=>e("/space/command"),description:"Go to Command Post space"},{key:"h",shift:!0,action:()=>e("/space/home"),description:"Go to Home space"},{key:"s",shift:!0,action:()=>e("/space/settings"),description:"Go to Settings space"},{key:"i",shift:!0,action:()=>e("/space/intelligence"),description:"Go to Intelligence space"}]);const F=w.useCallback(()=>{},[]),V=w.useRef(null),Y=w.useRef(null),q=w.useCallback($=>{i&&(Y.current=$,V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{const G=Y.current;!G||!i||(ve.updateLayout(i.id,G.map(J=>({i:J.i,x:J.x,y:J.y,w:J.w,h:J.h}))),Y.current=null,V.current=null)},50))},[i]),ye=w.useCallback($=>{var le;if(!i)return;const G=(le=i.widgets)==null?void 0:le.find(be=>be.id===$);Bn("canvas_panel_removed",{widgetId:$,format:G==null?void 0:G.format,source:G==null?void 0:G.source}),ve.removeWidget(i.id,$);const J=Array.isArray(i.widgets)?i.widgets:[];a({...i,widgets:J.filter(be=>be.id!==$)})},[i]),Z=w.useCallback($=>{if(!i)return;const G=ve.addWidget(i.id,$),J=Array.isArray(i.widgets)?i.widgets:[];return a({...i,widgets:[...J,G]}),Bn($.format==="system"?"canvas_system_panel_created":"canvas_panel_created",{source:$.source,name:$.name,format:$.format}),G},[i]),ge=w.useCallback(($,G)=>{if(!i||!Array.isArray(i.widgets)||i.widgets.length===0)return{x:0,y:0};const J=12,le=new Set;for(const be of i.widgets)for(let Ee=0;Ee<be.w;Ee++)for(let H=0;H<be.h;H++)le.add(`${be.x+Ee},${be.y+H}`);for(let be=0;be<200;be++)for(let Ee=0;Ee<=J-$;Ee++){let H=!0;for(let K=0;K<$;K++){for(let X=0;X<G;X++)if(le.has(`${Ee+K},${be+X}`)){H=!1;break}if(!H)break}if(H)return{x:Ee,y:be}}return{x:0,y:0}},[i]),he=w.useCallback(($,G,J=4,le=4)=>{const be=ge(J,le);Z({name:G,format:"system",source:$,x:be.x,y:be.y,w:J,h:le})},[Z,ge]),se=w.useCallback(async()=>{if(!i)return;const $=Array.isArray(i.widgets)?i.widgets.length:0;Bn("canvas_clear_all",{panelCount:$});try{await ve.clearSpace(i.id),a({...i,widgets:[]}),s("success","Canvas cleared.")}catch(G){s("error",`Couldn't clear the canvas — try again. (${G.message})`)}finally{M(!1)}},[i,s]),ie=w.useCallback(async()=>{if(T(!1),!(v!=null&&v.isNewer)||N)return;const $=v.current;D(!0);try{const G=await A(!0);if(!G.ok){D(!1),s("error",`Update failed — ${G.error||"unknown error"}.`);return}const J=await E($);D(!1),J?(s("success",`Updated to ${J}. Reloading…`),window.location.reload()):s("error","Update sent, but the gateway did not come back within 30s. Check service status manually.")}catch(G){D(!1),s("error",`Update failed — try again. (${G.message})`)}},[v,N,A,E,s]);w.useEffect(()=>{const $=G=>{const J=G.detail;if(console.log("[TitanCanvas] titan:space:refresh received:",J),!!i&&(J==null?void 0:J.spaceId)===i.id){const le=ve.get(i.id);le&&(console.log("[TitanCanvas] Refreshing space, widget count:",le.widgets.length),a(le))}};return window.addEventListener("titan:space:refresh",$),()=>window.removeEventListener("titan:space:refresh",$)},[i]),w.useEffect(()=>{const $=G=>{const J=G.detail;if(i&&J!=null&&J.source){const le=Number.isFinite(J.w)?J.w:4,be=Number.isFinite(J.h)?J.h:4,Ee=typeof J.name=="string"&&J.name.trim()?J.name.trim():String(J.source).replace("system:","").replace(/-/g," "),H=J.format==="react"||J.format==="vanilla"||J.format==="html"||J.format==="system"?J.format:String(J.source).startsWith("system:")?"system":"react",K=ge(le,be);Z({name:Ee,format:H,source:String(J.source),x:K.x,y:K.y,w:le,h:be})}};return window.addEventListener("titan:widget:add",$),()=>window.removeEventListener("titan:widget:add",$)},[i,Z,ge]),w.useEffect(()=>{const $=G=>{const J=G.detail;i&&(J==null?void 0:J.spaceId)===i.id&&typeof(J==null?void 0:J.widgetId)=="string"&&b(J.widgetId)};return window.addEventListener("titan:widget:edit",$),()=>window.removeEventListener("titan:widget:edit",$)},[i]),w.useEffect(()=>i?ve.observe(i.id,G=>{console.log("[TitanCanvas] CRDT observer fired, widgets:",G.length),a(J=>J&&{...J,widgets:G})}):void 0,[i==null?void 0:i.id]);const Q=w.useMemo(()=>{const $=i==null?void 0:i.widgets;return Array.isArray($)?$.filter(Boolean):[]},[i]),xe=w.useMemo(()=>Q.map(($,G)=>({i:$.id,x:Number.isFinite($.x)?$.x:G%3*4,y:Number.isFinite($.y)?$.y:Math.floor(G/3)*4,w:Number.isFinite($.w)?$.w:4,h:Number.isFinite($.h)?$.h:4,minW:2,minH:2,maxW:12,maxH:40})),[Q]);return i?n.jsxs("div",{className:"h-full w-full flex",children:[n.jsx(am,{}),n.jsx("div",{className:"fixed bottom-5 right-6 z-[60]",children:n.jsx(Zf,{...r})}),n.jsxs("div",{ref:g,className:"flex-1 relative overflow-auto",children:[n.jsx("style",{children:`
825
- .titan-canvas-grid .react-grid-item > .react-resizable-handle {
826
- background: none;
827
- padding: 0;
828
- opacity: 0.35;
829
- z-index: 10;
830
- transition: opacity 120ms ease, background-color 120ms ease;
831
- }
832
- .titan-canvas-grid .react-grid-item:hover > .react-resizable-handle { opacity: 0.85; }
833
- .titan-canvas-grid .react-grid-item > .react-resizable-handle:hover,
834
- .titan-canvas-grid .react-grid-item > .react-resizable-handle:active { opacity: 1; }
835
- /* Corner handles: 22x22 with a ring-coloured chevron */
836
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se,
837
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw,
838
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne,
839
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw {
840
- width: 22px;
841
- height: 22px;
842
- background-image: none;
843
- transform: none;
844
- }
845
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se::after,
846
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw::after,
847
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne::after,
848
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw::after {
849
- content: "";
850
- position: absolute;
851
- width: 12px; height: 12px;
852
- border: 2px solid var(--color-desk-brass);
853
- border-radius: 3px;
854
- }
855
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se::after { right: 3px; bottom: 3px; border-top: none; border-left: none; }
856
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw::after { left: 3px; bottom: 3px; border-top: none; border-right: none; }
857
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne::after { right: 3px; top: 3px; border-bottom: none; border-left: none; }
858
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw::after { left: 3px; top: 3px; border-bottom: none; border-right: none; }
859
- /* Edge handles: full-edge strips with a centre grip */
860
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e,
861
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w {
862
- top: 8px; bottom: 8px; height: auto; margin-top: 0;
863
- width: 8px; background-image: none; transform: none;
864
- }
865
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n,
866
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s {
867
- left: 8px; right: 8px; width: auto; margin-left: 0;
868
- height: 8px; background-image: none; transform: none;
869
- }
870
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after,
871
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after,
872
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after,
873
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after {
874
- content: ""; position: absolute; background: var(--color-desk-brass); border-radius: 2px;
875
- }
876
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after,
877
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after {
878
- top: 50%; transform: translateY(-50%);
879
- width: 3px; height: 32px;
880
- }
881
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after { right: 2px; }
882
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after { left: 2px; }
883
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after,
884
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after {
885
- left: 50%; transform: translateX(-50%);
886
- height: 3px; width: 32px;
887
- }
888
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after { top: 2px; }
889
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after { bottom: 2px; }
890
- /* Allow resizing and dragging freely — placeholder turns accent blue */
891
- .titan-canvas-grid .react-grid-placeholder {
892
- background: rgba(99, 102, 241, 0.14) !important;
893
- border: 1px dashed rgba(99, 102, 241, 0.55) !important;
894
- border-radius: 12px;
895
- opacity: 1 !important;
896
- }
897
- `}),n.jsx("div",{className:"fixed inset-0 opacity-[0.06] pointer-events-none",style:{backgroundImage:"radial-gradient(circle at 1px 1px, var(--theme-metal-dark, rgba(120,90,50,0.4)) 1px, transparent 0)",backgroundSize:"24px 24px"}}),n.jsxs("div",{className:"titan-canvas-titlebar absolute top-0 left-0 right-0 z-40",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("div",{className:"titan-canvas-space-icon",style:{color:i.color||"var(--color-desk-accent)"},children:n.jsx(Ic,{className:"w-4 h-4"})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("h1",{className:"titan-canvas-title truncate",children:i.name}),n.jsxs("div",{className:"titan-canvas-subtitle",children:[Q.length," panel",Q.length!==1?"s":""," on desktop canvas"]})]}),n.jsx(Ft,{label:"Open Mission Chat",onClick:()=>e("/mission"),variant:"primary",children:n.jsx(qt,{className:"w-4 h-4"})}),n.jsx("button",{onClick:()=>c(!0),className:"titan-canvas-instructions truncate",title:"Edit agent instructions for this space",children:i.agentInstructions?n.jsx("span",{className:"truncate",children:i.agentInstructions}):n.jsx("span",{className:"italic",children:"add agent instructions"})})]}),n.jsxs("div",{className:"titan-canvas-toolbar",children:[Py.map($=>{const G=$.icon;return n.jsx(Ft,{label:`Add ${$.label}`,onClick:()=>he($.source,$.name,$.w,$.h),children:n.jsx(G,{className:"w-4 h-4"})},$.source)}),Q.length>0&&n.jsx(Ft,{label:"Clear canvas",onClick:()=>M(!0),variant:"danger",children:n.jsx(dc,{className:"w-4 h-4"})}),n.jsx("button",{disabled:N,className:`titan-canvas-version-chip ${v!=null&&v.isNewer?"titan-canvas-version-chip--update":""}`,style:v!=null&&v.isNewer?void 0:{background:"var(--theme-paper, rgba(253,246,227,0.7))",borderColor:"var(--color-desk-border)"},title:v!=null&&v.isNewer?`Update available: ${v.current} → ${v.latest}`:`TITAN ${(v==null?void 0:v.current)||""}`,onClick:()=>{!(v!=null&&v.isNewer)||N||T(!0)},children:N?"…":v!=null&&v.isNewer?`↑ ${v.latest}`:`v${(v==null?void 0:v.current)||""}`}),n.jsx(Ft,{label:"Open widget gallery",onClick:()=>p(!0),variant:"primary",children:n.jsx(wc,{className:"w-4 h-4"})}),n.jsx(Ft,{label:"Open command palette",onClick:()=>y(!0),children:n.jsx(pc,{className:"w-4 h-4"})}),n.jsx(Ft,{label:"Open chat dock",onClick:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle")),children:n.jsx(vn,{className:"w-4 h-4"})})]})]}),n.jsx("div",{ref:j,className:"relative pt-28 min-h-[5000px]",style:{transform:`scale(${r.zoom})`,transformOrigin:"top center",transition:"transform 120ms ease-out"},children:Q.length===0?n.jsx($y,{space:i,onAddWidget:he,onOpenChat:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle",{detail:{open:!0}}))}):n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"pt-12 text-center",children:n.jsx("div",{className:"inline-block rounded-xl px-6 py-3 border text-sm font-serif",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)"},children:"Loading grid..."})}),children:n.jsx(Ay,{className:"layout titan-canvas-grid",width:k,layouts:{lg:xe},breakpoints:Dy,cols:Iy,rowHeight:Ly,margin:My,containerPadding:[12,12],isDraggable:!0,isResizable:!0,draggableHandle:".panel-drag-handle",resizeHandles:Oy,compactType:null,preventCollision:!1,allowOverlap:!0,useCSSTransforms:!0,onLayoutChange:F,onDragStop:$=>{q($)},onResizeStop:$=>{q($)},children:Q.map($=>n.jsx(Wy,{widget:$,space:i,onRemove:ye},$.id))})})}),n.jsx(Jp,{space:i,defaultExpanded:d,hideMascot:!0}),n.jsx(em,{}),n.jsx(Qp,{}),n.jsx(cm,{space:i,open:l,onClose:()=>c(!1),onSaved:$=>{a(G=>G&&{...G,agentInstructions:$||void 0})}}),f&&(()=>{const $=Q.find(G=>G.id===f);return!$||$.format==="system"?(b(null),null):n.jsx(hm,{widget:$,spaceId:i.id,open:!0,onClose:()=>b(null),onSaved:G=>{const J=Q.map(le=>le.id===G.id?{...le,...G}:le);a(le=>le&&{...le,widgets:J})}})})(),n.jsx(ym,{open:u,onClose:()=>p(!1)}),n.jsx(_m,{}),m&&n.jsx(Al,{currentSpaceId:i.id,onSpaceSelect:$=>{e(`/space/${$}`),y(!1)},onAction:$=>{$.type==="widget"&&he($.source,$.name,$.w,$.h),y(!1)},onClose:()=>y(!1)}),n.jsx(ip,{open:_,onClose:()=>R(!1)}),n.jsx(xi,{open:P,title:"Clear this canvas?",message:`This removes all ${Q.length} panel${Q.length!==1?"s":""} from "${i.name}". This can't be undone.`,confirmLabel:"Clear canvas",onConfirm:se,onCancel:()=>M(!1)}),n.jsx(xi,{open:S,variant:"primary",title:"Update TITAN?",message:`Update TITAN from ${v==null?void 0:v.current} → ${v==null?void 0:v.latest}? Your data in ~/.titan/ will be preserved. The gateway will restart after the update.`,confirmLabel:"Update",onConfirm:ie,onCancel:()=>T(!1)})]})]}):n.jsx("div",{className:"h-full w-full flex items-center justify-center",children:n.jsx("div",{className:"rounded-xl px-6 py-3 border text-sm",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)",fontFamily:"var(--theme-font-display, 'Georgia', serif)"},children:"Loading space..."})})}function $y({space:t,onAddWidget:e,onOpenChat:s}){const r=[{title:"System",items:[{label:"SOMA",source:"system:soma",w:6,h:6},{label:"Command Post",source:"system:command-post",w:8,h:6},{label:"Overview",source:"system:overview",w:6,h:5},{label:"Organism",source:"system:organism",w:6,h:6},{label:"Infra",source:"system:infra",w:6,h:4},{label:"VRAM",source:"system:vram",w:6,h:6},{label:"Fleet",source:"system:fleet",w:6,h:5}]},{title:"Intelligence",items:[{label:"Intelligence",source:"system:intelligence",w:6,h:5},{label:"Memory Graph",source:"system:memory-graph",w:8,h:7},{label:"Memory Wiki",source:"system:memory-wiki",w:6,h:6},{label:"Autoresearch",source:"system:autoresearch",w:6,h:6},{label:"Self-Proposals",source:"system:self-proposals",w:6,h:6},{label:"Training",source:"system:training",w:6,h:6},{label:"Eval",source:"system:eval",w:6,h:6}]},{title:"Tools",items:[{label:"Tools",source:"system:tools",w:5,h:4},{label:"Files",source:"system:files",w:4,h:6},{label:"Browser",source:"system:browser",w:6,h:5},{label:"Recipes",source:"system:recipes",w:6,h:6},{label:"Voice",source:"system:voice",w:5,h:5}]},{title:"Workflows",items:[{label:"Mission Driver",source:"system:mission-driver",w:7,h:7},{label:"Mission Graph",source:"system:mission-graph",w:8,h:7},{label:"Daily Digest",source:"system:daily-digest",w:5,h:7},{label:"Time Travel",source:"system:time-travel",w:8,h:6},{label:"Sessions",source:"system:sessions",w:6,h:5},{label:"Checkpoints",source:"system:checkpoints",w:6,h:5},{label:"Cron",source:"system:cron",w:6,h:6}]},{title:"Comms",items:[{label:"Watch",source:"system:watch",w:8,h:7},{label:"Backup",source:"system:backup",w:6,h:6},{label:"Teams",source:"system:teams",w:6,h:6}]}];return n.jsx("div",{className:"h-full flex items-start justify-center pt-8 pb-32 px-4 sm:px-6",children:n.jsxs("div",{className:"titan-canvas-empty-panel text-center w-full max-w-4xl px-5 sm:px-8 py-8 sm:py-10",children:[n.jsx("style",{children:`
898
- .titan-empty-hero {
899
- background: linear-gradient(180deg,
900
- color-mix(in srgb, var(--theme-metal-bright) 22%, transparent) 0%,
901
- color-mix(in srgb, var(--theme-metal) 14%, transparent) 100%);
902
- color: var(--theme-accent);
903
- border: 1px solid color-mix(in srgb, var(--theme-metal) 55%, transparent);
904
- box-shadow:
905
- 0 0 0 0 color-mix(in srgb, var(--theme-accent) 0%, transparent),
906
- 0 2px 6px var(--theme-shadow);
907
- transition: transform 140ms ease, box-shadow 220ms ease, border-color 140ms ease;
908
- font-family: var(--theme-font-display);
909
- }
910
- .titan-empty-hero:hover {
911
- transform: translateY(-1px);
912
- border-color: var(--theme-metal-bright);
913
- box-shadow:
914
- 0 0 24px color-mix(in srgb, var(--theme-accent) 35%, transparent),
915
- 0 4px 12px var(--theme-shadow);
916
- }
917
- .titan-empty-chip {
918
- width: 110px;
919
- background: var(--theme-paper);
920
- color: var(--theme-ink-soft);
921
- border: 1px solid color-mix(in srgb, var(--theme-metal) 40%, transparent);
922
- box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--theme-paper-line) 50%, transparent);
923
- font-family: var(--theme-font-display);
924
- transition: transform 120ms ease, border-color 120ms ease, color 120ms ease, box-shadow 120ms ease;
925
- }
926
- .titan-empty-chip:hover {
927
- transform: translateY(-1px);
928
- border-color: var(--theme-metal-bright);
929
- color: var(--theme-ink);
930
- box-shadow:
931
- inset 0 0 0 1px color-mix(in srgb, var(--theme-metal-bright) 35%, transparent),
932
- 0 2px 6px var(--theme-shadow);
933
- }
934
- .titan-empty-group-label {
935
- font-family: var(--theme-font-mono);
936
- color: var(--theme-metal-dark);
937
- letter-spacing: 0.18em;
938
- }
939
- .titan-empty-rule {
940
- background: linear-gradient(90deg,
941
- transparent 0%,
942
- color-mix(in srgb, var(--theme-metal) 50%, transparent) 50%,
943
- transparent 100%);
944
- }
945
- `}),n.jsx("div",{className:"w-14 h-14 rounded-lg flex items-center justify-center mx-auto mb-5",style:{background:"color-mix(in srgb, var(--theme-metal) 16%, transparent)",border:"1px solid color-mix(in srgb, var(--theme-metal) 35%, transparent)"},children:n.jsx("svg",{className:"w-7 h-7",style:{color:"var(--theme-metal)"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"})})}),n.jsx("h2",{className:"text-xl font-bold mb-2",style:{color:"var(--theme-ink)",fontFamily:"var(--theme-font-display)"},children:t.name}),n.jsx("p",{className:"text-sm mb-7",style:{color:"var(--theme-ink-soft)",fontFamily:"var(--theme-font-display)"},children:'This desk is empty. Ask the AI to build something — try "make me a weather widget for Kelseyville" or "add a clock" — or place a system panel below.'}),n.jsx("div",{className:"flex justify-center mb-8",children:n.jsxs("button",{onClick:s,className:"titan-empty-hero inline-flex items-center gap-2 px-6 py-3 rounded-lg text-base font-semibold",children:[n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a7 7 0 0 0-4 12.7V17a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-2.3A7 7 0 0 0 12 2z"}),n.jsx("path",{d:"M10 22h4"})]}),"Ask Agent"]})}),n.jsx("div",{className:"space-y-5 text-left",children:r.map(i=>n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-3 mb-2.5 px-1",children:[n.jsx("span",{className:"titan-empty-group-label text-[10px] font-bold uppercase",children:i.title}),n.jsx("span",{className:"titan-empty-rule flex-1 h-px"})]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:i.items.map(a=>n.jsxs("button",{onClick:()=>e(a.source,a.label,a.w,a.h),className:"titan-empty-chip px-3 py-1.5 rounded-md text-[11px] text-center",title:`Add ${a.label}`,children:["+ ",a.label]},a.source))})]},i.title))})]})})}const jb=Object.freeze(Object.defineProperty({__proto__:null,default:Fy},Symbol.toStringTag,{value:"Module"}));export{bc as D,Xs as G,jb as T};