titan-agent 6.1.0-beta.2 → 6.1.0-beta.21

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 (235) hide show
  1. package/LICENSE +1 -29
  2. package/README.md +1 -1
  3. package/dist/agent/agentLessons.js +2 -2
  4. package/dist/agent/agentLessons.js.map +1 -1
  5. package/dist/agent/autoModeClassifier.js +95 -0
  6. package/dist/agent/autoModeClassifier.js.map +1 -0
  7. package/dist/agent/durableJournal.js +2 -2
  8. package/dist/agent/durableJournal.js.map +1 -1
  9. package/dist/agent/goalDriver.js +67 -0
  10. package/dist/agent/goalDriver.js.map +1 -1
  11. package/dist/agent/goalPlanFile.js +3 -3
  12. package/dist/agent/goalPlanFile.js.map +1 -1
  13. package/dist/agent/missionLifecycle.js +2 -2
  14. package/dist/agent/missionLifecycle.js.map +1 -1
  15. package/dist/agent/subAgent.js +41 -0
  16. package/dist/agent/subAgent.js.map +1 -1
  17. package/dist/agent/toolContract.js +49 -0
  18. package/dist/agent/toolContract.js.map +1 -0
  19. package/dist/agent/toolRunner.js +72 -11
  20. package/dist/agent/toolRunner.js.map +1 -1
  21. package/dist/agent/trajectoryRecorder.js +185 -0
  22. package/dist/agent/trajectoryRecorder.js.map +1 -0
  23. package/dist/agent/verification.js +164 -0
  24. package/dist/agent/verification.js.map +1 -0
  25. package/dist/agent/worktreeExecutor.js +207 -0
  26. package/dist/agent/worktreeExecutor.js.map +1 -0
  27. package/dist/config/schema.js +28 -1
  28. package/dist/config/schema.js.map +1 -1
  29. package/dist/gateway/server.js +54 -0
  30. package/dist/gateway/server.js.map +1 -1
  31. package/dist/memory/facade.js +137 -0
  32. package/dist/memory/facade.js.map +1 -0
  33. package/dist/migrations/003-soma-profile-default.js +2 -2
  34. package/dist/migrations/003-soma-profile-default.js.map +1 -1
  35. package/dist/migrations/005-route-redirects.js +3 -1
  36. package/dist/migrations/005-route-redirects.js.map +1 -1
  37. package/dist/migrations/runner.js +2 -2
  38. package/dist/migrations/runner.js.map +1 -1
  39. package/dist/providers/defaultModel.js +14 -0
  40. package/dist/providers/defaultModel.js.map +1 -1
  41. package/dist/providers/router.js +4 -0
  42. package/dist/providers/router.js.map +1 -1
  43. package/dist/providers/stub.js +185 -0
  44. package/dist/providers/stub.js.map +1 -0
  45. package/dist/skills/builtin/backup.js +1 -2
  46. package/dist/skills/builtin/backup.js.map +1 -1
  47. package/dist/skills/builtin/contracts.js +254 -0
  48. package/dist/skills/builtin/contracts.js.map +1 -0
  49. package/dist/skills/builtin/download_image.js +9 -0
  50. package/dist/skills/builtin/download_image.js.map +1 -1
  51. package/dist/skills/builtin/filesystem.js +70 -20
  52. package/dist/skills/builtin/filesystem.js.map +1 -1
  53. package/dist/skills/registry.js +7 -0
  54. package/dist/skills/registry.js.map +1 -1
  55. package/dist/storage/patterns.js +2 -2
  56. package/dist/storage/patterns.js.map +1 -1
  57. package/dist/storage/personalGallery.js +2 -2
  58. package/dist/storage/personalGallery.js.map +1 -1
  59. package/dist/storage/somaProfile.js +2 -2
  60. package/dist/storage/somaProfile.js.map +1 -1
  61. package/dist/utils/constants.js +1 -1
  62. package/dist/utils/constants.js.map +1 -1
  63. package/package.json +2 -2
  64. package/ui/dist/assets/{AuditPanel-DrDvXZ9u.js → AuditPanel-RNrvKmfX.js} +1 -1
  65. package/ui/dist/assets/{AutonomyPanel-BfhW-PRX.js → AutonomyPanel-D0nmt79R.js} +2 -2
  66. package/ui/dist/assets/{AutopilotPanel-C3yQBxAp.js → AutopilotPanel-DlcdfRRy.js} +1 -1
  67. package/ui/dist/assets/{AutoresearchPanel-BgpR3EcK.js → AutoresearchPanel-CXeO6kGK.js} +2 -2
  68. package/ui/dist/assets/BackupPanel-CKb-cDsk.js +1 -0
  69. package/ui/dist/assets/{BrowserPanel-BNaKZOnn.js → BrowserPanel-CDaoF6n5.js} +1 -1
  70. package/ui/dist/assets/CPActivity-BZbeztg1.js +1 -0
  71. package/ui/dist/assets/CPAgentDetail-C9fvLxKi.js +1 -0
  72. package/ui/dist/assets/CPAgents-BsBA9kb2.js +1 -0
  73. package/ui/dist/assets/CPApprovals-Di5itVIK.js +1 -0
  74. package/ui/dist/assets/CPCosts-DmgckHli.js +1 -0
  75. package/ui/dist/assets/CPDashboard-CmSb7woK.js +1 -0
  76. package/ui/dist/assets/{CPFiles-CUpP5I82.js → CPFiles-Dd0NGcpX.js} +1 -1
  77. package/ui/dist/assets/CPGoals-DeILFq0A.js +1 -0
  78. package/ui/dist/assets/{CPInbox-DUW_hntB.js → CPInbox-DAtidZez.js} +2 -2
  79. package/ui/dist/assets/CPIssueDetail-BvwoGI57.js +1 -0
  80. package/ui/dist/assets/CPIssues-CZ1hIKDP.js +1 -0
  81. package/ui/dist/assets/{CPLayout-J0fa-it4.js → CPLayout-luPwhNpA.js} +3 -3
  82. package/ui/dist/assets/CPOrg-BlYp_KP6.js +8 -0
  83. package/ui/dist/assets/CPRuns-D0HMCjIo.js +1 -0
  84. package/ui/dist/assets/{CPSocial-By_FStZ4.js → CPSocial-CZaGi14s.js} +2 -2
  85. package/ui/dist/assets/ChannelsPanel-khiBHwx3.js +1 -0
  86. package/ui/dist/assets/{CheckpointsPanel-DvKUd2VF.js → CheckpointsPanel-n2y3jzzT.js} +1 -1
  87. package/ui/dist/assets/{CommandPostHub-CQqRYBjf.js → CommandPostHub-iWf-zt5p.js} +4 -4
  88. package/ui/dist/assets/{CronPanel-Brmnnu8_.js → CronPanel-BkRJl8u6.js} +1 -1
  89. package/ui/dist/assets/{DataTable-seaktPzB.js → DataTable-DZ2cG3Cv.js} +1 -1
  90. package/ui/dist/assets/{DreamPanel-CO7iSdjn.js → DreamPanel-DF6l0WB-.js} +1 -1
  91. package/ui/dist/assets/{EmptyState-CmK9fywh.js → EmptyState-D7xwm8hA.js} +1 -1
  92. package/ui/dist/assets/{EvalHarnessPanel-2RVBKbym.js → EvalHarnessPanel-BHabu49z.js} +2 -2
  93. package/ui/dist/assets/{EvalPanel-CqAwhFQ5.js → EvalPanel-yAesMLSP.js} +1 -1
  94. package/ui/dist/assets/{FileViewer-D98m-vF5.js → FileViewer-DOWUQccc.js} +52 -14
  95. package/ui/dist/assets/{FilesPanel-dRQM0apb.js → FilesPanel-BjuDhqaX.js} +2 -2
  96. package/ui/dist/assets/FleetPanel-B0ZhS2XX.js +1 -0
  97. package/ui/dist/assets/{HomelabPanel-DjMUrO2B.js → HomelabPanel-D373ddvj.js} +1 -1
  98. package/ui/dist/assets/InfraView-CI99NZbI.js +2 -0
  99. package/ui/dist/assets/InlineEditableField-fDk3eGVo.js +1 -0
  100. package/ui/dist/assets/Input-j10hONMY.js +1 -0
  101. package/ui/dist/assets/IntegrationsPanel-kPa5Qq-f.js +1 -0
  102. package/ui/dist/assets/IntelligenceView-DeKBaAlY.js +2 -0
  103. package/ui/dist/assets/LearningPanel-B8tqHeEZ.js +1 -0
  104. package/ui/dist/assets/{LogsPanel-Bs9IsTCH.js → LogsPanel-sXc__trb.js} +1 -1
  105. package/ui/dist/assets/McpPanel-DEr8pZwB.js +1 -0
  106. package/ui/dist/assets/{MemoryGraphPanel-F1P9COyY.js → MemoryGraphPanel-DZl7USJ6.js} +1 -1
  107. package/ui/dist/assets/MemoryWikiPanel-DTNVWvVT.js +11 -0
  108. package/ui/dist/assets/{MeshPanel-CgIAh5ZX.js → MeshPanel-b77zyQx4.js} +1 -1
  109. package/ui/dist/assets/MissionCanvas-D_quSl5F.js +69 -0
  110. package/ui/dist/assets/MissionChat-rQ5rUPAt.js +7 -0
  111. package/ui/dist/assets/MissionLibrary-Cxw7sLxv.js +5 -0
  112. package/ui/dist/assets/MissionStart-ChMWO1rr.js +1 -0
  113. package/ui/dist/assets/Modal-Dl5b6Yaj.js +1 -0
  114. package/ui/dist/assets/NvidiaPanel-D7qFbbeJ.js +1 -0
  115. package/ui/dist/assets/{OrganismPanel-CNZM3eof.js → OrganismPanel-EiQ9Gfqx.js} +1 -1
  116. package/ui/dist/assets/OverviewPanel-Bectj1Z5.js +1 -0
  117. package/ui/dist/assets/{PageHeader-llOXO43Z.js → PageHeader-CiuoyvDR.js} +1 -1
  118. package/ui/dist/assets/{PersonaProfilesPanel-CfsQTMra.js → PersonaProfilesPanel-BO87DSVG.js} +1 -1
  119. package/ui/dist/assets/{PersonasPanel-DIac_kZ3.js → PersonasPanel-BNogLwM0.js} +1 -1
  120. package/ui/dist/assets/RecipesPanel-DyqfWlaY.js +1 -0
  121. package/ui/dist/assets/{SecurityPanel-_gqMk8hJ.js → SecurityPanel-OMC-Tvbz.js} +1 -1
  122. package/ui/dist/assets/SelfImprovePanel-DXIfG_df.js +1 -0
  123. package/ui/dist/assets/{SelfProposalsPanel-DuA0zsGH.js → SelfProposalsPanel-CmgEz1TQ.js} +2 -2
  124. package/ui/dist/assets/SessionsPanel-gJXosEGf.js +1 -0
  125. package/ui/dist/assets/{SessionsTab-bFYaFvTZ.js → SessionsTab-BOVzzjTO.js} +1 -1
  126. package/ui/dist/assets/SettingsPanel-DifFGEvi.js +1 -0
  127. package/ui/dist/assets/SettingsView-BNpj0iym.js +2 -0
  128. package/ui/dist/assets/SkeletonLoader-CNSsfH3f.js +1 -0
  129. package/ui/dist/assets/{SkillsPanel-D08WcRGp.js → SkillsPanel-6fbRov-m.js} +1 -1
  130. package/ui/dist/assets/{SomaView-CYukE7Fp.js → SomaView-D3boPl5D.js} +1 -1
  131. package/ui/dist/assets/{StatCard-DT4Bx1mY.js → StatCard-2BmOlamJ.js} +1 -1
  132. package/ui/dist/assets/StatusBadge-CdVHF1nG.js +1 -0
  133. package/ui/dist/assets/Tabs-DW9ytf9H.js +1 -0
  134. package/ui/dist/assets/{TeamsPanel-DOBe72TK.js → TeamsPanel-CNaQ8Dbw.js} +1 -1
  135. package/ui/dist/assets/TelemetryPanel-DL81QlAW.js +1 -0
  136. package/ui/dist/assets/TitanCanvas-DLIN_wV3.js +1152 -0
  137. package/ui/dist/assets/ToolsView-BlChEE4n.js +2 -0
  138. package/ui/dist/assets/Tooltip-oR5JnwoN.js +6 -0
  139. package/ui/dist/assets/{TraceViewer-0bCz0x_a.js → TraceViewer-DtJXjCXV.js} +1 -1
  140. package/ui/dist/assets/TrainingPanel-4XMGaRN_.js +1 -0
  141. package/ui/dist/assets/{VoiceOverlay-B08Sw918.js → VoiceOverlay-B3fXJ-EC.js} +1 -1
  142. package/ui/dist/assets/{VramPanel-CJiic8y4.js → VramPanel-HisAYiqI.js} +1 -1
  143. package/ui/dist/assets/{WatchView-CaQMDEAy.js → WatchView-C92y0hU7.js} +1 -1
  144. package/ui/dist/assets/{WorkTab-D5bi2WRi.js → WorkTab-BYAWcvA1.js} +1 -1
  145. package/ui/dist/assets/{WorkflowsPanel-DdY6E93C.js → WorkflowsPanel-D2DiOBLA.js} +1 -1
  146. package/ui/dist/assets/{arrow-left-CHJyrO8S.js → arrow-left-thXQMJQ6.js} +1 -1
  147. package/ui/dist/assets/{briefcase-ROIEmiah.js → briefcase-ByMhDqlL.js} +1 -1
  148. package/ui/dist/assets/{chart-column-wFkjV3Ni.js → chart-column-CYHJVuxN.js} +1 -1
  149. package/ui/dist/assets/{check-BcOm5jPO.js → check-ChWLFWCx.js} +1 -1
  150. package/ui/dist/assets/{chevron-down-CM11GPpR.js → chevron-down-CU_O_5h3.js} +1 -1
  151. package/ui/dist/assets/{chevron-right-aFDDgFsL.js → chevron-right-DAiXsK24.js} +1 -1
  152. package/ui/dist/assets/{chevron-up-D6g7FB6i.js → chevron-up-BudRYwvy.js} +1 -1
  153. package/ui/dist/assets/{circle-check-big-DPz64kZW.js → circle-check-big-gkA-V2JW.js} +1 -1
  154. package/ui/dist/assets/{clock-BbCCaukN.js → clock-qO5kIED9.js} +1 -1
  155. package/ui/dist/assets/clsx-B-dksMZM.js +1 -0
  156. package/ui/dist/assets/{dollar-sign-Dy5-qkg3.js → dollar-sign-1gQNJK3V.js} +1 -1
  157. package/ui/dist/assets/{download-DjheLEns.js → download-DMD1m87c.js} +1 -1
  158. package/ui/dist/assets/{external-link-BgxGF7ZQ.js → external-link-ByafQkZ7.js} +1 -1
  159. package/ui/dist/assets/{folder-DY4eeMdo.js → folder-DeG4RuOD.js} +1 -1
  160. package/ui/dist/assets/{funnel-LWmcwhj-.js → funnel-wE8i5V9Y.js} +1 -1
  161. package/ui/dist/assets/{git-branch-CPZciK10.js → git-branch-BWSuK1LU.js} +1 -1
  162. package/ui/dist/assets/index-B8YEFBRH.js +277 -0
  163. package/ui/dist/assets/index-Cb5bSxRB.css +1 -0
  164. package/ui/dist/assets/{layers-Bn7bgu2Z.js → layers-tN-wIpE0.js} +1 -1
  165. package/ui/dist/assets/{legacy-BVPeht6t.js → legacy-BSZBdyop.js} +2 -2
  166. package/ui/dist/assets/{lightbulb-tzuCyEQk.js → lightbulb-TUHKCda3.js} +1 -1
  167. package/ui/dist/assets/{list-todo-say4NbSw.js → list-todo-DtxcUGz2.js} +1 -1
  168. package/ui/dist/assets/{missions-DbC8UmMc.js → missions-C3EC4uKT.js} +1 -1
  169. package/ui/dist/assets/{network-v9O7MmZT.js → network-ephW7nah.js} +1 -1
  170. package/ui/dist/assets/{pause-CZo33QlA.js → pause-DeggUVZc.js} +1 -1
  171. package/ui/dist/assets/{play-DbCJhc5H.js → play-Dfc0ia6v.js} +1 -1
  172. package/ui/dist/assets/{plug-CtpCZg2z.js → plug-Bl_6i_9u.js} +1 -1
  173. package/ui/dist/assets/{plus-O61rB_YF.js → plus-CQwCh7WY.js} +1 -1
  174. package/ui/dist/assets/{proxy-BAUTNyg6.js → proxy-BjQ4lsww.js} +1 -1
  175. package/ui/dist/assets/{rotate-ccw-n5WkWR51.js → rotate-ccw-CUuN2ebi.js} +1 -1
  176. package/ui/dist/assets/{save-D2Qh8KyN.js → save-PlTUvsN5.js} +1 -1
  177. package/ui/dist/assets/{search-C9SdcZJq.js → search-BHgLDT-j.js} +1 -1
  178. package/ui/dist/assets/{send-DZ_5M5QQ.js → send-pflQNBoT.js} +1 -1
  179. package/ui/dist/assets/{shield-check-DyP5PmaY.js → shield-check-CrD-s89i.js} +1 -1
  180. package/ui/dist/assets/{target-CWfn705s.js → target-D4oh8GME.js} +1 -1
  181. package/ui/dist/assets/{terminal-CdhfA0Kr.js → terminal-BvJZ1R3x.js} +1 -1
  182. package/ui/dist/assets/{toggle-right-CmYQLQRS.js → toggle-right-Dl7x_ed7.js} +1 -1
  183. package/ui/dist/assets/{trash-2-TQcEJEv4.js → trash-2-lPcFwnW5.js} +1 -1
  184. package/ui/dist/assets/{trending-up-Cw22bM4J.js → trending-up-DqUbZfDe.js} +1 -1
  185. package/ui/dist/assets/{trophy-DUF8Bcas.js → trophy-Dv6zFfKM.js} +1 -1
  186. package/ui/dist/assets/{users-BX_ZaByZ.js → users-NPyAWbs5.js} +1 -1
  187. package/ui/dist/assets/{wrench-Cfp7nYhG.js → wrench-BCKgeHj3.js} +1 -1
  188. package/ui/dist/index.html +2 -2
  189. package/ui/dist/sw.js +1 -1
  190. package/ui/dist/assets/BackupPanel-BNxMlNIP.js +0 -1
  191. package/ui/dist/assets/CPActivity-CjIgehOq.js +0 -1
  192. package/ui/dist/assets/CPAgentDetail-oaymYRNI.js +0 -1
  193. package/ui/dist/assets/CPAgents-CWQ6iJfO.js +0 -1
  194. package/ui/dist/assets/CPApprovals-DzATBhtM.js +0 -1
  195. package/ui/dist/assets/CPCosts-xVQR148_.js +0 -1
  196. package/ui/dist/assets/CPDashboard-Dt6Jr7Zw.js +0 -1
  197. package/ui/dist/assets/CPGoals-Bt1a3C9T.js +0 -1
  198. package/ui/dist/assets/CPIssueDetail-DHxqtiuh.js +0 -1
  199. package/ui/dist/assets/CPIssues-D0l3fgUs.js +0 -1
  200. package/ui/dist/assets/CPOrg-DQ3tbYld.js +0 -8
  201. package/ui/dist/assets/CPRuns-0vncicUW.js +0 -1
  202. package/ui/dist/assets/ChannelsPanel-CiJs4gyw.js +0 -1
  203. package/ui/dist/assets/FleetPanel-Bg-f3_ip.js +0 -1
  204. package/ui/dist/assets/InfraView-CHYaZqMK.js +0 -2
  205. package/ui/dist/assets/InlineEditableField-BOLRKQq1.js +0 -1
  206. package/ui/dist/assets/Input-4pNffAw-.js +0 -1
  207. package/ui/dist/assets/IntegrationsPanel-CFucvr-Q.js +0 -1
  208. package/ui/dist/assets/IntelligenceView-Dh-Wuf13.js +0 -2
  209. package/ui/dist/assets/LearningPanel-CtlougkF.js +0 -1
  210. package/ui/dist/assets/McpPanel-BobqpLsh.js +0 -1
  211. package/ui/dist/assets/MemoryWikiPanel-BfYksjoI.js +0 -11
  212. package/ui/dist/assets/MissionCanvas-0V_vtqiu.js +0 -50
  213. package/ui/dist/assets/MissionChat-9hGhc9Zw.js +0 -7
  214. package/ui/dist/assets/MissionLibrary-dFkT8pGp.js +0 -5
  215. package/ui/dist/assets/MissionStart-CZSEie0Q.js +0 -1
  216. package/ui/dist/assets/Modal-V2yNnkKk.js +0 -1
  217. package/ui/dist/assets/NvidiaPanel-qLJysI9M.js +0 -1
  218. package/ui/dist/assets/OverviewPanel-Be6LukJ_.js +0 -1
  219. package/ui/dist/assets/RecipesPanel-DDYOCx3w.js +0 -1
  220. package/ui/dist/assets/SelfImprovePanel-B8o_fO30.js +0 -1
  221. package/ui/dist/assets/SessionsPanel-DeCBkSgY.js +0 -1
  222. package/ui/dist/assets/SettingsPanel-BlsRDAt7.js +0 -1
  223. package/ui/dist/assets/SettingsView-Dsa7Zr4e.js +0 -2
  224. package/ui/dist/assets/SkeletonLoader-BkQoZllJ.js +0 -1
  225. package/ui/dist/assets/StatusBadge-BFEHCdgi.js +0 -1
  226. package/ui/dist/assets/Tabs-g2Gs9sK0.js +0 -1
  227. package/ui/dist/assets/TelemetryPanel-DXAGuV0R.js +0 -1
  228. package/ui/dist/assets/TitanCanvas-DCl3gxSl.js +0 -1072
  229. package/ui/dist/assets/ToolsView-CnUjq0Js.js +0 -2
  230. package/ui/dist/assets/Tooltip-DJ99YlFF.js +0 -6
  231. package/ui/dist/assets/TrainingPanel-BLf_KMaE.js +0 -1
  232. package/ui/dist/assets/eye-off-CYR4nH5I.js +0 -6
  233. package/ui/dist/assets/index-PwwKjgT3.css +0 -1
  234. package/ui/dist/assets/index-slWylU2o.js +0 -244
  235. package/ui/dist/assets/loader-circle-E8aLxmMz.js +0 -6
@@ -1,1072 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SomaView-CYukE7Fp.js","assets/index-slWylU2o.js","assets/index-PwwKjgT3.css","assets/Input-4pNffAw-.js","assets/loader-circle-E8aLxmMz.js","assets/Tooltip-DJ99YlFF.js","assets/SomaView-BtCkeWfZ.css","assets/CommandPostHub-CQqRYBjf.js","assets/Modal-V2yNnkKk.js","assets/proxy-BAUTNyg6.js","assets/InlineEditableField-BOLRKQq1.js","assets/check-BcOm5jPO.js","assets/terminal-CdhfA0Kr.js","assets/approvalHeadline-DB9SgR-9.js","assets/chevron-right-aFDDgFsL.js","assets/wrench-Cfp7nYhG.js","assets/pause-CZo33QlA.js","assets/dollar-sign-Dy5-qkg3.js","assets/git-branch-CPZciK10.js","assets/chart-column-wFkjV3Ni.js","assets/clock-BbCCaukN.js","assets/users-BX_ZaByZ.js","assets/target-CWfn705s.js","assets/briefcase-ROIEmiah.js","assets/send-DZ_5M5QQ.js","assets/plus-O61rB_YF.js","assets/trash-2-TQcEJEv4.js","assets/IntelligenceView-Dh-Wuf13.js","assets/MemoryGraphPanel-F1P9COyY.js","assets/network-v9O7MmZT.js","assets/search-C9SdcZJq.js","assets/InfraView-CHYaZqMK.js","assets/ToolsView-CnUjq0Js.js","assets/SettingsView-Dsa7Zr4e.js","assets/SettingsPanel-BlsRDAt7.js","assets/PageHeader-llOXO43Z.js","assets/circle-check-big-DPz64kZW.js","assets/VoiceOverlay-B08Sw918.js","assets/chevron-down-CM11GPpR.js","assets/download-DjheLEns.js","assets/play-DbCJhc5H.js","assets/save-D2Qh8KyN.js","assets/chevron-up-D6g7FB6i.js","assets/rotate-ccw-n5WkWR51.js","assets/folder-DY4eeMdo.js","assets/shield-check-DyP5PmaY.js","assets/external-link-BgxGF7ZQ.js","assets/SecurityPanel-_gqMk8hJ.js","assets/AuditPanel-DrDvXZ9u.js","assets/funnel-LWmcwhj-.js","assets/AutopilotPanel-C3yQBxAp.js","assets/WorkflowsPanel-DdY6E93C.js","assets/toggle-right-CmYQLQRS.js","assets/LearningPanel-CtlougkF.js","assets/lightbulb-tzuCyEQk.js","assets/trending-up-Cw22bM4J.js","assets/SelfImprovePanel-B8o_fO30.js","assets/trophy-DUF8Bcas.js","assets/PersonasPanel-DIac_kZ3.js","assets/PersonaProfilesPanel-CfsQTMra.js","assets/DreamPanel-CO7iSdjn.js","assets/HomelabPanel-DjMUrO2B.js","assets/StatCard-DT4Bx1mY.js","assets/SkeletonLoader-BkQoZllJ.js","assets/NvidiaPanel-qLJysI9M.js","assets/eye-off-CYR4nH5I.js","assets/FilesPanel-dRQM0apb.js","assets/arrow-left-CHJyrO8S.js","assets/LogsPanel-Bs9IsTCH.js","assets/TelemetryPanel-DXAGuV0R.js","assets/SkillsPanel-D08WcRGp.js","assets/McpPanel-BobqpLsh.js","assets/plug-CtpCZg2z.js","assets/IntegrationsPanel-CFucvr-Q.js","assets/ChannelsPanel-CiJs4gyw.js","assets/MeshPanel-CgIAh5ZX.js","assets/DataTable-seaktPzB.js","assets/MemoryWikiPanel-BfYksjoI.js","assets/AutoresearchPanel-BgpR3EcK.js","assets/SelfProposalsPanel-DuA0zsGH.js","assets/OverviewPanel-Be6LukJ_.js","assets/layers-Bn7bgu2Z.js","assets/SessionsPanel-DeCBkSgY.js","assets/WatchView-CaQMDEAy.js","assets/BackupPanel-BNxMlNIP.js","assets/TrainingPanel-BLf_KMaE.js","assets/RecipesPanel-DDYOCx3w.js","assets/VramPanel-CJiic8y4.js","assets/TeamsPanel-DOBe72TK.js","assets/CronPanel-Brmnnu8_.js","assets/CheckpointsPanel-DvKUd2VF.js","assets/OrganismPanel-CNZM3eof.js","assets/FleetPanel-Bg-f3_ip.js","assets/BrowserPanel-BNaKZOnn.js","assets/EvalPanel-CqAwhFQ5.js","assets/legacy-BVPeht6t.js"])))=>i.map(i=>d[i]);
2
- var fl=Object.defineProperty;var pl=(t,e,s)=>e in t?fl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var Be=(t,e,s)=>pl(t,typeof e!="symbol"?e+"":e,s);import{c as Ce,a as Qe,g as gl,r as w,b as me,j as n,s as ml,u as Gi,d as yl,e as bl,X as _s,S as xr,A as gt,C as wr,f as vr,G as qi,R as ie,_ as ae,Z as xl,h as dn,I as ri,i as wl,k as vl,W as _l,M as kl,H as Sl,l as jl,t as An}from"./index-slWylU2o.js";import{C as El}from"./chevron-up-D6g7FB6i.js";import{P as Nl}from"./plus-O61rB_YF.js";import{F as un,M as Yi,U as _r}from"./users-BX_ZaByZ.js";import{W as kr,B as Ki}from"./wrench-Cfp7nYhG.js";import{N as Ji}from"./network-v9O7MmZT.js";import{T as Xi,P as Cl,R as hn}from"./terminal-CdhfA0Kr.js";import{S as fn}from"./save-D2Qh8KyN.js";import{R as Qi}from"./rotate-ccw-n5WkWR51.js";import{S as Zi}from"./search-C9SdcZJq.js";import{S as eo}from"./send-DZ_5M5QQ.js";import{M as to,V as Tl}from"./VoiceOverlay-B08Sw918.js";import{F as so,a as Rl}from"./folder-DY4eeMdo.js";import{C as ds}from"./clock-BbCCaukN.js";import{C as Al}from"./chevron-right-aFDDgFsL.js";import{C as ii}from"./check-BcOm5jPO.js";import{S as Il}from"./shield-check-DyP5PmaY.js";import{E as oi}from"./external-link-BgxGF7ZQ.js";import{L as no}from"./loader-circle-E8aLxmMz.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 Ll=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],ro=Ce("archive",Ll);/**
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 Dl=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],us=Ce("book-open",Dl);/**
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 Ml=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]],mt=Ce("brain",Ml);/**
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 Ol=[["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"}]],Pl=Ce("compass",Ol);/**
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 Wl=[["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"}]],Ul=Ce("database",Wl);/**
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 Bl=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],io=Ce("eye",Bl);/**
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 Fl=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],$l=Ce("gauge",Fl);/**
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 zl=[["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"}]],oo=Ce("git-pull-request",zl);/**
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 Hl=[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}]],Vl=Ce("hexagon",Hl);/**
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 Gl=[["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"}]],ql=Ce("history",Gl);/**
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 Yl=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]],Kl=Ce("house",Yl);/**
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 Jl=[["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"}]],ao=Ce("layout-grid",Jl);/**
63
- * @license lucide-react v0.513.0 - ISC
64
- *
65
- * This source code is licensed under the ISC license.
66
- * See the LICENSE file in the root directory of this source tree.
67
- */const Xl=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],lo=Ce("paperclip",Xl);/**
68
- * @license lucide-react v0.513.0 - ISC
69
- *
70
- * This source code is licensed under the ISC license.
71
- * See the LICENSE file in the root directory of this source tree.
72
- */const Ql=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],ai=Ce("power",Ql);/**
73
- * @license lucide-react v0.513.0 - ISC
74
- *
75
- * This source code is licensed under the ISC license.
76
- * See the LICENSE file in the root directory of this source tree.
77
- */const Zl=[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]],co=Ce("radio",Zl);/**
78
- * @license lucide-react v0.513.0 - ISC
79
- *
80
- * This source code is licensed under the ISC license.
81
- * See the LICENSE file in the root directory of this source tree.
82
- */const ec=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Sr=Ce("server",ec);/**
83
- * @license lucide-react v0.513.0 - ISC
84
- *
85
- * This source code is licensed under the ISC license.
86
- * See the LICENSE file in the root directory of this source tree.
87
- */const tc=[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],jr=Ce("settings",tc);/**
88
- * @license lucide-react v0.513.0 - ISC
89
- *
90
- * This source code is licensed under the ISC license.
91
- * See the LICENSE file in the root directory of this source tree.
92
- */const sc=[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]],uo=Ce("test-tube",sc);/**
93
- * @license lucide-react v0.513.0 - ISC
94
- *
95
- * This source code is licensed under the ISC license.
96
- * See the LICENSE file in the root directory of this source tree.
97
- */const nc=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],rc=Ce("wifi-off",nc),Ue=()=>new Map,er=t=>{const e=Ue();return t.forEach((s,r)=>{e.set(r,s)}),e},ze=(t,e,s)=>{let r=t.get(e);return r===void 0&&t.set(e,r=s()),r},ic=(t,e)=>{const s=[];for(const[r,i]of t)s.push(e(i,r));return s},oc=(t,e)=>{for(const[s,r]of t)if(e(r,s))return!0;return!1},yt=()=>new Set,In=t=>t[t.length-1],ac=(t,e)=>{for(let s=0;s<e.length;s++)t.push(e[s])},at=Array.from,Er=(t,e)=>{for(let s=0;s<t.length;s++)if(!e(t[s],s,t))return!1;return!0},ho=(t,e)=>{for(let s=0;s<t.length;s++)if(e(t[s],s,t))return!0;return!1},lc=(t,e)=>{const s=new Array(t);for(let r=0;r<t;r++)s[r]=e(r,s);return s},pn=Array.isArray;class fo{constructor(){this._observers=Ue()}on(e,s){return ze(this._observers,e,yt).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 at((this._observers.get(e)||Ue()).values()).forEach(r=>r(...s))}destroy(){this._observers=Ue()}}class Nr{constructor(){this._observers=Ue()}on(e,s){ze(this._observers,e,yt).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 at((this._observers.get(e)||Ue()).values()).forEach(r=>r(...s))}destroy(){this._observers=Ue()}}const Ke=Math.floor,Us=Math.abs,cc=Math.log10,Cr=(t,e)=>t<e?t:e,At=(t,e)=>t>e?t:e,po=t=>t!==0?t<0:1/t<0,li=1,ci=2,Ln=4,Dn=8,hs=32,it=64,$e=128,gn=31,tr=63,kt=127,dc=2147483647,Hs=Number.MAX_SAFE_INTEGER,di=Number.MIN_SAFE_INTEGER,uc=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Ke(t)===t),go=String.fromCharCode,hc=t=>t.toLowerCase(),fc=/^\s*/g,pc=t=>t.replace(fc,""),gc=/([A-Z])/g,ui=(t,e)=>pc(t.replace(gc,s=>`${e}${hc(s)}`)),mc=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},fs=typeof TextEncoder<"u"?new TextEncoder:null,yc=t=>fs.encode(t),sr=fs?yc:mc;let as=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});as&&as.decode(new Uint8Array).length===1&&(as=null);const bc=(t,e)=>lc(e,()=>t).join("");class ks{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Ae=()=>new ks,xc=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(xc(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},wc=(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(At(s,e)*2),t.cpos=0)},Te=(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},ps=Te,re=(t,e)=>{for(;e>kt;)Te(t,$e|kt&e),e=Ke(e/128);Te(t,kt&e)},Tr=(t,e)=>{const s=po(e);for(s&&(e=-e),Te(t,(e>tr?$e:0)|(s?it:0)|tr&e),e=Ke(e/64);e>0;)Te(t,(e>kt?$e:0)|kt&e),e=Ke(e/128)},nr=new Uint8Array(3e4),vc=nr.length/3,_c=(t,e)=>{if(e.length<vc){const s=fs.encodeInto(e,nr).written||0;re(t,s);for(let r=0;r<s;r++)Te(t,nr[r])}else Se(t,sr(e))},kc=(t,e)=>{const s=unescape(encodeURIComponent(e)),r=s.length;re(t,r);for(let i=0;i<r;i++)Te(t,s.codePointAt(i))},et=fs&&fs.encodeInto?_c:kc,mn=(t,e)=>{const s=t.cbuf.length,r=t.cpos,i=Cr(s-r,e.length),o=e.length-i;t.cbuf.set(e.subarray(0,i),r),t.cpos+=i,o>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(At(s*2,o)),t.cbuf.set(e.subarray(i)),t.cpos=o)},Se=(t,e)=>{re(t,e.byteLength),mn(t,e)},Rr=(t,e)=>{wc(t,e);const s=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,s},Sc=(t,e)=>Rr(t,4).setFloat32(0,e,!1),jc=(t,e)=>Rr(t,8).setFloat64(0,e,!1),Ec=(t,e)=>Rr(t,8).setBigInt64(0,e,!1),hi=new DataView(new ArrayBuffer(4)),Nc=t=>(hi.setFloat32(0,t),hi.getFloat32(0)===t),Ht=(t,e)=>{switch(typeof e){case"string":Te(t,119),et(t,e);break;case"number":uc(e)&&Us(e)<=dc?(Te(t,125),Tr(t,e)):Nc(e)?(Te(t,124),Sc(t,e)):(Te(t,123),jc(t,e));break;case"bigint":Te(t,122),Ec(t,e);break;case"object":if(e===null)Te(t,126);else if(pn(e)){Te(t,117),re(t,e.length);for(let s=0;s<e.length;s++)Ht(t,e[s])}else if(e instanceof Uint8Array)Te(t,116),Se(t,e);else{Te(t,118);const s=Object.keys(e);re(t,s.length);for(let r=0;r<s.length;r++){const i=s[r];et(t,i),Ht(t,e[i])}}break;case"boolean":Te(t,e?120:121);break;default:Te(t,127)}};class fi extends ks{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&re(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const pi=t=>{t.count>0&&(Tr(t.encoder,t.count===1?t.s:-t.s),t.count>1&&re(t.encoder,t.count-2))};class Bs{constructor(){this.encoder=new ks,this.s=0,this.count=0}write(e){this.s===e?this.count++:(pi(this),this.count=1,this.s=e)}toUint8Array(){return pi(this),ke(this.encoder)}}const gi=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Tr(t.encoder,e),t.count>1&&re(t.encoder,t.count-2)}};class Mn{constructor(){this.encoder=new ks,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(gi(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return gi(this),ke(this.encoder)}}class Cc{constructor(){this.sarr=[],this.s="",this.lensE=new Bs}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 ks;return this.sarr.push(this.s),this.s="",et(e,this.sarr.join("")),mn(e,this.lensE.toUint8Array()),ke(e)}}const He=t=>new Error(t),Xe=()=>{throw He("Method unimplemented")},Je=()=>{throw He("Unexpected case")},mo=He("Unexpected end of array"),yo=He("Integer out of Range");class yn{constructor(e){this.arr=e,this.pos=0}}const nt=t=>new yn(t),Tc=t=>t.pos!==t.arr.length,Rc=(t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s},Re=t=>Rc(t,ce(t)),jt=t=>t.arr[t.pos++],ce=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&kt)*s,s*=128,i<$e)return e;if(e>Hs)throw yo}throw mo},Ar=t=>{let e=t.arr[t.pos++],s=e&tr,r=64;const i=(e&it)>0?-1:1;if((e&$e)===0)return i*s;const o=t.arr.length;for(;t.pos<o;){if(e=t.arr[t.pos++],s=s+(e&kt)*r,r*=128,e<$e)return i*s;if(s>Hs)throw yo}throw mo},Ac=t=>{let e=ce(t);if(e===0)return"";{let s=String.fromCodePoint(jt(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(jt(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))}},Ic=t=>as.decode(Re(t)),ot=as?Ic:Ac,Ir=(t,e)=>{const s=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,s},Lc=t=>Ir(t,4).getFloat32(0,!1),Dc=t=>Ir(t,8).getFloat64(0,!1),Mc=t=>Ir(t,8).getBigInt64(0,!1),Oc=[t=>{},t=>null,Ar,Lc,Dc,Mc,t=>!1,t=>!0,ot,t=>{const e=ce(t),s={};for(let r=0;r<e;r++){const i=ot(t);s[i]=Vt(t)}return s},t=>{const e=ce(t),s=[];for(let r=0;r<e;r++)s.push(Vt(t));return s},Re],Vt=t=>Oc[127-jt(t)](t);class mi extends yn{constructor(e,s){super(e),this.reader=s,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Tc(this)?this.count=ce(this)+1:this.count=-1),this.count--,this.s}}class Fs extends yn{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Ar(this);const e=po(this.s);this.count=1,e&&(this.s=-this.s,this.count=ce(this)+2)}return this.count--,this.s}}class On extends yn{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Ar(this),s=e&1;this.diff=Ke(e/2),this.count=1,s&&(this.count=ce(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Pc{constructor(e){this.decoder=new Fs(e),this.str=ot(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 Wc=crypto.getRandomValues.bind(crypto),Uc=Math.random,bo=()=>Wc(new Uint32Array(1))[0],Bc="10000000-1000-4000-8000"+-1e11,xo=()=>Bc.replace(/[018]/g,t=>(t^bo()&15>>t/4).toString(16)),lt=Date.now,Gt=t=>new Promise(t);Promise.all.bind(Promise);const Fc=t=>Promise.reject(t),Lr=t=>Promise.resolve(t),yi=t=>t===void 0?null:t;class $c{constructor(){this.map=new Map}setItem(e,s){this.map.set(e,s)}getItem(e){return this.map.get(e)}}let wo=new $c,Dr=!0;try{typeof localStorage<"u"&&localStorage&&(wo=localStorage,Dr=!1)}catch{}const vo=wo,zc=t=>Dr||addEventListener("storage",t),Hc=t=>Dr||removeEventListener("storage",t),gs=Symbol("Equality"),_o=(t,e)=>{var s;return t===e||!!((s=t==null?void 0:t[gs])!=null&&s.call(t,e))||!1},Vc=t=>typeof t=="object",Gc=Object.assign,qc=Object.keys,Yc=(t,e)=>{for(const s in t)e(t[s],s)},Vs=t=>qc(t).length,Kc=t=>{for(const e in t)return!1;return!0},Ss=(t,e)=>{for(const s in t)if(!e(t[s],s))return!1;return!0},Mr=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Jc=(t,e)=>t===e||Vs(t)===Vs(e)&&Ss(t,(s,r)=>(s!==void 0||Mr(e,r))&&_o(e[r],s)),Xc=Object.freeze,ko=t=>{for(const e in t){const s=t[e];(typeof s=="object"||typeof s=="function")&&ko(t[e])}return Xc(t)},Or=(t,e,s=0)=>{try{for(;s<t.length;s++)t[s](...e)}finally{s<t.length&&Or(t,e,s+1)}},Qc=()=>{},Zc=t=>t,Ut=(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[gs]!=null)return t[gs](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)||!Ut(t.get(s),e.get(s)))return!1;break}case void 0:case Object:if(Vs(t)!==Vs(e))return!1;for(const s in t)if(!Mr(t,s)||!Ut(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(!Ut(t[s],e[s]))return!1;break;default:return!1}return!0},ed=(t,e)=>e.includes(t);var So={};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]",jo=typeof window<"u"&&typeof document<"u"&&!qt;let Ze;const td=()=>{if(Ze===void 0)if(qt){Ze=Ue();const t=process.argv;let e=null;for(let s=0;s<t.length;s++){const r=t[s];r[0]==="-"?(e!==null&&Ze.set(e,""),e=r):e!==null&&(Ze.set(e,r),e=null)}e!==null&&Ze.set(e,"")}else typeof location=="object"?(Ze=Ue(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,s]=t.split("=");Ze.set(`--${ui(e,"-")}`,s),Ze.set(`-${ui(e,"-")}`,s)}})):Ze=Ue();return Ze},rr=t=>td().has(t),ms=t=>yi(qt?So[t.toUpperCase().replaceAll("-","_")]:vo.getItem(t)),Eo=t=>rr("--"+t)||ms(t)!==null,sd=Eo("production"),nd=qt&&ed(So.FORCE_COLOR,["true","1","2"]),rd=nd||!rr("--no-colors")&&!Eo("no-color")&&(!qt||process.stdout.isTTY)&&(!qt||rr("--color")||ms("COLORTERM")!==null||(ms("TERM")||"").includes("color")),No=t=>new Uint8Array(t),id=(t,e,s)=>new Uint8Array(t,e,s),od=t=>new Uint8Array(t),ad=t=>{let e="";for(let s=0;s<t.byteLength;s++)e+=go(t[s]);return btoa(e)},ld=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),cd=t=>{const e=atob(t),s=No(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s},dd=t=>{const e=Buffer.from(t,"base64");return id(e.buffer,e.byteOffset,e.byteLength)},Co=jo?ad:ld,To=jo?cd:dd,ud=t=>{const e=No(t.byteLength);return e.set(t),e};class hd{constructor(e,s){this.left=e,this.right=s}}const rt=(t,e)=>new hd(t,e),bi=t=>t.next()>=.5,Pn=(t,e,s)=>Ke(t.next()*(s+1-e)+e),Ro=(t,e,s)=>Ke(t.next()*(s+1-e)+e),Pr=(t,e,s)=>Ro(t,e,s),fd=t=>go(Pr(t,97,122)),pd=(t,e=0,s=20)=>{const r=Pr(t,e,s);let i="";for(let o=0;o<r;o++)i+=fd(t);return i},Wn=(t,e)=>e[Pr(t,0,e.length-1)],gd=Symbol("0schema");class md{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(bc(" ",(this._rerrs.length-s)*2)+`${r.path!=null?`[${r.path}] `:""}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(`
98
- `)}}const ir=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[gs]?_o(t,e):pn(t)?Er(t,s=>ho(e,r=>ir(s,r))):Vc(t)?Ss(t,(s,r)=>ir(s,e[r])):!1;class Pe{extends(e){let[s,r]=[this.shape,e.shape];return this.constructor._dilutes&&([r,s]=[s,r]),ir(s,r)}equals(e){return this.constructor===e.constructor&&Ut(this.shape,e.shape)}[gd](){return!0}[gs](e){return this.equals(e)}validate(e){return this.check(e)}check(e,s){Xe()}get nullable(){return Zt(this,_n)}get optional(){return new Lo(this)}cast(e){return xi(e,this),e}expect(e){return xi(e,this),e}}Be(Pe,"_dilutes",!1);class Wr extends Pe{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 je=(t,e=null)=>new Wr(t,e);je(Wr);class Ur extends Pe{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 Le=t=>new Ur(t);je(Ur);class bn extends Pe{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 xn=(...t)=>new bn(t),Ao=je(bn),yd=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Io=t=>{if(Yt.check(t))return[yd(t)];if(Ao.check(t))return t.shape.map(e=>e+"");if($o.check(t))return["[+-]?\\d+.?\\d*"];if(zo.check(t))return[".*"];if(qs.check(t))return t.shape.map(Io).flat(1);Je()};class bd extends Pe{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Io).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}}je(bd);const xd=Symbol("optional");class Lo extends Pe{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[xd](){return!0}}const wd=je(Lo);class vd extends Pe{check(e,s){return s==null||s.extend(null,"never",typeof e),!1}}je(vd);const cn=class cn extends Pe{constructor(e,s=!1){super(),this.shape=e,this._isPartial=s}get partial(){return new cn(this.shape,!0)}check(e,s){return e==null?(s==null||s.extend(null,"object","null"),!1):Ss(this.shape,(r,i)=>{const o=this._isPartial&&!Mr(e,i)||r.check(e[i],s);return!o&&(s==null||s.extend(i.toString(),r.toString(),typeof e[i],"Object property does not match")),o})}};Be(cn,"_dilutes",!0);let Gs=cn;const _d=t=>new Gs(t),kd=je(Gs),Sd=Le(t=>t!=null&&(t.constructor===Object||t.constructor==null));class Do extends Pe{constructor(e,s){super(),this.shape={keys:e,values:s}}check(e,s){return e!=null&&Ss(e,(r,i)=>{const o=this.shape.keys.check(i,s);return!o&&(s==null||s.extend(i+"","Record",typeof e,o?"Key doesn't match schema":"Value doesn't match value")),o&&this.shape.values.check(r,s)})}}const Mo=(t,e)=>new Do(t,e),jd=je(Do);class Oo extends Pe{constructor(e){super(),this.shape=e}check(e,s){return e!=null&&Ss(this.shape,(r,i)=>{const o=r.check(e[i],s);return!o&&(s==null||s.extend(i.toString(),"Tuple",typeof r)),o})}}const Ed=(...t)=>new Oo(t);je(Oo);class Po extends Pe{constructor(e){super(),this.shape=e.length===1?e[0]:new wn(e)}check(e,s){const r=pn(e)&&Er(e,i=>this.shape.check(i));return!r&&(s==null||s.extend(null,"Array","")),r}}const Wo=(...t)=>new Po(t),Nd=je(Po),Cd=Le(t=>pn(t));class Uo extends Pe{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 Td=(t,e=null)=>new Uo(t,e);je(Uo);const Rd=Td(Pe);class Ad extends Pe{constructor(e){super(),this.len=e.length-1,this.args=Ed(...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 Id=je(Ad),Ld=Le(t=>typeof t=="function");class Dd extends Pe{constructor(e){super(),this.shape=e}check(e,s){const r=Er(this.shape,i=>i.check(e,s));return!r&&(s==null||s.extend(null,"Intersectinon",typeof e)),r}}je(Dd,t=>t.shape.length>0);class wn extends Pe{constructor(e){super(),this.shape=e}check(e,s){const r=ho(this.shape,i=>i.check(e,s));return s==null||s.extend(null,"Union",typeof e),r}}Be(wn,"_dilutes",!0);const Zt=(...t)=>t.findIndex(e=>qs.check(e))>=0?Zt(...t.map(e=>ys(e)).map(e=>qs.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new wn(t),qs=je(wn),Bo=()=>!0,Ys=Le(Bo),Md=je(Ur,t=>t.shape===Bo),Br=Le(t=>typeof t=="bigint"),Od=Le(t=>t===Br),Fo=Le(t=>typeof t=="symbol");Le(t=>t===Fo);const Bt=Le(t=>typeof t=="number"),$o=Le(t=>t===Bt),Yt=Le(t=>typeof t=="string"),zo=Le(t=>t===Yt),vn=Le(t=>typeof t=="boolean"),Pd=Le(t=>t===vn),Ho=xn(void 0);je(bn,t=>t.shape.length===1&&t.shape[0]===void 0);xn(void 0);const _n=xn(null),Wd=je(bn,t=>t.shape.length===1&&t.shape[0]===null);je(Uint8Array);je(Wr,t=>t.shape===Uint8Array);const Ud=Zt(Bt,Yt,_n,Ho,Br,vn,Fo);(()=>{const t=Wo(Ys),e=Mo(Yt,Ys),s=Zt(Bt,Yt,_n,vn,t,e);return t.shape=s,e.shape.values=s,s})();const ys=t=>{if(Rd.check(t))return t;if(Sd.check(t)){const e={};for(const s in t)e[s]=ys(t[s]);return _d(e)}else{if(Cd.check(t))return Zt(...t.map(ys));if(Ud.check(t))return xn(t);if(Ld.check(t))return je(t)}Je()},xi=sd?()=>{}:(t,e)=>{const s=new md;if(!e.check(t,s))throw He(`Expected value to be of type ${e.constructor.name}.
99
- ${s.toString()}`)};class Bd{constructor(e){this.patterns=[],this.$state=e}if(e,s){return this.patterns.push({if:ys(e),h:s}),this}else(e){return this.if(Ys,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 He("Unhandled pattern")}}}const Fd=t=>new Bd(t),Vo=Fd(Ys).if($o,(t,e)=>Pn(e,di,Hs)).if(zo,(t,e)=>pd(e)).if(Pd,(t,e)=>bi(e)).if(Od,(t,e)=>BigInt(Pn(e,di,Hs))).if(qs,(t,e)=>Pt(e,Wn(e,t.shape))).if(kd,(t,e)=>{const s={};for(const r in t.shape){let i=t.shape[r];if(wd.check(i)){if(bi(e))continue;i=i.shape}s[r]=Vo(i,e)}return s}).if(Nd,(t,e)=>{const s=[],r=Ro(e,0,42);for(let i=0;i<r;i++)s.push(Pt(e,t.shape));return s}).if(Ao,(t,e)=>Wn(e,t.shape)).if(Wd,(t,e)=>null).if(Id,(t,e)=>{const s=Pt(e,t.res);return()=>s}).if(Md,(t,e)=>Pt(e,Wn(e,[Bt,Yt,_n,Ho,Br,vn,Wo(Bt),Mo(Zt("a","b","c"),Bt)]))).if(jd,(t,e)=>{const s={},r=Pn(e,0,3);for(let i=0;i<r;i++){const o=Pt(e,t.shape.keys),c=Pt(e,t.shape.values);s[o]=c}return s}).done(),Pt=(t,e)=>Vo(ys(e),t),kn=typeof document<"u"?document:{};Le(t=>t.nodeType===Gd);typeof DOMParser<"u"&&new DOMParser;Le(t=>t.nodeType===zd);Le(t=>t.nodeType===Hd);const $d=t=>ic(t,(e,s)=>`${s}:${e};`).join(""),zd=kn.ELEMENT_NODE,Hd=kn.TEXT_NODE,Vd=kn.DOCUMENT_NODE,Gd=kn.DOCUMENT_FRAGMENT_NODE;Le(t=>t.nodeType===Vd);const qd=JSON.stringify,dt=Symbol,Ye=dt(),Et=dt(),Go=dt(),Fr=dt(),qo=dt(),Yo=dt(),Ko=dt(),Sn=dt(),jn=dt(),Yd=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 o=t[r];if(o===void 0)break;if(o.constructor===String||o.constructor===Number)e.push(o);else if(o.constructor===Object)break}for(r>0&&s.push(e.join(""));r<t.length;r++){const o=t[r];o instanceof Symbol||s.push(o)}return s},wi=[qo,Ko,Sn,Go];let Un=0,vi=lt();const Kd=(t,e)=>{const s=wi[Un],r=ms("log"),i=r!==null&&(r==="*"||r==="true"||new RegExp(r,"gi").test(e));return Un=(Un+1)%wi.length,e+=": ",i?(...o)=>{var d;o.length===1&&((d=o[0])==null?void 0:d.constructor)===Function&&(o=o[0]());const c=lt(),l=c-vi;vi=c,t(s,e,jn,...o.map(p=>{switch(p!=null&&p.constructor===Uint8Array&&(p=Array.from(p)),typeof p){case"string":case"symbol":return p;default:return qd(p)}}),s," +"+l+"ms")}:Qc},Jd={[Ye]:rt("font-weight","bold"),[Et]:rt("font-weight","normal"),[Go]:rt("color","blue"),[qo]:rt("color","green"),[Fr]:rt("color","grey"),[Yo]:rt("color","red"),[Ko]:rt("color","purple"),[Sn]:rt("color","orange"),[jn]:rt("color","black")},Xd=t=>{var c;t.length===1&&((c=t[0])==null?void 0:c.constructor)===Function&&(t=t[0]());const e=[],s=[],r=Ue();let i=[],o=0;for(;o<t.length;o++){const l=t[o],d=Jd[l];if(d!==void 0)r.set(d.left,d.right);else{if(l===void 0)break;if(l.constructor===String||l.constructor===Number){const p=$d(r);o>0||p.length>0?(e.push("%c"+l),s.push(p)):e.push(l)}else break}}for(o>0&&(i=s,i.unshift(e.join("")));o<t.length;o++){const l=t[o];l instanceof Symbol||i.push(l)}return i},Jo=rd?Xd:Yd,Xo=(...t)=>{console.log(...Jo(t)),Qo.forEach(e=>e.print(t))},Qd=(...t)=>{console.warn(...Jo(t)),t.unshift(Sn),Qo.forEach(e=>e.print(t))},Qo=yt(),Zd=t=>Kd(Xo,t),Zo=t=>({[Symbol.iterator](){return this},next:t}),eu=(t,e)=>Zo(()=>{let s;do s=t.next();while(!s.done&&!e(s.value));return s}),Bn=(t,e)=>Zo(()=>{const{done:s,value:r}=t.next();return{done:s,value:s?void 0:e(r)}});class En{constructor(e,s){this.clock=e,this.len=s}}class js{constructor(){this.clients=new Map}}const ea=(t,e,s)=>e.clients.forEach((r,i)=>{const o=t.doc.store.clients.get(i);if(o!=null){const c=o[o.length-1],l=c.id.clock+c.length;for(let d=0,p=r[d];d<r.length&&p.clock<l;p=r[++d])pa(t,o,p.clock,p.len,s)}}),tu=(t,e)=>{let s=0,r=t.length-1;for(;s<=r;){const i=Ke((s+r)/2),o=t[i],c=o.clock;if(c<=e){if(e<c+o.len)return i;s=i+1}else r=i-1}return null},ta=(t,e)=>{const s=t.clients.get(e.client);return s!==void 0&&tu(s,e.clock)!==null},$r=t=>{t.clients.forEach(e=>{e.sort((i,o)=>i.clock-o.clock);let s,r;for(s=1,r=1;s<e.length;s++){const i=e[r-1],o=e[s];i.clock+i.len>=o.clock?e[r-1]=new En(i.clock,At(i.len,o.clock+o.len-i.clock)):(r<s&&(e[r]=o),r++)}e.length=r})},su=t=>{const e=new js;for(let s=0;s<t.length;s++)t[s].clients.forEach((r,i)=>{if(!e.clients.has(i)){const o=r.slice();for(let c=s+1;c<t.length;c++)ac(o,t[c].clients.get(i)||[]);e.clients.set(i,o)}});return $r(e),e},Ks=(t,e,s,r)=>{ze(t.clients,e,()=>[]).push(new En(s,r))},nu=()=>new js,ru=t=>{const e=nu();return t.clients.forEach((s,r)=>{const i=[];for(let o=0;o<s.length;o++){const c=s[o];if(c.deleted){const l=c.id.clock;let d=c.length;if(o+1<s.length)for(let p=s[o+1];o+1<s.length&&p.deleted;p=s[++o+1])d+=p.length;i.push(new En(l,d))}}i.length>0&&e.clients.set(r,i)}),e},es=(t,e)=>{re(t.restEncoder,e.clients.size),at(e.clients.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{t.resetDsCurVal(),re(t.restEncoder,s);const i=r.length;re(t.restEncoder,i);for(let o=0;o<i;o++){const c=r[o];t.writeDsClock(c.clock),t.writeDsLen(c.len)}})},zr=t=>{const e=new js,s=ce(t.restDecoder);for(let r=0;r<s;r++){t.resetDsCurVal();const i=ce(t.restDecoder),o=ce(t.restDecoder);if(o>0){const c=ze(e.clients,i,()=>[]);for(let l=0;l<o;l++)c.push(new En(t.readDsClock(),t.readDsLen()))}}return e},_i=(t,e,s)=>{const r=new js,i=ce(t.restDecoder);for(let o=0;o<i;o++){t.resetDsCurVal();const c=ce(t.restDecoder),l=ce(t.restDecoder),d=s.clients.get(c)||[],p=Ie(s,c);for(let m=0;m<l;m++){const u=t.readDsClock(),f=u+t.readDsLen();if(u<p){p<f&&Ks(r,c,p,f-p);let x=tt(d,u),b=d[x];for(!b.deleted&&b.id.clock<u&&(d.splice(x+1,0,sn(e,b,u-b.id.clock)),x++);x<d.length&&(b=d[x++],b.id.clock<f);)b.deleted||(f<b.id.clock+b.length&&d.splice(x,0,sn(e,b,f-b.id.clock)),b.delete(e))}else Ks(r,c,u,f-u)}}if(r.clients.size>0){const o=new Nt;return re(o.restEncoder,0),es(o,r),o.toUint8Array()}return null},sa=bo;class ts extends fo{constructor({guid:e=xo(),collectionid:s=null,gc:r=!0,gcFilter:i=()=>!0,meta:o=null,autoLoad:c=!1,shouldLoad:l=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=sa(),this.guid=e,this.collectionid=s,this.share=new Map,this.store=new ha,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=c,this.meta=o,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Gt(p=>{this.on("load",()=>{this.isLoaded=!0,p(this)})});const d=()=>Gt(p=>{const m=u=>{(u===void 0||u===!0)&&(this.off("sync",m),p())};this.on("sync",m)});this.on("sync",p=>{p===!1&&this.isSynced&&(this.whenSynced=d()),this.isSynced=p===void 0||p===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=d()}load(){const e=this._item;e!==null&&!this.shouldLoad&&be(e.parent.doc,s=>{s.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(at(this.subdocs).map(e=>e.guid))}transact(e,s=null){return be(this,e,s)}get(e,s=Me){const r=ze(this.share,e,()=>{const o=new s;return o._integrate(this,null),o}),i=r.constructor;if(s!==Me&&i!==s)if(i===Me){const o=new s;o._map=r._map,r._map.forEach(c=>{for(;c!==null;c=c.left)c.parent=o}),o._start=r._start;for(let c=o._start;c!==null;c=c.right)c.parent=o;return o._length=r._length,this.share.set(e,o),o._integrate(this,null),o}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,$t)}getText(e=""){return this.get(e,Jt)}getMap(e=""){return this.get(e,Ct)}getXmlElement(e=""){return this.get(e,Xt)}getXmlFragment(e=""){return this.get(e,Tt)}toJSON(){const e={};return this.share.forEach((s,r)=>{e[r]=s.toJSON()}),e}destroy(){this.isDestroyed=!0,at(this.subdocs).forEach(s=>s.destroy());const e=this._item;if(e!==null){this._item=null;const s=e.content;s.doc=new ts({guid:this.guid,...s.opts,shouldLoad:!1}),s.doc._item=e,be(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 na{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return ce(this.restDecoder)}readDsLen(){return ce(this.restDecoder)}}class ra extends na{readLeftID(){return pe(ce(this.restDecoder),ce(this.restDecoder))}readRightID(){return pe(ce(this.restDecoder),ce(this.restDecoder))}readClient(){return ce(this.restDecoder)}readInfo(){return jt(this.restDecoder)}readString(){return ot(this.restDecoder)}readParentInfo(){return ce(this.restDecoder)===1}readTypeRef(){return ce(this.restDecoder)}readLen(){return ce(this.restDecoder)}readAny(){return Vt(this.restDecoder)}readBuf(){return ud(Re(this.restDecoder))}readJSON(){return JSON.parse(ot(this.restDecoder))}readKey(){return ot(this.restDecoder)}}class iu{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=ce(this.restDecoder),this.dsCurrVal}readDsLen(){const e=ce(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Kt extends iu{constructor(e){super(e),this.keys=[],ce(e),this.keyClockDecoder=new On(Re(e)),this.clientDecoder=new Fs(Re(e)),this.leftClockDecoder=new On(Re(e)),this.rightClockDecoder=new On(Re(e)),this.infoDecoder=new mi(Re(e),jt),this.stringDecoder=new Pc(Re(e)),this.parentInfoDecoder=new mi(Re(e),jt),this.typeRefDecoder=new Fs(Re(e)),this.lenDecoder=new Fs(Re(e))}readLeftID(){return new Ft(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Ft(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 Vt(this.restDecoder)}readBuf(){return Re(this.restDecoder)}readJSON(){return Vt(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 ia{constructor(){this.restEncoder=Ae()}toUint8Array(){return ke(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){re(this.restEncoder,e)}writeDsLen(e){re(this.restEncoder,e)}}class Es extends ia{writeLeftID(e){re(this.restEncoder,e.client),re(this.restEncoder,e.clock)}writeRightID(e){re(this.restEncoder,e.client),re(this.restEncoder,e.clock)}writeClient(e){re(this.restEncoder,e)}writeInfo(e){ps(this.restEncoder,e)}writeString(e){et(this.restEncoder,e)}writeParentInfo(e){re(this.restEncoder,e?1:0)}writeTypeRef(e){re(this.restEncoder,e)}writeLen(e){re(this.restEncoder,e)}writeAny(e){Ht(this.restEncoder,e)}writeBuf(e){Se(this.restEncoder,e)}writeJSON(e){et(this.restEncoder,JSON.stringify(e))}writeKey(e){et(this.restEncoder,e)}}class oa{constructor(){this.restEncoder=Ae(),this.dsCurrVal=0}toUint8Array(){return ke(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const s=e-this.dsCurrVal;this.dsCurrVal=e,re(this.restEncoder,s)}writeDsLen(e){e===0&&Je(),re(this.restEncoder,e-1),this.dsCurrVal+=e}}class Nt extends oa{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Mn,this.clientEncoder=new Bs,this.leftClockEncoder=new Mn,this.rightClockEncoder=new Mn,this.infoEncoder=new fi(ps),this.stringEncoder=new Cc,this.parentInfoEncoder=new fi(ps),this.typeRefEncoder=new Bs,this.lenEncoder=new Bs}toUint8Array(){const e=Ae();return re(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()),mn(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){Ht(this.restEncoder,e)}writeBuf(e){Se(this.restEncoder,e)}writeJSON(e){Ht(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 ou=(t,e,s,r)=>{r=At(r,e[0].id.clock);const i=tt(e,r);re(t.restEncoder,e.length-i),t.writeClient(s),re(t.restEncoder,r);const o=e[i];o.write(t,r-o.id.clock);for(let c=i+1;c<e.length;c++)e[c].write(t,0)},Hr=(t,e,s)=>{const r=new Map;s.forEach((i,o)=>{Ie(e,o)>i&&r.set(o,i)}),Nn(e).forEach((i,o)=>{s.has(o)||r.set(o,0)}),re(t.restEncoder,r.size),at(r.entries()).sort((i,o)=>o[0]-i[0]).forEach(([i,o])=>{ou(t,e.clients.get(i),i,o)})},au=(t,e)=>{const s=Ue(),r=ce(t.restDecoder);for(let i=0;i<r;i++){const o=ce(t.restDecoder),c=new Array(o),l=t.readClient();let d=ce(t.restDecoder);s.set(l,{i:0,refs:c});for(let p=0;p<o;p++){const m=t.readInfo();switch(gn&m){case 0:{const u=t.readLen();c[p]=new Ge(pe(l,d),u),d+=u;break}case 10:{const u=ce(t.restDecoder);c[p]=new qe(pe(l,d),u),d+=u;break}default:{const u=(m&(it|$e))===0,f=new Ee(pe(l,d),null,(m&$e)===$e?t.readLeftID():null,null,(m&it)===it?t.readRightID():null,u?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,u&&(m&hs)===hs?t.readString():null,La(t,m));c[p]=f,d+=f.length}}}}return s},lu=(t,e,s)=>{const r=[];let i=at(s.keys()).sort((x,b)=>x-b);if(i.length===0)return null;const o=()=>{if(i.length===0)return null;let x=s.get(i[i.length-1]);for(;x.refs.length===x.i;)if(i.pop(),i.length>0)x=s.get(i[i.length-1]);else return null;return x};let c=o();if(c===null)return null;const l=new ha,d=new Map,p=(x,b)=>{const j=d.get(x);(j==null||j>b)&&d.set(x,b)};let m=c.refs[c.i++];const u=new Map,f=()=>{for(const x of r){const b=x.id.client,j=s.get(b);j?(j.i--,l.clients.set(b,j.refs.slice(j.i)),s.delete(b),j.i=0,j.refs=[]):l.clients.set(b,[x]),i=i.filter(A=>A!==b)}r.length=0};for(;;){if(m.constructor!==qe){const b=ze(u,m.id.client,()=>Ie(e,m.id.client))-m.id.clock;if(b<0)r.push(m),p(m.id.client,m.id.clock-1),f();else{const j=m.getMissing(t,e);if(j!==null){r.push(m);const A=s.get(j)||{refs:[],i:0};if(A.refs.length===A.i)p(j,Ie(e,j)),f();else{m=A.refs[A.i++];continue}}else(b===0||b<m.length)&&(m.integrate(t,b),u.set(m.id.client,m.id.clock+m.length))}}if(r.length>0)m=r.pop();else if(c!==null&&c.i<c.refs.length)m=c.refs[c.i++];else{if(c=o(),c===null)break;m=c.refs[c.i++]}}if(l.clients.size>0){const x=new Nt;return Hr(x,l,new Map),re(x.restEncoder,0),{missing:d,update:x.toUint8Array()}}return null},cu=(t,e)=>Hr(t,e.doc.store,e.beforeState),du=(t,e,s,r=new Kt(t))=>be(e,i=>{i.local=!1;let o=!1;const c=i.doc,l=c.store,d=au(r,c),p=lu(i,l,d),m=l.pendingStructs;if(m){for(const[f,x]of m.missing)if(x<Ie(l,f)){o=!0;break}if(p){for(const[f,x]of p.missing){const b=m.missing.get(f);(b==null||b>x)&&m.missing.set(f,x)}m.update=Js([m.update,p.update])}}else l.pendingStructs=p;const u=_i(r,i,l);if(l.pendingDs){const f=new Kt(nt(l.pendingDs));ce(f.restDecoder);const x=_i(f,i,l);u&&x?l.pendingDs=Js([u,x]):l.pendingDs=u||x}else l.pendingDs=u;if(o){const f=l.pendingStructs.update;l.pendingStructs=null,aa(i.doc,f)}},s,!1),aa=(t,e,s,r=Kt)=>{const i=nt(e);du(i,t,s,new r(i))},la=(t,e,s)=>aa(t,e,s,ra),uu=(t,e,s=new Map)=>{Hr(t,e.store,s),es(t,ru(e.store))},hu=(t,e=new Uint8Array([0]),s=new Nt)=>{const r=ca(e);uu(s,t,r);const i=[s.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(Nu(t.store.pendingStructs.update,e)),i.length>1){if(s.constructor===Es)return ju(i.map((o,c)=>c===0?o:Tu(o)));if(s.constructor===Nt)return Js(i)}return i[0]},Vr=(t,e)=>hu(t,e,new Es),fu=t=>{const e=new Map,s=ce(t.restDecoder);for(let r=0;r<s;r++){const i=ce(t.restDecoder),o=ce(t.restDecoder);e.set(i,o)}return e},ca=t=>fu(new na(nt(t))),da=(t,e)=>(re(t.restEncoder,e.size),at(e.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{re(t.restEncoder,s),re(t.restEncoder,r)}),t),pu=(t,e)=>da(t,Nn(e.store)),gu=(t,e=new oa)=>(t instanceof Map?da(e,t):pu(e,t),e.toUint8Array()),mu=t=>gu(t,new ia);class yu{constructor(){this.l=[]}}const ki=()=>new yu,Si=(t,e)=>t.l.push(e),ji=(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.")},ua=(t,e,s)=>Or(t.l,[e,s]);class Ft{constructor(e,s){this.client=e,this.clock=s}}const Ts=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,pe=(t,e)=>new Ft(t,e),bu=t=>{for(const[e,s]of t.doc.share.entries())if(s===t)return e;throw Je()},Wt=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!ta(e.ds,t.id),or=(t,e)=>{const s=ze(t.meta,or,yt),r=t.doc.store;s.has(e)||(e.sv.forEach((i,o)=>{i<Ie(r,o)&&bt(t,pe(o,i))}),ea(t,e.ds,i=>{}),s.add(e))};class ha{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Nn=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},Ie=(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},fa=(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 Je()}s.push(e)},tt=(t,e)=>{let s=0,r=t.length-1,i=t[r],o=i.id.clock;if(o===e)return r;let c=Ke(e/(o+i.length-1)*r);for(;s<=r;){if(i=t[c],o=i.id.clock,o<=e){if(e<o+i.length)return c;s=c+1}else r=c-1;c=Ke((s+r)/2)}throw Je()},xu=(t,e)=>{const s=t.clients.get(e.client);return s[tt(s,e.clock)]},Fn=xu,ar=(t,e,s)=>{const r=tt(e,s),i=e[r];return i.id.clock<s&&i instanceof Ee?(e.splice(r+1,0,sn(t,i,s-i.id.clock)),r+1):r},bt=(t,e)=>{const s=t.doc.store.clients.get(e.client);return s[ar(t,s,e.clock)]},Ei=(t,e,s)=>{const r=e.clients.get(s.client),i=tt(r,s.clock),o=r[i];return s.clock!==o.id.clock+o.length-1&&o.constructor!==Ge&&r.splice(i+1,0,sn(t,o,s.clock-o.id.clock+1)),o},wu=(t,e,s)=>{const r=t.clients.get(e.id.client);r[tt(r,e.id.clock)]=s},pa=(t,e,s,r,i)=>{if(r===0)return;const o=s+r;let c=ar(t,e,s),l;do l=e[c++],o<l.id.clock+l.length&&ar(t,e,o),i(l);while(c<e.length&&e[c].id.clock<o)};class vu{constructor(e,s,r){this.doc=e,this.deleteSet=new js,this.beforeState=Nn(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 Ni=(t,e)=>e.deleteSet.clients.size===0&&!oc(e.afterState,(s,r)=>e.beforeState.get(r)!==s)?!1:($r(e.deleteSet),cu(t,e),es(t,e.deleteSet),!0),Ci=(t,e,s)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&ze(t.changed,e,yt).add(s)},$s=(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 Ee&&s.parentSub!==null&&s.parent._map.get(s.parentSub)===s&&s.parent._map.set(s.parentSub,r);continue}break}const o=e-i;return o&&t.splice(e+1-o,o),o},_u=(t,e,s)=>{for(const[r,i]of t.clients.entries()){const o=e.clients.get(r);for(let c=i.length-1;c>=0;c--){const l=i[c],d=l.clock+l.len;for(let p=tt(o,l.clock),m=o[p];p<o.length&&m.id.clock<d;m=o[++p]){const u=o[p];if(l.clock+l.len<=u.id.clock)break;u instanceof Ee&&u.deleted&&!u.keep&&s(u)&&u.gc(e,!1)}}}},ku=(t,e)=>{t.clients.forEach((s,r)=>{const i=e.clients.get(r);for(let o=s.length-1;o>=0;o--){const c=s[o],l=Cr(i.length-1,1+tt(i,c.clock+c.len-1));for(let d=l,p=i[d];d>0&&p.id.clock>=c.clock;p=i[d])d-=1+$s(i,d)}})},ga=(t,e)=>{if(e<t.length){const s=t[e],r=s.doc,i=r.store,o=s.deleteSet,c=s._mergeStructs;try{$r(o),s.afterState=Nn(s.doc.store),r.emit("beforeObserverCalls",[s,r]);const l=[];s.changed.forEach((d,p)=>l.push(()=>{(p._item===null||!p._item.deleted)&&p._callObserver(s,d)})),l.push(()=>{s.changedParentTypes.forEach((d,p)=>{p._dEH.l.length>0&&(p._item===null||!p._item.deleted)&&(d=d.filter(m=>m.target._item===null||!m.target._item.deleted),d.forEach(m=>{m.currentTarget=p,m._path=null}),d.sort((m,u)=>m.path.length-u.path.length),l.push(()=>{ua(p._dEH,d,s)}))}),l.push(()=>r.emit("afterTransaction",[s,r])),l.push(()=>{s._needFormattingCleanup&&zu(s)})}),Or(l,[])}finally{r.gc&&_u(o,i,r.gcFilter),ku(o,i),s.afterState.forEach((m,u)=>{const f=s.beforeState.get(u)||0;if(f!==m){const x=i.clients.get(u),b=At(tt(x,f),1);for(let j=x.length-1;j>=b;)j-=1+$s(x,j)}});for(let m=c.length-1;m>=0;m--){const{client:u,clock:f}=c[m].id,x=i.clients.get(u),b=tt(x,f);b+1<x.length&&$s(x,b+1)>1||b>0&&$s(x,b)}if(!s.local&&s.afterState.get(r.clientID)!==s.beforeState.get(r.clientID)&&(Xo(Sn,Ye,"[yjs] ",Et,Yo,"Changed the client-id because another client seems to be using it."),r.clientID=sa()),r.emit("afterTransactionCleanup",[s,r]),r._observers.has("update")){const m=new Es;Ni(m,s)&&r.emit("update",[m.toUint8Array(),s.origin,r,s])}if(r._observers.has("updateV2")){const m=new Nt;Ni(m,s)&&r.emit("updateV2",[m.toUint8Array(),s.origin,r,s])}const{subdocsAdded:l,subdocsLoaded:d,subdocsRemoved:p}=s;(l.size>0||p.size>0||d.size>0)&&(l.forEach(m=>{m.clientID=r.clientID,m.collectionid==null&&(m.collectionid=r.collectionid),r.subdocs.add(m)}),p.forEach(m=>r.subdocs.delete(m)),r.emit("subdocs",[{loaded:d,added:l,removed:p},r,s]),p.forEach(m=>m.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):ga(t,e+1)}}},be=(t,e,s=null,r=!0)=>{const i=t._transactionCleanups;let o=!1,c=null;t._transaction===null&&(o=!0,t._transaction=new vu(t,s,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{c=e(t._transaction)}finally{if(o){const l=t._transaction===i[0];t._transaction=null,l&&ga(i,0)}}return c};function*Su(t){const e=ce(t.restDecoder);for(let s=0;s<e;s++){const r=ce(t.restDecoder),i=t.readClient();let o=ce(t.restDecoder);for(let c=0;c<r;c++){const l=t.readInfo();if(l===10){const d=ce(t.restDecoder);yield new qe(pe(i,o),d),o+=d}else if((gn&l)!==0){const d=(l&(it|$e))===0,p=new Ee(pe(i,o),null,(l&$e)===$e?t.readLeftID():null,null,(l&it)===it?t.readRightID():null,d?t.readParentInfo()?t.readString():t.readLeftID():null,d&&(l&hs)===hs?t.readString():null,La(t,l));yield p,o+=p.length}else{const d=t.readLen();yield new Ge(pe(i,o),d),o+=d}}}}class Gr{constructor(e,s){this.gen=Su(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 qr{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const ju=t=>Js(t,ra,Es),Eu=(t,e)=>{if(t.constructor===Ge){const{client:s,clock:r}=t.id;return new Ge(pe(s,r+e),t.length-e)}else if(t.constructor===qe){const{client:s,clock:r}=t.id;return new qe(pe(s,r+e),t.length-e)}else{const s=t,{client:r,clock:i}=s.id;return new Ee(pe(r,i+e),null,pe(r,i+e-1),null,s.rightOrigin,s.parent,s.parentSub,s.content.splice(e))}},Js=(t,e=Kt,s=Nt)=>{if(t.length===1)return t[0];const r=t.map(m=>new e(nt(m)));let i=r.map(m=>new Gr(m,!0)),o=null;const c=new s,l=new qr(c);for(;i=i.filter(f=>f.curr!==null),i.sort((f,x)=>{if(f.curr.id.client===x.curr.id.client){const b=f.curr.id.clock-x.curr.id.clock;return b===0?f.curr.constructor===x.curr.constructor?0:f.curr.constructor===qe?1:-1:b}else return x.curr.id.client-f.curr.id.client}),i.length!==0;){const m=i[0],u=m.curr.id.client;if(o!==null){let f=m.curr,x=!1;for(;f!==null&&f.id.clock+f.length<=o.struct.id.clock+o.struct.length&&f.id.client>=o.struct.id.client;)f=m.next(),x=!0;if(f===null||f.id.client!==u||x&&f.id.clock>o.struct.id.clock+o.struct.length)continue;if(u!==o.struct.id.client)ft(l,o.struct,o.offset),o={struct:f,offset:0},m.next();else if(o.struct.id.clock+o.struct.length<f.id.clock)if(o.struct.constructor===qe)o.struct.length=f.id.clock+f.length-o.struct.id.clock;else{ft(l,o.struct,o.offset);const b=f.id.clock-o.struct.id.clock-o.struct.length;o={struct:new qe(pe(u,o.struct.id.clock+o.struct.length),b),offset:0}}else{const b=o.struct.id.clock+o.struct.length-f.id.clock;b>0&&(o.struct.constructor===qe?o.struct.length-=b:f=Eu(f,b)),o.struct.mergeWith(f)||(ft(l,o.struct,o.offset),o={struct:f,offset:0},m.next())}}else o={struct:m.curr,offset:0},m.next();for(let f=m.curr;f!==null&&f.id.client===u&&f.id.clock===o.struct.id.clock+o.struct.length&&f.constructor!==qe;f=m.next())ft(l,o.struct,o.offset),o={struct:f,offset:0}}o!==null&&(ft(l,o.struct,o.offset),o=null),Yr(l);const d=r.map(m=>zr(m)),p=su(d);return es(c,p),c.toUint8Array()},Nu=(t,e,s=Kt,r=Nt)=>{const i=ca(e),o=new r,c=new qr(o),l=new s(nt(t)),d=new Gr(l,!1);for(;d.curr;){const m=d.curr,u=m.id.client,f=i.get(u)||0;if(d.curr.constructor===qe){d.next();continue}if(m.id.clock+m.length>f)for(ft(c,m,At(f-m.id.clock,0)),d.next();d.curr&&d.curr.id.client===u;)ft(c,d.curr,0),d.next();else for(;d.curr&&d.curr.id.client===u&&d.curr.id.clock+d.curr.length<=f;)d.next()}Yr(c);const p=zr(l);return es(o,p),o.toUint8Array()},ma=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:ke(t.encoder.restEncoder)}),t.encoder.restEncoder=Ae(),t.written=0)},ft=(t,e,s)=>{t.written>0&&t.currClient!==e.id.client&&ma(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),re(t.encoder.restEncoder,e.id.clock+s)),e.write(t.encoder,s),t.written++},Yr=t=>{ma(t);const e=t.encoder.restEncoder;re(e,t.clientStructs.length);for(let s=0;s<t.clientStructs.length;s++){const r=t.clientStructs[s];re(e,r.written),mn(e,r.restEncoder)}},Cu=(t,e,s,r)=>{const i=new s(nt(t)),o=new Gr(i,!1),c=new r,l=new qr(c);for(let p=o.curr;p!==null;p=o.next())ft(l,e(p),0);Yr(l);const d=zr(i);return es(c,d),c.toUint8Array()},Tu=t=>Cu(t,Zc,Kt,Es),Ti="You must not compute changes after the event-handler fired.";class Cn{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=Ru(this.currentTarget,this.target))}deletes(e){return ta(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw He(Ti);const e=new Map,s=this.target;this.transaction.changed.get(s).forEach(i=>{if(i!==null){const o=s._map.get(i);let c,l;if(this.adds(o)){let d=o.left;for(;d!==null&&this.adds(d);)d=d.left;if(this.deletes(o))if(d!==null&&this.deletes(d))c="delete",l=In(d.content.getContent());else return;else d!==null&&this.deletes(d)?(c="update",l=In(d.content.getContent())):(c="add",l=void 0)}else if(this.deletes(o))c="delete",l=In(o.content.getContent());else return;e.set(i,{action:c,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 He(Ti);const s=this.target,r=yt(),i=yt(),o=[];if(e={added:r,deleted:i,delta:o,keys:this.keys},this.transaction.changed.get(s).has(null)){let l=null;const d=()=>{l&&o.push(l)};for(let p=s._start;p!==null;p=p.right)p.deleted?this.deletes(p)&&!this.adds(p)&&((l===null||l.delete===void 0)&&(d(),l={delete:0}),l.delete+=p.length,i.add(p)):this.adds(p)?((l===null||l.insert===void 0)&&(d(),l={insert:[]}),l.insert=l.insert.concat(p.content.getContent()),r.add(p)):((l===null||l.retain===void 0)&&(d(),l={retain:0}),l.retain+=p.length);l!==null&&l.retain===void 0&&d()}this._changes=e}return e}}const Ru=(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},Oe=()=>{Qd("Invalid access: Add Yjs type to a document before reading data.")},ya=80;let Kr=0;class Au{constructor(e,s){e.marker=!0,this.p=e,this.index=s,this.timestamp=Kr++}}const Iu=t=>{t.timestamp=Kr++},ba=(t,e,s)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=s,t.timestamp=Kr++},Lu=(t,e,s)=>{if(t.length>=ya){const r=t.reduce((i,o)=>i.timestamp<o.timestamp?i:o);return ba(r,e,s),r}else{const r=new Au(e,s);return t.push(r),r}},Tn=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const s=t._searchMarker.length===0?null:t._searchMarker.reduce((o,c)=>Us(e-o.index)<Us(e-c.index)?o:c);let r=t._start,i=0;for(s!==null&&(r=s.p,i=s.index,Iu(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&&Us(s.index-i)<r.parent.length/ya?(ba(s,r,i),s):Lu(t._searchMarker,r,i)},bs=(t,e,s)=>{for(let r=t.length-1;r>=0;r--){const i=t[r];if(s>0){let o=i.p;for(o.marker=!1;o&&(o.deleted||!o.countable);)o=o.left,o&&!o.deleted&&o.countable&&(i.index-=o.length);if(o===null||o.marker===!0){t.splice(r,1);continue}i.p=o,o.marker=!0}(e<i.index||s>0&&e===i.index)&&(i.index=At(e,i.index+s))}},Rn=(t,e,s)=>{const r=t,i=e.changedParentTypes;for(;ze(i,t,()=>[]).push(s),t._item!==null;)t=t._item.parent;ua(r._eH,s,e)};class Me{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ki(),this._dEH=ki(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,s){this.doc=e,this._item=s}_copy(){throw Xe()}clone(){throw Xe()}_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){Si(this._eH,e)}observeDeep(e){Si(this._dEH,e)}unobserve(e){ji(this._eH,e)}unobserveDeep(e){ji(this._dEH,e)}toJSON(){}}const xa=(t,e,s)=>{t.doc??Oe(),e<0&&(e=t._length+e),s<0&&(s=t._length+s);let r=s-e;const i=[];let o=t._start;for(;o!==null&&r>0;){if(o.countable&&!o.deleted){const c=o.content.getContent();if(c.length<=e)e-=c.length;else{for(let l=e;l<c.length&&r>0;l++)i.push(c[l]),r--;e=0}}o=o.right}return i},wa=t=>{t.doc??Oe();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},xs=(t,e)=>{let s=0,r=t._start;for(t.doc??Oe();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let o=0;o<i.length;o++)e(i[o],s++,t)}r=r.right}},va=(t,e)=>{const s=[];return xs(t,(r,i)=>{s.push(e(r,i,t))}),s},Du=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}}}},_a=(t,e)=>{t.doc??Oe();const s=Tn(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}},Xs=(t,e,s,r)=>{let i=s;const o=t.doc,c=o.clientID,l=o.store,d=s===null?e._start:s.right;let p=[];const m=()=>{p.length>0&&(i=new Ee(pe(c,Ie(l,c)),i,i&&i.lastId,d,d&&d.id,e,null,new Rt(p)),i.integrate(t,0),p=[])};r.forEach(u=>{if(u===null)p.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:p.push(u);break;default:switch(m(),u.constructor){case Uint8Array:case ArrayBuffer:i=new Ee(pe(c,Ie(l,c)),i,i&&i.lastId,d,d&&d.id,e,null,new Ns(new Uint8Array(u))),i.integrate(t,0);break;case ts:i=new Ee(pe(c,Ie(l,c)),i,i&&i.lastId,d,d&&d.id,e,null,new Cs(u)),i.integrate(t,0);break;default:if(u instanceof Me)i=new Ee(pe(c,Ie(l,c)),i,i&&i.lastId,d,d&&d.id,e,null,new ut(u)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),m()},ka=()=>He("Length exceeded!"),Sa=(t,e,s,r)=>{if(s>e._length)throw ka();if(s===0)return e._searchMarker&&bs(e._searchMarker,s,r.length),Xs(t,e,null,r);const i=s,o=Tn(e,s);let c=e._start;for(o!==null&&(c=o.p,s-=o.index,s===0&&(c=c.prev,s+=c&&c.countable&&!c.deleted?c.length:0));c!==null;c=c.right)if(!c.deleted&&c.countable){if(s<=c.length){s<c.length&&bt(t,pe(c.id.client,c.id.clock+s));break}s-=c.length}return e._searchMarker&&bs(e._searchMarker,i,r.length),Xs(t,e,c,r)},Mu=(t,e,s)=>{let i=(e._searchMarker||[]).reduce((o,c)=>c.index>o.index?c:o,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return Xs(t,e,i,s)},ja=(t,e,s,r)=>{if(r===0)return;const i=s,o=r,c=Tn(e,s);let l=e._start;for(c!==null&&(l=c.p,s-=c.index);l!==null&&s>0;l=l.right)!l.deleted&&l.countable&&(s<l.length&&bt(t,pe(l.id.client,l.id.clock+s)),s-=l.length);for(;r>0&&l!==null;)l.deleted||(r<l.length&&bt(t,pe(l.id.client,l.id.clock+r)),l.delete(t),r-=l.length),l=l.right;if(r>0)throw ka();e._searchMarker&&bs(e._searchMarker,i,-o+r)},Qs=(t,e,s)=>{const r=e._map.get(s);r!==void 0&&r.delete(t)},Jr=(t,e,s,r)=>{const i=e._map.get(s)||null,o=t.doc,c=o.clientID;let l;if(r==null)l=new Rt([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Rt([r]);break;case Uint8Array:l=new Ns(r);break;case ts:l=new Cs(r);break;default:if(r instanceof Me)l=new ut(r);else throw new Error("Unexpected content type")}new Ee(pe(c,Ie(o.store,c)),i,i&&i.lastId,null,null,e,s,l).integrate(t,0)},Xr=(t,e)=>{t.doc??Oe();const s=t._map.get(e);return s!==void 0&&!s.deleted?s.content.getContent()[s.length-1]:void 0},Ea=t=>{const e={};return t.doc??Oe(),t._map.forEach((s,r)=>{s.deleted||(e[r]=s.content.getContent()[s.length-1])}),e},Na=(t,e)=>{t.doc??Oe();const s=t._map.get(e);return s!==void 0&&!s.deleted},Ou=(t,e)=>{const s={};return t._map.forEach((r,i)=>{let o=r;for(;o!==null&&(!e.sv.has(o.id.client)||o.id.clock>=(e.sv.get(o.id.client)||0));)o=o.left;o!==null&&Wt(o,e)&&(s[i]=o.content.getContent()[o.length-1])}),s},Rs=t=>(t.doc??Oe(),eu(t._map.entries(),e=>!e[1].deleted));class Pu extends Cn{}class $t extends Me{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const s=new $t;return s.push(e),s}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new $t}clone(){const e=new $t;return e.insert(0,this.toArray().map(s=>s instanceof Me?s.clone():s)),e}get length(){return this.doc??Oe(),this._length}_callObserver(e,s){super._callObserver(e,s),Rn(this,e,new Pu(this,e))}insert(e,s){this.doc!==null?be(this.doc,r=>{Sa(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}push(e){this.doc!==null?be(this.doc,s=>{Mu(s,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,s=1){this.doc!==null?be(this.doc,r=>{ja(r,this,e,s)}):this._prelimContent.splice(e,s)}get(e){return _a(this,e)}toArray(){return wa(this)}slice(e=0,s=this.length){return xa(this,e,s)}toJSON(){return this.map(e=>e instanceof Me?e.toJSON():e)}map(e){return va(this,e)}forEach(e){xs(this,e)}[Symbol.iterator](){return Du(this)}_write(e){e.writeTypeRef(lh)}}const Wu=t=>new $t;class Uu extends Cn{constructor(e,s,r){super(e,s),this.keysChanged=r}}class Ct extends Me{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 Ct}clone(){const e=new Ct;return this.forEach((s,r)=>{e.set(r,s instanceof Me?s.clone():s)}),e}_callObserver(e,s){Rn(this,e,new Uu(this,e,s))}toJSON(){this.doc??Oe();const e={};return this._map.forEach((s,r)=>{if(!s.deleted){const i=s.content.getContent()[s.length-1];e[r]=i instanceof Me?i.toJSON():i}}),e}get size(){return[...Rs(this)].length}keys(){return Bn(Rs(this),e=>e[0])}values(){return Bn(Rs(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Bn(Rs(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Oe(),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?be(this.doc,s=>{Qs(s,this,e)}):this._prelimContent.delete(e)}set(e,s){return this.doc!==null?be(this.doc,r=>{Jr(r,this,e,s)}):this._prelimContent.set(e,s),s}get(e){return Xr(this,e)}has(e){return Na(this,e)}clear(){this.doc!==null?be(this.doc,e=>{this.forEach(function(s,r,i){Qs(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(ch)}}const Bu=t=>new Ct,pt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Jc(t,e);class lr{constructor(e,s,r,i){this.left=e,this.right=s,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Je(),this.right.content.constructor){case Ne:this.right.deleted||ss(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 Ri=(t,e,s)=>{for(;e.right!==null&&s>0;){switch(e.right.content.constructor){case Ne:e.right.deleted||ss(e.currentAttributes,e.right.content);break;default:e.right.deleted||(s<e.right.length&&bt(t,pe(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},As=(t,e,s,r)=>{const i=new Map,o=r?Tn(e,s):null;if(o){const c=new lr(o.p.left,o.p,o.index,i);return Ri(t,c,s-o.index)}else{const c=new lr(null,e._start,0,i);return Ri(t,c,s)}},Ca=(t,e,s,r)=>{for(;s.right!==null&&(s.right.deleted===!0||s.right.content.constructor===Ne&&pt(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,o=i.clientID;r.forEach((c,l)=>{const d=s.left,p=s.right,m=new Ee(pe(o,Ie(i.store,o)),d,d&&d.lastId,p,p&&p.id,e,null,new Ne(l,c));m.integrate(t,0),s.right=m,s.forward()})},ss=(t,e)=>{const{key:s,value:r}=e;r===null?t.delete(s):t.set(s,r)},Ta=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Ne&&pt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Ra=(t,e,s,r)=>{const i=t.doc,o=i.clientID,c=new Map;for(const l in r){const d=r[l],p=s.currentAttributes.get(l)??null;if(!pt(p,d)){c.set(l,p);const{left:m,right:u}=s;s.right=new Ee(pe(o,Ie(i.store,o)),m,m&&m.lastId,u,u&&u.id,e,null,new Ne(l,d)),s.right.integrate(t,0),s.forward()}}return c},$n=(t,e,s,r,i)=>{s.currentAttributes.forEach((f,x)=>{i[x]===void 0&&(i[x]=null)});const o=t.doc,c=o.clientID;Ta(s,i);const l=Ra(t,e,s,i),d=r.constructor===String?new st(r):r instanceof Me?new ut(r):new It(r);let{left:p,right:m,index:u}=s;e._searchMarker&&bs(e._searchMarker,s.index,d.getLength()),m=new Ee(pe(c,Ie(o.store,c)),p,p&&p.lastId,m,m&&m.id,e,null,d),m.integrate(t,0),s.right=m,s.index=u,s.forward(),Ca(t,e,s,l)},Ai=(t,e,s,r,i)=>{const o=t.doc,c=o.clientID;Ta(s,i);const l=Ra(t,e,s,i);e:for(;s.right!==null&&(r>0||l.size>0&&(s.right.deleted||s.right.content.constructor===Ne));){if(!s.right.deleted)switch(s.right.content.constructor){case Ne:{const{key:d,value:p}=s.right.content,m=i[d];if(m!==void 0){if(pt(m,p))l.delete(d);else{if(r===0)break e;l.set(d,p)}s.right.delete(t)}else s.currentAttributes.set(d,p);break}default:r<s.right.length&&bt(t,pe(s.right.id.client,s.right.id.clock+r)),r-=s.right.length;break}s.forward()}if(r>0){let d="";for(;r>0;r--)d+=`
100
- `;s.right=new Ee(pe(c,Ie(o.store,c)),s.left,s.left&&s.left.lastId,s.right,s.right&&s.right.id,e,null,new st(d)),s.right.integrate(t,0),s.forward()}Ca(t,e,s,l)},Aa=(t,e,s,r,i)=>{let o=e;const c=Ue();for(;o&&(!o.countable||o.deleted);){if(!o.deleted&&o.content.constructor===Ne){const p=o.content;c.set(p.key,p)}o=o.right}let l=0,d=!1;for(;e!==o;){if(s===e&&(d=!0),!e.deleted){const p=e.content;switch(p.constructor){case Ne:{const{key:m,value:u}=p,f=r.get(m)??null;(c.get(m)!==p||f===u)&&(e.delete(t),l++,!d&&(i.get(m)??null)===u&&f!==u&&(f===null?i.delete(m):i.set(m,f))),!d&&!e.deleted&&ss(i,p);break}}}e=e.right}return l},Fu=(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===Ne){const r=e.content.key;s.has(r)?e.delete(t):s.add(r)}e=e.left}},$u=t=>{let e=0;return be(t.doc,s=>{let r=t._start,i=t._start,o=Ue();const c=er(o);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Ne:ss(c,i.content);break;default:e+=Aa(s,r,i,o,c),o=er(c),r=i;break}i=i.right}}),e},zu=t=>{const e=new Set,s=t.doc;for(const[r,i]of t.afterState.entries()){const o=t.beforeState.get(r)||0;i!==o&&pa(t,s.store.clients.get(r),o,i,c=>{!c.deleted&&c.content.constructor===Ne&&c.constructor!==Ge&&e.add(c.parent)})}be(s,r=>{ea(t,t.deleteSet,i=>{if(i instanceof Ge||!i.parent._hasFormatting||e.has(i.parent))return;const o=i.parent;i.content.constructor===Ne?e.add(o):Fu(r,i)});for(const i of e)$u(i)})},Ii=(t,e,s)=>{const r=s,i=er(e.currentAttributes),o=e.right;for(;s>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case ut:case It:case st:s<e.right.length&&bt(t,pe(e.right.id.client,e.right.id.clock+s)),s-=e.right.length,e.right.delete(t);break}e.forward()}o&&Aa(t,o,e.right,i,e.currentAttributes);const c=(e.left||e.right).parent;return c._searchMarker&&bs(c._searchMarker,e.index,-r+s),e};class Hu extends Cn{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=[];be(e,r=>{const i=new Map,o=new Map;let c=this.target._start,l=null;const d={};let p="",m=0,u=0;const f=()=>{if(l!==null){let x=null;switch(l){case"delete":u>0&&(x={delete:u}),u=0;break;case"insert":(typeof p=="object"||p.length>0)&&(x={insert:p},i.size>0&&(x.attributes={},i.forEach((b,j)=>{b!==null&&(x.attributes[j]=b)}))),p="";break;case"retain":m>0&&(x={retain:m},Kc(d)||(x.attributes=Gc({},d))),m=0;break}x&&s.push(x),l=null}};for(;c!==null;){switch(c.content.constructor){case ut:case It:this.adds(c)?this.deletes(c)||(f(),l="insert",p=c.content.getContent()[0],f()):this.deletes(c)?(l!=="delete"&&(f(),l="delete"),u+=1):c.deleted||(l!=="retain"&&(f(),l="retain"),m+=1);break;case st:this.adds(c)?this.deletes(c)||(l!=="insert"&&(f(),l="insert"),p+=c.content.str):this.deletes(c)?(l!=="delete"&&(f(),l="delete"),u+=c.length):c.deleted||(l!=="retain"&&(f(),l="retain"),m+=c.length);break;case Ne:{const{key:x,value:b}=c.content;if(this.adds(c)){if(!this.deletes(c)){const j=i.get(x)??null;pt(j,b)?b!==null&&c.delete(r):(l==="retain"&&f(),pt(b,o.get(x)??null)?delete d[x]:d[x]=b)}}else if(this.deletes(c)){o.set(x,b);const j=i.get(x)??null;pt(j,b)||(l==="retain"&&f(),d[x]=j)}else if(!c.deleted){o.set(x,b);const j=d[x];j!==void 0&&(pt(j,b)?j!==null&&c.delete(r):(l==="retain"&&f(),b===null?delete d[x]:d[x]=b))}c.deleted||(l==="insert"&&f(),ss(i,c.content));break}}c=c.right}for(f();s.length>0;){const x=s[s.length-1];if(x.retain!==void 0&&x.attributes===void 0)s.pop();else break}}),this._delta=s}return this._delta}}class Jt extends Me{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Oe(),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 Jt}clone(){const e=new Jt;return e.applyDelta(this.toDelta()),e}_callObserver(e,s){super._callObserver(e,s);const r=new Hu(this,e,s);Rn(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Oe();let e="",s=this._start;for(;s!==null;)!s.deleted&&s.countable&&s.content.constructor===st&&(e+=s.content.str),s=s.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:s=!0}={}){this.doc!==null?be(this.doc,r=>{const i=new lr(null,this._start,0,new Map);for(let o=0;o<e.length;o++){const c=e[o];if(c.insert!==void 0){const l=!s&&typeof c.insert=="string"&&o===e.length-1&&i.right===null&&c.insert.slice(-1)===`
101
- `?c.insert.slice(0,-1):c.insert;(typeof l!="string"||l.length>0)&&$n(r,this,i,l,c.attributes||{})}else c.retain!==void 0?Ai(r,this,i,c.retain,c.attributes||{}):c.delete!==void 0&&Ii(r,i,c.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,s,r){this.doc??Oe();const i=[],o=new Map,c=this.doc;let l="",d=this._start;function p(){if(l.length>0){const u={};let f=!1;o.forEach((b,j)=>{f=!0,u[j]=b});const x={insert:l};f&&(x.attributes=u),i.push(x),l=""}}const m=()=>{for(;d!==null;){if(Wt(d,e)||s!==void 0&&Wt(d,s))switch(d.content.constructor){case st:{const u=o.get("ychange");e!==void 0&&!Wt(d,e)?(u===void 0||u.user!==d.id.client||u.type!=="removed")&&(p(),o.set("ychange",r?r("removed",d.id):{type:"removed"})):s!==void 0&&!Wt(d,s)?(u===void 0||u.user!==d.id.client||u.type!=="added")&&(p(),o.set("ychange",r?r("added",d.id):{type:"added"})):u!==void 0&&(p(),o.delete("ychange")),l+=d.content.str;break}case ut:case It:{p();const u={insert:d.content.getContent()[0]};if(o.size>0){const f={};u.attributes=f,o.forEach((x,b)=>{f[b]=x})}i.push(u);break}case Ne:Wt(d,e)&&(p(),ss(o,d.content));break}d=d.right}p()};return e||s?be(c,u=>{e&&or(u,e),s&&or(u,s),m()},"cleanup"):m(),i}insert(e,s,r){if(s.length<=0)return;const i=this.doc;i!==null?be(i,o=>{const c=As(o,this,e,!r);r||(r={},c.currentAttributes.forEach((l,d)=>{r[d]=l})),$n(o,this,c,s,r)}):this._pending.push(()=>this.insert(e,s,r))}insertEmbed(e,s,r){const i=this.doc;i!==null?be(i,o=>{const c=As(o,this,e,!r);$n(o,this,c,s,r||{})}):this._pending.push(()=>this.insertEmbed(e,s,r||{}))}delete(e,s){if(s===0)return;const r=this.doc;r!==null?be(r,i=>{Ii(i,As(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?be(i,o=>{const c=As(o,this,e,!1);c.right!==null&&Ai(o,this,c,s,r)}):this._pending.push(()=>this.format(e,s,r))}removeAttribute(e){this.doc!==null?be(this.doc,s=>{Qs(s,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,s){this.doc!==null?be(this.doc,r=>{Jr(r,this,e,s)}):this._pending.push(()=>this.setAttribute(e,s))}getAttribute(e){return Xr(this,e)}getAttributes(){return Ea(this)}_write(e){e.writeTypeRef(dh)}}const Vu=t=>new Jt;class zn{constructor(e,s=()=>!0){this._filter=s,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Oe()}[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===Xt||s.constructor===Tt)&&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 Tt extends Me{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 Tt}clone(){const e=new Tt;return e.insert(0,this.toArray().map(s=>s instanceof Me?s.clone():s)),e}get length(){return this.doc??Oe(),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(),at(new zn(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e))}_callObserver(e,s){Rn(this,e,new Yu(this,s,e))}toString(){return va(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),xs(this,o=>{i.insertBefore(o.toDOM(e,s,r),null)}),i}insert(e,s){this.doc!==null?be(this.doc,r=>{Sa(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}insertAfter(e,s){if(this.doc!==null)be(this.doc,r=>{const i=e&&e instanceof Me?e._item:e;Xs(r,this,i,s)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(o=>o===e)+1;if(i===0&&e!==null)throw He("Reference item not found");r.splice(i,0,...s)}}delete(e,s=1){this.doc!==null?be(this.doc,r=>{ja(r,this,e,s)}):this._prelimContent.splice(e,s)}toArray(){return wa(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return _a(this,e)}slice(e=0,s=this.length){return xa(this,e,s)}forEach(e){xs(this,e)}_write(e){e.writeTypeRef(hh)}}const Gu=t=>new Tt;class Xt extends Tt{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 Xt(this.nodeName)}clone(){const e=new Xt(this.nodeName),s=this.getAttributes();return Yc(s,(r,i)=>{e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof Me?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 d=r[l];s.push(d+'="'+e[d]+'"')}const o=this.nodeName.toLocaleLowerCase(),c=s.length>0?" "+s.join(" "):"";return`<${o}${c}>${super.toString()}</${o}>`}removeAttribute(e){this.doc!==null?be(this.doc,s=>{Qs(s,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,s){this.doc!==null?be(this.doc,r=>{Jr(r,this,e,s)}):this._prelimAttrs.set(e,s)}getAttribute(e){return Xr(this,e)}hasAttribute(e){return Na(this,e)}getAttributes(e){return e?Ou(this,e):Ea(this)}toDOM(e=document,s={},r){const i=e.createElement(this.nodeName),o=this.getAttributes();for(const c in o){const l=o[c];typeof l=="string"&&i.setAttribute(c,l)}return xs(this,c=>{i.appendChild(c.toDOM(e,s,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(uh),e.writeKey(this.nodeName)}}const qu=t=>new Xt(t.readKey());class Yu extends Cn{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 Zs extends Ct{constructor(e){super(),this.hookName=e}_copy(){return new Zs(this.hookName)}clone(){const e=new Zs(this.hookName);return this.forEach((s,r)=>{e.set(r,s)}),e}toDOM(e=document,s={},r){const i=s[this.hookName];let o;return i!==void 0?o=i.createDom(this):o=document.createElement(this.hookName),o.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(o,this),o}_write(e){e.writeTypeRef(fh),e.writeKey(this.hookName)}}const Ku=t=>new Zs(t.readKey());class en extends Jt{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 en}clone(){const e=new en;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 o=[];for(const c in e.attributes[i])o.push({key:c,value:e.attributes[i][c]});o.sort((c,l)=>c.key<l.key?-1:1),s.push({nodeName:i,attrs:o})}s.sort((i,o)=>i.nodeName<o.nodeName?-1:1);let r="";for(let i=0;i<s.length;i++){const o=s[i];r+=`<${o.nodeName}`;for(let c=0;c<o.attrs.length;c++){const l=o.attrs[c];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(ph)}}const Ju=t=>new en;class Qr{constructor(e,s){this.id=e,this.length=s}get deleted(){throw Xe()}mergeWith(e){return!1}write(e,s,r){throw Xe()}integrate(e,s){throw Xe()}}const Xu=0;class Ge extends Qr{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),fa(e.doc.store,this)}write(e,s){e.writeInfo(Xu),e.writeLen(this.length-s)}getMissing(e,s){return null}}class Ns{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ns(this.content)}splice(e){throw Xe()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeBuf(this.content)}getRef(){return 3}}const Qu=t=>new Ns(t.readBuf());class ws{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new ws(this.len)}splice(e){const s=new ws(this.len-e);return this.len=e,s}mergeWith(e){return this.len+=e.len,!0}integrate(e,s){Ks(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 Zu=t=>new ws(t.readLen()),Ia=(t,e)=>new ts({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Cs{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 Cs(Ia(this.doc.guid,this.opts))}splice(e){throw Xe()}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 eh=t=>new Cs(Ia(t.readString(),t.readAny()));class It{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new It(this.embed)}splice(e){throw Xe()}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 It(t.readJSON());class Ne{constructor(e,s){this.key=e,this.value=s}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Ne(this.key,this.value)}splice(e){throw Xe()}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 sh=t=>new Ne(t.readKey(),t.readJSON());class tn{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new tn(this.arr)}splice(e){const s=new tn(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 o=this.arr[i];e.writeString(o===void 0?"undefined":JSON.stringify(o))}}getRef(){return 2}}const nh=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 tn(s)},rh=ms("node_env")==="development";class Rt{constructor(e){this.arr=e,rh&&ko(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Rt(this.arr)}splice(e){const s=new Rt(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 o=this.arr[i];e.writeAny(o)}}getRef(){return 8}}const ih=t=>{const e=t.readLen(),s=[];for(let r=0;r<e;r++)s.push(t.readAny());return new Rt(s)};class st{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new st(this.str)}splice(e){const s=new st(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 oh=t=>new st(t.readString()),ah=[Wu,Bu,Vu,qu,Gu,Ku,Ju],lh=0,ch=1,dh=2,uh=3,hh=4,fh=5,ph=6;class ut{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new ut(this.type._copy())}splice(e){throw Xe()}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 gh=t=>new ut(ah[t.readTypeRef()](t)),sn=(t,e,s)=>{const{client:r,clock:i}=e.id,o=new Ee(pe(r,i+s),e,pe(r,i+s-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(s));return e.deleted&&o.markDeleted(),e.keep&&(o.keep=!0),e.redone!==null&&(o.redone=pe(e.redone.client,e.redone.clock+s)),e.right=o,o.right!==null&&(o.right.left=o),t._mergeStructs.push(o),o.parentSub!==null&&o.right===null&&o.parent._map.set(o.parentSub,o),e.length=s,o};class Ee extends Qr{constructor(e,s,r,i,o,c,l,d){super(e,d.getLength()),this.origin=r,this.left=s,this.right=i,this.rightOrigin=o,this.parent=c,this.parentSub=l,this.redone=null,this.content=d,this.info=this.content.isCountable()?ci:0}set marker(e){(this.info&Dn)>0!==e&&(this.info^=Dn)}get marker(){return(this.info&Dn)>0}get keep(){return(this.info&li)>0}set keep(e){this.keep!==e&&(this.info^=li)}get countable(){return(this.info&ci)>0}get deleted(){return(this.info&Ln)>0}set deleted(e){this.deleted!==e&&(this.info^=Ln)}markDeleted(){this.info|=Ln}getMissing(e,s){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Ie(s,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Ie(s,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Ft&&this.id.client!==this.parent.client&&this.parent.clock>=Ie(s,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Ei(e,s,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=bt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ge||this.right&&this.right.constructor===Ge)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Ee?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Ee&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Ft){const r=Fn(s,this.parent);r.constructor===Ge?this.parent=null:this.parent=r.content.type}return null}integrate(e,s){if(s>0&&(this.id.clock+=s,this.left=Ei(e,e.doc.store,pe(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 o=new Set,c=new Set;for(;i!==null&&i!==this.right;){if(c.add(i),o.add(i),Ts(this.origin,i.origin)){if(i.id.client<this.id.client)r=i,o.clear();else if(Ts(this.rightOrigin,i.rightOrigin))break}else if(i.origin!==null&&c.has(Fn(e.doc.store,i.origin)))o.has(Fn(e.doc.store,i.origin))||(r=i,o.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),fa(e.doc.store,this),this.content.integrate(e,this),Ci(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Ge(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:pe(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ts(e.origin,this.lastId)&&this.right===e&&Ts(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(),Ks(e.deleteSet,this.id.client,this.id.clock,this.length),Ci(e,s,this.parentSub),this.content.delete(e)}}gc(e,s){if(!this.deleted)throw Je();this.content.gc(e),s?wu(e,this,new Ge(this.id,this.length)):this.content=new ws(this.length)}write(e,s){const r=s>0?pe(this.id.client,this.id.clock+s-1):this.origin,i=this.rightOrigin,o=this.parentSub,c=this.content.getRef()&gn|(r===null?0:$e)|(i===null?0:it)|(o===null?0:hs);if(e.writeInfo(c),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const l=this.parent;if(l._item!==void 0){const d=l._item;if(d===null){const p=bu(l);e.writeParentInfo(!0),e.writeString(p)}else e.writeParentInfo(!1),e.writeLeftID(d.id)}else l.constructor===String?(e.writeParentInfo(!0),e.writeString(l)):l.constructor===Ft?(e.writeParentInfo(!1),e.writeLeftID(l)):Je();o!==null&&e.writeString(o)}this.content.write(e,s)}}const La=(t,e)=>mh[e&gn](t),mh=[()=>{Je()},Zu,nh,Qu,oh,th,sh,gh,ih,eh,()=>{Je()}],yh=10;class qe extends Qr{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,s){Je()}write(e,s){e.writeInfo(yh),re(e.restEncoder,this.length-s)}getMissing(e,s){return null}}const Da=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Ma="__ $YJS$ __";Da[Ma]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Da[Ma]=!0;const Lt=t=>Gt((e,s)=>{t.onerror=r=>s(new Error(r.target.error)),t.onsuccess=r=>e(r.target.result)}),bh=(t,e)=>Gt((s,r)=>{const i=indexedDB.open(t);i.onupgradeneeded=o=>e(o.target.result),i.onerror=o=>r(He(o.target.error)),i.onsuccess=o=>{const c=o.target.result;c.onversionchange=()=>{c.close()},s(c)}}),xh=t=>Lt(indexedDB.deleteDatabase(t)),wh=(t,e)=>e.forEach(s=>t.createObjectStore.apply(t,s)),os=(t,e,s="readwrite")=>{const r=t.transaction(e,s);return e.map(i=>Ch(r,i))},Oa=(t,e)=>Lt(t.count(e)),vh=(t,e)=>Lt(t.get(e)),Pa=(t,e)=>Lt(t.delete(e)),_h=(t,e,s)=>Lt(t.put(e,s)),cr=(t,e)=>Lt(t.add(e)),kh=(t,e,s)=>Lt(t.getAll(e,s)),Sh=(t,e,s)=>{let r=null;return Nh(t,e,i=>(r=i,!1),s).then(()=>r)},jh=(t,e=null)=>Sh(t,e,"prev"),Eh=(t,e)=>Gt((s,r)=>{t.onerror=r,t.onsuccess=async i=>{const o=i.target.result;if(o===null||await e(o)===!1)return s();o.continue()}}),Nh=(t,e,s,r="next")=>Eh(t.openKeyCursor(e,r),i=>s(i.key)),Ch=(t,e)=>t.objectStore(e),Th=(t,e)=>IDBKeyRange.upperBound(t,e),Rh=(t,e)=>IDBKeyRange.lowerBound(t,e),Hn="custom",Wa="updates",Ua=500,Ba=(t,e=()=>{},s=()=>{})=>{const[r]=os(t.db,[Wa]);return kh(r,Rh(t._dbref,!1)).then(i=>{t._destroyed||(e(r),be(t.doc,()=>{i.forEach(o=>la(t.doc,o))},t,!1),s(r))}).then(()=>jh(r).then(i=>{t._dbref=i+1})).then(()=>Oa(r).then(i=>{t._dbsize=i})).then(()=>r)},Ah=(t,e=!0)=>Ba(t).then(s=>{(e||t._dbsize>=Ua)&&cr(s,Vr(t.doc)).then(()=>Pa(s,Th(t._dbref,!0))).then(()=>Oa(s).then(r=>{t._dbsize=r}))});class Ih extends Nr{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=bh(e,r=>wh(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Gt(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,Ba(this,c=>cr(c,Vr(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[o]=os(this.db,[Wa]);cr(o,r),++this._dbsize>=Ua&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Ah(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(()=>{xh(this.name)})}get(e){return this._db.then(s=>{const[r]=os(s,[Hn],"readonly");return vh(r,e)})}set(e,s){return this._db.then(r=>{const[i]=os(r,[Hn]);return _h(i,s,e)})}del(e){return this._db.then(s=>{const[r]=os(s,[Hn]);return Pa(r,e)})}}const Lh=1200,Dh=2500,nn=3e4,dr=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=c=>{t.lastMessageReceived=lt();const l=c.data,d=typeof l=="string"?JSON.parse(l):l;d&&d.type==="pong"&&(clearTimeout(r),r=setTimeout(o,nn/2)),t.emit("message",[d,t])};const i=c=>{t.ws!==null&&(t.ws=null,t.connecting=!1,t.connected?(t.connected=!1,t.emit("disconnect",[{type:"disconnect",error:c},t])):t.unsuccessfulReconnects++,setTimeout(dr,Cr(cc(t.unsuccessfulReconnects+1)*Lh,Dh),t)),clearTimeout(r)},o=()=>{t.ws===e&&t.send({type:"ping"})};e.onclose=()=>i(null),e.onerror=c=>i(c),e.onopen=()=>{t.lastMessageReceived=lt(),t.connecting=!1,t.connected=!0,t.unsuccessfulReconnects=0,t.emit("connect",[{type:"connect"},t]),r=setTimeout(o,nn/2)}}};class Mh extends Nr{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&&nn<lt()-this.lastMessageReceived&&this.ws.close()},nn/2),dr(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&&dr(this)}}const Fa=new Map;class Oh{constructor(e){this.room=e,this.onmessage=null,this._onChange=s=>s.key===e&&this.onmessage!==null&&this.onmessage({data:To(s.newValue||"")}),zc(this._onChange)}postMessage(e){vo.setItem(this.room,Co(od(e)))}close(){Hc(this._onChange)}}const Ph=typeof BroadcastChannel>"u"?Oh:BroadcastChannel,Zr=t=>ze(Fa,t,()=>{const e=yt(),s=new Ph(t);return s.onmessage=r=>e.forEach(i=>i(r.data,"broadcastchannel")),{bc:s,subs:e}}),Wh=(t,e)=>(Zr(t).subs.add(e),e),Uh=(t,e)=>{const s=Zr(t),r=s.subs.delete(e);return r&&s.subs.size===0&&(s.bc.close(),Fa.delete(t)),r},Bh=(t,e,s=null)=>{const r=Zr(t);r.bc.postMessage(e),r.subs.forEach(i=>i(e,s))},Fh=()=>{let t=!0;return(e,s)=>{if(t){t=!1;try{e()}finally{t=!0}}else s!==void 0&&s()}};function Is(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 Vn={exports:{}},Li;function $h(){return Li||(Li=1,(function(t,e){(function(s){t.exports=s()})(function(){var s=Math.floor,r=Math.abs,i=Math.pow;return(function(){function o(c,l,d){function p(f,x){if(!l[f]){if(!c[f]){var b=typeof Is=="function"&&Is;if(!x&&b)return b(f,!0);if(m)return m(f,!0);var j=new Error("Cannot find module '"+f+"'");throw j.code="MODULE_NOT_FOUND",j}var A=l[f]={exports:{}};c[f][0].call(A.exports,function(v){var I=c[f][1][v];return p(I||v)},A,A.exports,o,c,l,d)}return l[f].exports}for(var m=typeof Is=="function"&&Is,u=0;u<d.length;u++)p(d[u]);return p}return o})()({1:[function(o,c,l){function d(k){var _=k.length;if(0<_%4)throw new Error("Invalid string. Length must be a multiple of 4");var T=k.indexOf("=");T===-1&&(T=_);var E=T===_?0:4-T%4;return[T,E]}function p(k,_,T){return 3*(_+T)/4-T}function m(k){var _,T,E=d(k),C=E[0],M=E[1],S=new A(p(k,C,M)),R=0,O=0<M?C-4:C;for(T=0;T<O;T+=4)_=j[k.charCodeAt(T)]<<18|j[k.charCodeAt(T+1)]<<12|j[k.charCodeAt(T+2)]<<6|j[k.charCodeAt(T+3)],S[R++]=255&_>>16,S[R++]=255&_>>8,S[R++]=255&_;return M===2&&(_=j[k.charCodeAt(T)]<<2|j[k.charCodeAt(T+1)]>>4,S[R++]=255&_),M===1&&(_=j[k.charCodeAt(T)]<<10|j[k.charCodeAt(T+1)]<<4|j[k.charCodeAt(T+2)]>>2,S[R++]=255&_>>8,S[R++]=255&_),S}function u(k){return b[63&k>>18]+b[63&k>>12]+b[63&k>>6]+b[63&k]}function f(k,_,T){for(var E,C=[],M=_;M<T;M+=3)E=(16711680&k[M]<<16)+(65280&k[M+1]<<8)+(255&k[M+2]),C.push(u(E));return C.join("")}function x(k){for(var _,T=k.length,E=T%3,C=[],M=16383,S=0,R=T-E;S<R;S+=M)C.push(f(k,S,S+M>R?R:S+M));return E===1?(_=k[T-1],C.push(b[_>>2]+b[63&_<<4]+"==")):E===2&&(_=(k[T-2]<<8)+k[T-1],C.push(b[_>>10]+b[63&_>>4]+b[63&_<<2]+"=")),C.join("")}l.byteLength=function(k){var _=d(k),T=_[0],E=_[1];return 3*(T+E)/4-E},l.toByteArray=m,l.fromByteArray=x;for(var b=[],j=[],A=typeof Uint8Array>"u"?Array:Uint8Array,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",I=0,g=v.length;I<g;++I)b[I]=v[I],j[v.charCodeAt(I)]=I;j[45]=62,j[95]=63},{}],2:[function(){},{}],3:[function(o,c,l){(function(){(function(){var d=String.fromCharCode,p=Math.min;function m(a){if(2147483647<a)throw new RangeError('The value "'+a+'" is invalid for option "size"');var h=new Uint8Array(a);return h.__proto__=u.prototype,h}function u(a,h,y){if(typeof a=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return j(a)}return f(a,h,y)}function f(a,h,y){if(typeof a=="string")return A(a,h);if(ArrayBuffer.isView(a))return v(a);if(a==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a);if(D(a,ArrayBuffer)||a&&D(a.buffer,ArrayBuffer))return I(a,h,y);if(typeof a=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var L=a.valueOf&&a.valueOf();if(L!=null&&L!==a)return u.from(L,h,y);var P=g(a);if(P)return P;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof a[Symbol.toPrimitive]=="function")return u.from(a[Symbol.toPrimitive]("string"),h,y);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a)}function x(a){if(typeof a!="number")throw new TypeError('"size" argument must be of type number');if(0>a)throw new RangeError('The value "'+a+'" is invalid for option "size"')}function b(a,h,y){return x(a),0>=a||h===void 0?m(a):typeof y=="string"?m(a).fill(h,y):m(a).fill(h)}function j(a){return x(a),m(0>a?0:0|k(a))}function A(a,h){if((typeof h!="string"||h==="")&&(h="utf8"),!u.isEncoding(h))throw new TypeError("Unknown encoding: "+h);var y=0|_(a,h),L=m(y),P=L.write(a,h);return P!==y&&(L=L.slice(0,P)),L}function v(a){for(var h=0>a.length?0:0|k(a.length),y=m(h),L=0;L<h;L+=1)y[L]=255&a[L];return y}function I(a,h,y){if(0>h||a.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(a.byteLength<h+(y||0))throw new RangeError('"length" is outside of buffer bounds');var L;return L=h===void 0&&y===void 0?new Uint8Array(a):y===void 0?new Uint8Array(a,h):new Uint8Array(a,h,y),L.__proto__=u.prototype,L}function g(a){if(u.isBuffer(a)){var h=0|k(a.length),y=m(h);return y.length===0||a.copy(y,0,0,h),y}return a.length===void 0?a.type==="Buffer"&&Array.isArray(a.data)?v(a.data):void 0:typeof a.length!="number"||U(a.length)?m(0):v(a)}function k(a){if(a>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|a}function _(a,h){if(u.isBuffer(a))return a.length;if(ArrayBuffer.isView(a)||D(a,ArrayBuffer))return a.byteLength;if(typeof a!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof a);var y=a.length,L=2<arguments.length&&arguments[2]===!0;if(!L&&y===0)return 0;for(var P=!1;;)switch(h){case"ascii":case"latin1":case"binary":return y;case"utf8":case"utf-8":return xe(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*y;case"hex":return y>>>1;case"base64":return Q(a).length;default:if(P)return L?-1:xe(a).length;h=(""+h).toLowerCase(),P=!0}}function T(a,h,y){var L=!1;if((h===void 0||0>h)&&(h=0),h>this.length||((y===void 0||y>this.length)&&(y=this.length),0>=y)||(y>>>=0,h>>>=0,y<=h))return"";for(a||(a="utf8");;)switch(a){case"hex":return ne(this,h,y);case"utf8":case"utf-8":return W(this,h,y);case"ascii":return $(this,h,y);case"latin1":case"binary":return ee(this,h,y);case"base64":return q(this,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return X(this,h,y);default:if(L)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),L=!0}}function E(a,h,y){var L=a[h];a[h]=a[y],a[y]=L}function C(a,h,y,L,P){if(a.length===0)return-1;if(typeof y=="string"?(L=y,y=0):2147483647<y?y=2147483647:-2147483648>y&&(y=-2147483648),y=+y,U(y)&&(y=P?0:a.length-1),0>y&&(y=a.length+y),y>=a.length){if(P)return-1;y=a.length-1}else if(0>y)if(P)y=0;else return-1;if(typeof h=="string"&&(h=u.from(h,L)),u.isBuffer(h))return h.length===0?-1:M(a,h,y,L,P);if(typeof h=="number")return h&=255,typeof Uint8Array.prototype.indexOf=="function"?P?Uint8Array.prototype.indexOf.call(a,h,y):Uint8Array.prototype.lastIndexOf.call(a,h,y):M(a,[h],y,L,P);throw new TypeError("val must be string, number or Buffer")}function M(a,h,y,L,P){function F(Dt,ns){return se===1?Dt[ns]:Dt.readUInt16BE(ns*se)}var se=1,he=a.length,ve=h.length;if(L!==void 0&&(L=(L+"").toLowerCase(),L==="ucs2"||L==="ucs-2"||L==="utf16le"||L==="utf-16le")){if(2>a.length||2>h.length)return-1;se=2,he/=2,ve/=2,y/=2}var fe;if(P){var ue=-1;for(fe=y;fe<he;fe++)if(F(a,fe)!==F(h,ue===-1?0:fe-ue))ue!==-1&&(fe-=fe-ue),ue=-1;else if(ue===-1&&(ue=fe),fe-ue+1===ve)return ue*se}else for(y+ve>he&&(y=he-ve),fe=y;0<=fe;fe--){for(var De=!0,wt=0;wt<ve;wt++)if(F(a,fe+wt)!==F(h,wt)){De=!1;break}if(De)return fe}return-1}function S(a,h,y,L){y=+y||0;var P=a.length-y;L?(L=+L,L>P&&(L=P)):L=P;var F=h.length;L>F/2&&(L=F/2);for(var se,he=0;he<L;++he){if(se=parseInt(h.substr(2*he,2),16),U(se))return he;a[y+he]=se}return he}function R(a,h,y,L){return oe(xe(h,a.length-y),a,y,L)}function O(a,h,y,L){return oe(K(h),a,y,L)}function B(a,h,y,L){return O(a,h,y,L)}function z(a,h,y,L){return oe(Q(h),a,y,L)}function G(a,h,y,L){return oe(Y(h,a.length-y),a,y,L)}function q(a,h,y){return h===0&&y===a.length?H.fromByteArray(a):H.fromByteArray(a.slice(h,y))}function W(a,h,y){y=p(a.length,y);for(var L=[],P=h;P<y;){var F=a[P],se=null,he=239<F?4:223<F?3:191<F?2:1;if(P+he<=y){var ve,fe,ue,De;he===1?128>F&&(se=F):he===2?(ve=a[P+1],(192&ve)==128&&(De=(31&F)<<6|63&ve,127<De&&(se=De))):he===3?(ve=a[P+1],fe=a[P+2],(192&ve)==128&&(192&fe)==128&&(De=(15&F)<<12|(63&ve)<<6|63&fe,2047<De&&(55296>De||57343<De)&&(se=De))):he===4&&(ve=a[P+1],fe=a[P+2],ue=a[P+3],(192&ve)==128&&(192&fe)==128&&(192&ue)==128&&(De=(15&F)<<18|(63&ve)<<12|(63&fe)<<6|63&ue,65535<De&&1114112>De&&(se=De)))}se===null?(se=65533,he=1):65535<se&&(se-=65536,L.push(55296|1023&se>>>10),se=56320|1023&se),L.push(se),P+=he}return V(L)}function V(a){var h=a.length;if(h<=4096)return d.apply(String,a);for(var y="",L=0;L<h;)y+=d.apply(String,a.slice(L,L+=4096));return y}function $(a,h,y){var L="";y=p(a.length,y);for(var P=h;P<y;++P)L+=d(127&a[P]);return L}function ee(a,h,y){var L="";y=p(a.length,y);for(var P=h;P<y;++P)L+=d(a[P]);return L}function ne(a,h,y){var L=a.length;(!h||0>h)&&(h=0),(!y||0>y||y>L)&&(y=L);for(var P="",F=h;F<y;++F)P+=ye(a[F]);return P}function X(a,h,y){for(var L=a.slice(h,y),P="",F=0;F<L.length;F+=2)P+=d(L[F]+256*L[F+1]);return P}function Z(a,h,y){if(a%1!=0||0>a)throw new RangeError("offset is not uint");if(a+h>y)throw new RangeError("Trying to access beyond buffer length")}function J(a,h,y,L,P,F){if(!u.isBuffer(a))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>P||h<F)throw new RangeError('"value" argument is out of bounds');if(y+L>a.length)throw new RangeError("Index out of range")}function we(a,h,y,L){if(y+L>a.length)throw new RangeError("Index out of range");if(0>y)throw new RangeError("Index out of range")}function We(a,h,y,L,P){return h=+h,y>>>=0,P||we(a,h,y,4),te.write(a,h,y,L,23,4),y+4}function le(a,h,y,L,P){return h=+h,y>>>=0,P||we(a,h,y,8),te.write(a,h,y,L,52,8),y+8}function ge(a){if(a=a.split("=")[0],a=a.trim().replace(N,""),2>a.length)return"";for(;a.length%4!=0;)a+="=";return a}function ye(a){return 16>a?"0"+a.toString(16):a.toString(16)}function xe(a,h){h=h||1/0;for(var y,L=a.length,P=null,F=[],se=0;se<L;++se){if(y=a.charCodeAt(se),55295<y&&57344>y){if(!P){if(56319<y){-1<(h-=3)&&F.push(239,191,189);continue}else if(se+1===L){-1<(h-=3)&&F.push(239,191,189);continue}P=y;continue}if(56320>y){-1<(h-=3)&&F.push(239,191,189),P=y;continue}y=(P-55296<<10|y-56320)+65536}else P&&-1<(h-=3)&&F.push(239,191,189);if(P=null,128>y){if(0>(h-=1))break;F.push(y)}else if(2048>y){if(0>(h-=2))break;F.push(192|y>>6,128|63&y)}else if(65536>y){if(0>(h-=3))break;F.push(224|y>>12,128|63&y>>6,128|63&y)}else if(1114112>y){if(0>(h-=4))break;F.push(240|y>>18,128|63&y>>12,128|63&y>>6,128|63&y)}else throw new Error("Invalid code point")}return F}function K(a){for(var h=[],y=0;y<a.length;++y)h.push(255&a.charCodeAt(y));return h}function Y(a,h){for(var y,L,P,F=[],se=0;se<a.length&&!(0>(h-=2));++se)y=a.charCodeAt(se),L=y>>8,P=y%256,F.push(P),F.push(L);return F}function Q(a){return H.toByteArray(ge(a))}function oe(a,h,y,L){for(var P=0;P<L&&!(P+y>=h.length||P>=a.length);++P)h[P+y]=a[P];return P}function D(a,h){return a instanceof h||a!=null&&a.constructor!=null&&a.constructor.name!=null&&a.constructor.name===h.name}function U(a){return a!==a}var H=o("base64-js"),te=o("ieee754");l.Buffer=u,l.SlowBuffer=function(a){return+a!=a&&(a=0),u.alloc(+a)},l.INSPECT_MAX_BYTES=50,l.kMaxLength=2147483647,u.TYPED_ARRAY_SUPPORT=(function(){try{var a=new Uint8Array(1);return a.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},a.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(a,h,y){return f(a,h,y)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(a,h,y){return b(a,h,y)},u.allocUnsafe=function(a){return j(a)},u.allocUnsafeSlow=function(a){return j(a)},u.isBuffer=function(a){return a!=null&&a._isBuffer===!0&&a!==u.prototype},u.compare=function(a,h){if(D(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),D(h,Uint8Array)&&(h=u.from(h,h.offset,h.byteLength)),!u.isBuffer(a)||!u.isBuffer(h))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===h)return 0;for(var y=a.length,L=h.length,P=0,F=p(y,L);P<F;++P)if(a[P]!==h[P]){y=a[P],L=h[P];break}return y<L?-1:L<y?1:0},u.isEncoding=function(a){switch((a+"").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(a,h){if(!Array.isArray(a))throw new TypeError('"list" argument must be an Array of Buffers');if(a.length===0)return u.alloc(0);var y;if(h===void 0)for(h=0,y=0;y<a.length;++y)h+=a[y].length;var L=u.allocUnsafe(h),P=0;for(y=0;y<a.length;++y){var F=a[y];if(D(F,Uint8Array)&&(F=u.from(F)),!u.isBuffer(F))throw new TypeError('"list" argument must be an Array of Buffers');F.copy(L,P),P+=F.length}return L},u.byteLength=_,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var a=this.length;if(a%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var h=0;h<a;h+=2)E(this,h,h+1);return this},u.prototype.swap32=function(){var a=this.length;if(a%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var h=0;h<a;h+=4)E(this,h,h+3),E(this,h+1,h+2);return this},u.prototype.swap64=function(){var a=this.length;if(a%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var h=0;h<a;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 a=this.length;return a===0?"":arguments.length===0?W(this,0,a):T.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(a){if(!u.isBuffer(a))throw new TypeError("Argument must be a Buffer");return this===a||u.compare(this,a)===0},u.prototype.inspect=function(){var a="",h=l.INSPECT_MAX_BYTES;return a=this.toString("hex",0,h).replace(/(.{2})/g,"$1 ").trim(),this.length>h&&(a+=" ... "),"<Buffer "+a+">"},u.prototype.compare=function(a,h,y,L,P){if(D(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),!u.isBuffer(a))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof a);if(h===void 0&&(h=0),y===void 0&&(y=a?a.length:0),L===void 0&&(L=0),P===void 0&&(P=this.length),0>h||y>a.length||0>L||P>this.length)throw new RangeError("out of range index");if(L>=P&&h>=y)return 0;if(L>=P)return-1;if(h>=y)return 1;if(h>>>=0,y>>>=0,L>>>=0,P>>>=0,this===a)return 0;for(var F=P-L,se=y-h,he=p(F,se),ve=this.slice(L,P),fe=a.slice(h,y),ue=0;ue<he;++ue)if(ve[ue]!==fe[ue]){F=ve[ue],se=fe[ue];break}return F<se?-1:se<F?1:0},u.prototype.includes=function(a,h,y){return this.indexOf(a,h,y)!==-1},u.prototype.indexOf=function(a,h,y){return C(this,a,h,y,!0)},u.prototype.lastIndexOf=function(a,h,y){return C(this,a,h,y,!1)},u.prototype.write=function(a,h,y,L){if(h===void 0)L="utf8",y=this.length,h=0;else if(y===void 0&&typeof h=="string")L=h,y=this.length,h=0;else if(isFinite(h))h>>>=0,isFinite(y)?(y>>>=0,L===void 0&&(L="utf8")):(L=y,y=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var P=this.length-h;if((y===void 0||y>P)&&(y=P),0<a.length&&(0>y||0>h)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");L||(L="utf8");for(var F=!1;;)switch(L){case"hex":return S(this,a,h,y);case"utf8":case"utf-8":return R(this,a,h,y);case"ascii":return O(this,a,h,y);case"latin1":case"binary":return B(this,a,h,y);case"base64":return z(this,a,h,y);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,a,h,y);default:if(F)throw new TypeError("Unknown encoding: "+L);L=(""+L).toLowerCase(),F=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},u.prototype.slice=function(a,h){var y=this.length;a=~~a,h=h===void 0?y:~~h,0>a?(a+=y,0>a&&(a=0)):a>y&&(a=y),0>h?(h+=y,0>h&&(h=0)):h>y&&(h=y),h<a&&(h=a);var L=this.subarray(a,h);return L.__proto__=u.prototype,L},u.prototype.readUIntLE=function(a,h,y){a>>>=0,h>>>=0,y||Z(a,h,this.length);for(var L=this[a],P=1,F=0;++F<h&&(P*=256);)L+=this[a+F]*P;return L},u.prototype.readUIntBE=function(a,h,y){a>>>=0,h>>>=0,y||Z(a,h,this.length);for(var L=this[a+--h],P=1;0<h&&(P*=256);)L+=this[a+--h]*P;return L},u.prototype.readUInt8=function(a,h){return a>>>=0,h||Z(a,1,this.length),this[a]},u.prototype.readUInt16LE=function(a,h){return a>>>=0,h||Z(a,2,this.length),this[a]|this[a+1]<<8},u.prototype.readUInt16BE=function(a,h){return a>>>=0,h||Z(a,2,this.length),this[a]<<8|this[a+1]},u.prototype.readUInt32LE=function(a,h){return a>>>=0,h||Z(a,4,this.length),(this[a]|this[a+1]<<8|this[a+2]<<16)+16777216*this[a+3]},u.prototype.readUInt32BE=function(a,h){return a>>>=0,h||Z(a,4,this.length),16777216*this[a]+(this[a+1]<<16|this[a+2]<<8|this[a+3])},u.prototype.readIntLE=function(a,h,y){a>>>=0,h>>>=0,y||Z(a,h,this.length);for(var L=this[a],P=1,F=0;++F<h&&(P*=256);)L+=this[a+F]*P;return P*=128,L>=P&&(L-=i(2,8*h)),L},u.prototype.readIntBE=function(a,h,y){a>>>=0,h>>>=0,y||Z(a,h,this.length);for(var L=h,P=1,F=this[a+--L];0<L&&(P*=256);)F+=this[a+--L]*P;return P*=128,F>=P&&(F-=i(2,8*h)),F},u.prototype.readInt8=function(a,h){return a>>>=0,h||Z(a,1,this.length),128&this[a]?-1*(255-this[a]+1):this[a]},u.prototype.readInt16LE=function(a,h){a>>>=0,h||Z(a,2,this.length);var y=this[a]|this[a+1]<<8;return 32768&y?4294901760|y:y},u.prototype.readInt16BE=function(a,h){a>>>=0,h||Z(a,2,this.length);var y=this[a+1]|this[a]<<8;return 32768&y?4294901760|y:y},u.prototype.readInt32LE=function(a,h){return a>>>=0,h||Z(a,4,this.length),this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24},u.prototype.readInt32BE=function(a,h){return a>>>=0,h||Z(a,4,this.length),this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]},u.prototype.readFloatLE=function(a,h){return a>>>=0,h||Z(a,4,this.length),te.read(this,a,!0,23,4)},u.prototype.readFloatBE=function(a,h){return a>>>=0,h||Z(a,4,this.length),te.read(this,a,!1,23,4)},u.prototype.readDoubleLE=function(a,h){return a>>>=0,h||Z(a,8,this.length),te.read(this,a,!0,52,8)},u.prototype.readDoubleBE=function(a,h){return a>>>=0,h||Z(a,8,this.length),te.read(this,a,!1,52,8)},u.prototype.writeUIntLE=function(a,h,y,L){if(a=+a,h>>>=0,y>>>=0,!L){var P=i(2,8*y)-1;J(this,a,h,y,P,0)}var F=1,se=0;for(this[h]=255&a;++se<y&&(F*=256);)this[h+se]=255&a/F;return h+y},u.prototype.writeUIntBE=function(a,h,y,L){if(a=+a,h>>>=0,y>>>=0,!L){var P=i(2,8*y)-1;J(this,a,h,y,P,0)}var F=y-1,se=1;for(this[h+F]=255&a;0<=--F&&(se*=256);)this[h+F]=255&a/se;return h+y},u.prototype.writeUInt8=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,1,255,0),this[h]=255&a,h+1},u.prototype.writeUInt16LE=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,2,65535,0),this[h]=255&a,this[h+1]=a>>>8,h+2},u.prototype.writeUInt16BE=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,2,65535,0),this[h]=a>>>8,this[h+1]=255&a,h+2},u.prototype.writeUInt32LE=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,4,4294967295,0),this[h+3]=a>>>24,this[h+2]=a>>>16,this[h+1]=a>>>8,this[h]=255&a,h+4},u.prototype.writeUInt32BE=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,4,4294967295,0),this[h]=a>>>24,this[h+1]=a>>>16,this[h+2]=a>>>8,this[h+3]=255&a,h+4},u.prototype.writeIntLE=function(a,h,y,L){if(a=+a,h>>>=0,!L){var P=i(2,8*y-1);J(this,a,h,y,P-1,-P)}var F=0,se=1,he=0;for(this[h]=255&a;++F<y&&(se*=256);)0>a&&he===0&&this[h+F-1]!==0&&(he=1),this[h+F]=255&(a/se>>0)-he;return h+y},u.prototype.writeIntBE=function(a,h,y,L){if(a=+a,h>>>=0,!L){var P=i(2,8*y-1);J(this,a,h,y,P-1,-P)}var F=y-1,se=1,he=0;for(this[h+F]=255&a;0<=--F&&(se*=256);)0>a&&he===0&&this[h+F+1]!==0&&(he=1),this[h+F]=255&(a/se>>0)-he;return h+y},u.prototype.writeInt8=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,1,127,-128),0>a&&(a=255+a+1),this[h]=255&a,h+1},u.prototype.writeInt16LE=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,2,32767,-32768),this[h]=255&a,this[h+1]=a>>>8,h+2},u.prototype.writeInt16BE=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,2,32767,-32768),this[h]=a>>>8,this[h+1]=255&a,h+2},u.prototype.writeInt32LE=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,4,2147483647,-2147483648),this[h]=255&a,this[h+1]=a>>>8,this[h+2]=a>>>16,this[h+3]=a>>>24,h+4},u.prototype.writeInt32BE=function(a,h,y){return a=+a,h>>>=0,y||J(this,a,h,4,2147483647,-2147483648),0>a&&(a=4294967295+a+1),this[h]=a>>>24,this[h+1]=a>>>16,this[h+2]=a>>>8,this[h+3]=255&a,h+4},u.prototype.writeFloatLE=function(a,h,y){return We(this,a,h,!0,y)},u.prototype.writeFloatBE=function(a,h,y){return We(this,a,h,!1,y)},u.prototype.writeDoubleLE=function(a,h,y){return le(this,a,h,!0,y)},u.prototype.writeDoubleBE=function(a,h,y){return le(this,a,h,!1,y)},u.prototype.copy=function(a,h,y,L){if(!u.isBuffer(a))throw new TypeError("argument should be a Buffer");if(y||(y=0),L||L===0||(L=this.length),h>=a.length&&(h=a.length),h||(h=0),0<L&&L<y&&(L=y),L===y||a.length===0||this.length===0)return 0;if(0>h)throw new RangeError("targetStart out of bounds");if(0>y||y>=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),a.length-h<L-y&&(L=a.length-h+y);var P=L-y;if(this===a&&typeof Uint8Array.prototype.copyWithin=="function")this.copyWithin(h,y,L);else if(this===a&&y<h&&h<L)for(var F=P-1;0<=F;--F)a[F+h]=this[F+y];else Uint8Array.prototype.set.call(a,this.subarray(y,L),h);return P},u.prototype.fill=function(a,h,y,L){if(typeof a=="string"){if(typeof h=="string"?(L=h,h=0,y=this.length):typeof y=="string"&&(L=y,y=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(a.length===1){var P=a.charCodeAt(0);(L==="utf8"&&128>P||L==="latin1")&&(a=P)}}else typeof a=="number"&&(a&=255);if(0>h||this.length<h||this.length<y)throw new RangeError("Out of range index");if(y<=h)return this;h>>>=0,y=y===void 0?this.length:y>>>0,a||(a=0);var F;if(typeof a=="number")for(F=h;F<y;++F)this[F]=a;else{var se=u.isBuffer(a)?a:u.from(a,L),he=se.length;if(he===0)throw new TypeError('The value "'+a+'" is invalid for argument "value"');for(F=0;F<y-h;++F)this[F+h]=se[F%he]}return this};var N=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,o("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(o,c,l){(function(d){(function(){function p(){let u;try{u=l.storage.getItem("debug")}catch{}return!u&&typeof d<"u"&&"env"in d&&(u=d.env.DEBUG),u}l.formatArgs=function(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+c.exports.humanize(this.diff),!this.useColors)return;const f="color: "+this.color;u.splice(1,0,f,"color: inherit");let x=0,b=0;u[0].replace(/%[a-zA-Z%]/g,j=>{j==="%%"||(x++,j==="%c"&&(b=x))}),u.splice(b,0,f)},l.save=function(u){try{u?l.storage.setItem("debug",u):l.storage.removeItem("debug")}catch{}},l.load=p,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||(()=>{}),c.exports=o("./common")(l);const{formatters:m}=c.exports;m.j=function(u){try{return JSON.stringify(u)}catch(f){return"[UnexpectedJSONParseError]: "+f.message}}}).call(this)}).call(this,o("_process"))},{"./common":5,_process:12}],5:[function(o,c){c.exports=function(l){function d(u){function f(...j){if(!f.enabled)return;const A=f,v=+new Date,I=v-(x||v);A.diff=I,A.prev=x,A.curr=v,x=v,j[0]=d.coerce(j[0]),typeof j[0]!="string"&&j.unshift("%O");let g=0;j[0]=j[0].replace(/%([a-zA-Z%])/g,(_,T)=>{if(_==="%%")return"%";g++;const E=d.formatters[T];if(typeof E=="function"){const C=j[g];_=E.call(A,C),j.splice(g,1),g--}return _}),d.formatArgs.call(A,j),(A.log||d.log).apply(A,j)}let x,b=null;return f.namespace=u,f.useColors=d.useColors(),f.color=d.selectColor(u),f.extend=p,f.destroy=d.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>b===null?d.enabled(u):b,set:j=>{b=j}}),typeof d.init=="function"&&d.init(f),f}function p(u,f){const x=d(this.namespace+(typeof f>"u"?":":f)+u);return x.log=this.log,x}function m(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}return d.debug=d,d.default=d,d.coerce=function(u){return u instanceof Error?u.stack||u.message:u},d.disable=function(){const u=[...d.names.map(m),...d.skips.map(m).map(f=>"-"+f)].join(",");return d.enable(""),u},d.enable=function(u){d.save(u),d.names=[],d.skips=[];let f;const x=(typeof u=="string"?u:"").split(/[\s,]+/),b=x.length;for(f=0;f<b;f++)x[f]&&(u=x[f].replace(/\*/g,".*?"),u[0]==="-"?d.skips.push(new RegExp("^"+u.substr(1)+"$")):d.names.push(new RegExp("^"+u+"$")))},d.enabled=function(u){if(u[u.length-1]==="*")return!0;let f,x;for(f=0,x=d.skips.length;f<x;f++)if(d.skips[f].test(u))return!1;for(f=0,x=d.names.length;f<x;f++)if(d.names[f].test(u))return!0;return!1},d.humanize=o("ms"),d.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=>{d[u]=l[u]}),d.names=[],d.skips=[],d.formatters={},d.selectColor=function(u){let f=0;for(let x=0;x<u.length;x++)f=(f<<5)-f+u.charCodeAt(x),f|=0;return d.colors[r(f)%d.colors.length]},d.enable(d.load()),d}},{ms:11}],6:[function(o,c){function l(d,p){for(const m in p)Object.defineProperty(d,m,{value:p[m],enumerable:!0,configurable:!0});return d}c.exports=function(d,p,m){if(!d||typeof d=="string")throw new TypeError("Please pass an Error to err-code");m||(m={}),typeof p=="object"&&(m=p,p=""),p&&(m.code=p);try{return l(d,m)}catch{m.message=d.message,m.stack=d.stack;const f=function(){};return f.prototype=Object.create(Object.getPrototypeOf(d)),l(new f,m)}}},{}],7:[function(o,c){function l(S){console&&console.warn&&console.warn(S)}function d(){d.init.call(this)}function p(S){if(typeof S!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof S)}function m(S){return S._maxListeners===void 0?d.defaultMaxListeners:S._maxListeners}function u(S,R,O,B){var z,G,q;if(p(O),G=S._events,G===void 0?(G=S._events=Object.create(null),S._eventsCount=0):(G.newListener!==void 0&&(S.emit("newListener",R,O.listener?O.listener:O),G=S._events),q=G[R]),q===void 0)q=G[R]=O,++S._eventsCount;else if(typeof q=="function"?q=G[R]=B?[O,q]:[q,O]:B?q.unshift(O):q.push(O),z=m(S),0<z&&q.length>z&&!q.warned){q.warned=!0;var W=new Error("Possible EventEmitter memory leak detected. "+q.length+" "+(R+" listeners added. Use emitter.setMaxListeners() to increase limit"));W.name="MaxListenersExceededWarning",W.emitter=S,W.type=R,W.count=q.length,l(W)}return S}function f(){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 x(S,R,O){var B={fired:!1,wrapFn:void 0,target:S,type:R,listener:O},z=f.bind(B);return z.listener=O,B.wrapFn=z,z}function b(S,R,O){var B=S._events;if(B===void 0)return[];var z=B[R];return z===void 0?[]:typeof z=="function"?O?[z.listener||z]:[z]:O?I(z):A(z,z.length)}function j(S){var R=this._events;if(R!==void 0){var O=R[S];if(typeof O=="function")return 1;if(O!==void 0)return O.length}return 0}function A(S,R){for(var O=Array(R),B=0;B<R;++B)O[B]=S[B];return O}function v(S,R){for(;R+1<S.length;R++)S[R]=S[R+1];S.pop()}function I(S){for(var R=Array(S.length),O=0;O<R.length;++O)R[O]=S[O].listener||S[O];return R}function g(S,R,O){typeof S.on=="function"&&k(S,"error",R,O)}function k(S,R,O,B){if(typeof S.on=="function")B.once?S.once(R,O):S.on(R,O);else if(typeof S.addEventListener=="function")S.addEventListener(R,function z(G){B.once&&S.removeEventListener(R,z),O(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof S)}var _,T=typeof Reflect=="object"?Reflect:null,E=T&&typeof T.apply=="function"?T.apply:function(S,R,O){return Function.prototype.apply.call(S,R,O)};_=T&&typeof T.ownKeys=="function"?T.ownKeys:Object.getOwnPropertySymbols?function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:function(S){return Object.getOwnPropertyNames(S)};var C=Number.isNaN||function(S){return S!==S};c.exports=d,c.exports.once=function(S,R){return new Promise(function(O,B){function z(q){S.removeListener(R,G),B(q)}function G(){typeof S.removeListener=="function"&&S.removeListener("error",z),O([].slice.call(arguments))}k(S,R,G,{once:!0}),R!=="error"&&g(S,z,{once:!0})})},d.EventEmitter=d,d.prototype._events=void 0,d.prototype._eventsCount=0,d.prototype._maxListeners=void 0;var M=10;Object.defineProperty(d,"defaultMaxListeners",{enumerable:!0,get:function(){return M},set:function(S){if(typeof S!="number"||0>S||C(S))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+S+".");M=S}}),d.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},d.prototype.setMaxListeners=function(S){if(typeof S!="number"||0>S||C(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},d.prototype.getMaxListeners=function(){return m(this)},d.prototype.emit=function(S){for(var R=[],O=1;O<arguments.length;O++)R.push(arguments[O]);var B=S==="error",z=this._events;if(z!==void 0)B=B&&z.error===void 0;else if(!B)return!1;if(B){var G;if(0<R.length&&(G=R[0]),G instanceof Error)throw G;var q=new Error("Unhandled error."+(G?" ("+G.message+")":""));throw q.context=G,q}var W=z[S];if(W===void 0)return!1;if(typeof W=="function")E(W,this,R);else for(var V=W.length,$=A(W,V),O=0;O<V;++O)E($[O],this,R);return!0},d.prototype.addListener=function(S,R){return u(this,S,R,!1)},d.prototype.on=d.prototype.addListener,d.prototype.prependListener=function(S,R){return u(this,S,R,!0)},d.prototype.once=function(S,R){return p(R),this.on(S,x(this,S,R)),this},d.prototype.prependOnceListener=function(S,R){return p(R),this.prependListener(S,x(this,S,R)),this},d.prototype.removeListener=function(S,R){var O,B,z,G,q;if(p(R),B=this._events,B===void 0)return this;if(O=B[S],O===void 0)return this;if(O===R||O.listener===R)--this._eventsCount==0?this._events=Object.create(null):(delete B[S],B.removeListener&&this.emit("removeListener",S,O.listener||R));else if(typeof O!="function"){for(z=-1,G=O.length-1;0<=G;G--)if(O[G]===R||O[G].listener===R){q=O[G].listener,z=G;break}if(0>z)return this;z===0?O.shift():v(O,z),O.length===1&&(B[S]=O[0]),B.removeListener!==void 0&&this.emit("removeListener",S,q||R)}return this},d.prototype.off=d.prototype.removeListener,d.prototype.removeAllListeners=function(S){var R,O,B;if(O=this._events,O===void 0)return this;if(O.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):O[S]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete O[S]),this;if(arguments.length===0){var z,G=Object.keys(O);for(B=0;B<G.length;++B)z=G[B],z!=="removeListener"&&this.removeAllListeners(z);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(R=O[S],typeof R=="function")this.removeListener(S,R);else if(R!==void 0)for(B=R.length-1;0<=B;B--)this.removeListener(S,R[B]);return this},d.prototype.listeners=function(S){return b(this,S,!0)},d.prototype.rawListeners=function(S){return b(this,S,!1)},d.listenerCount=function(S,R){return typeof S.listenerCount=="function"?S.listenerCount(R):j.call(S,R)},d.prototype.listenerCount=j,d.prototype.eventNames=function(){return 0<this._eventsCount?_(this._events):[]}},{}],8:[function(o,c){c.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(o,c,l){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */l.read=function(d,p,m,u,f){var x,b,j=8*f-u-1,A=(1<<j)-1,v=A>>1,I=-7,g=m?f-1:0,k=m?-1:1,_=d[p+g];for(g+=k,x=_&(1<<-I)-1,_>>=-I,I+=j;0<I;x=256*x+d[p+g],g+=k,I-=8);for(b=x&(1<<-I)-1,x>>=-I,I+=u;0<I;b=256*b+d[p+g],g+=k,I-=8);if(x===0)x=1-v;else{if(x===A)return b?NaN:(_?-1:1)*(1/0);b+=i(2,u),x-=v}return(_?-1:1)*b*i(2,x-u)},l.write=function(d,p,m,u,f,x){var b,j,A,v=Math.LN2,I=Math.log,g=8*x-f-1,k=(1<<g)-1,_=k>>1,T=f===23?i(2,-24)-i(2,-77):0,E=u?0:x-1,C=u?1:-1,M=0>p||p===0&&0>1/p?1:0;for(p=r(p),isNaN(p)||p===1/0?(j=isNaN(p)?1:0,b=k):(b=s(I(p)/v),1>p*(A=i(2,-b))&&(b--,A*=2),p+=1<=b+_?T/A:T*i(2,1-_),2<=p*A&&(b++,A/=2),b+_>=k?(j=0,b=k):1<=b+_?(j=(p*A-1)*i(2,f),b+=_):(j=p*i(2,_-1)*i(2,f),b=0));8<=f;d[m+E]=255&j,E+=C,j/=256,f-=8);for(b=b<<f|j,g+=f;0<g;d[m+E]=255&b,E+=C,b/=256,g-=8);d[m+E-C]|=128*M}},{}],10:[function(o,c){c.exports=typeof Object.create=="function"?function(l,d){d&&(l.super_=d,l.prototype=Object.create(d.prototype,{constructor:{value:l,enumerable:!1,writable:!0,configurable:!0}}))}:function(l,d){if(d){l.super_=d;var p=function(){};p.prototype=d.prototype,l.prototype=new p,l.prototype.constructor=l}}},{}],11:[function(o,c){var l=Math.round;function d(f){if(f+="",!(100<f.length)){var x=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(x){var b=parseFloat(x[1]),j=(x[2]||"ms").toLowerCase();return j==="years"||j==="year"||j==="yrs"||j==="yr"||j==="y"?315576e5*b:j==="weeks"||j==="week"||j==="w"?6048e5*b:j==="days"||j==="day"||j==="d"?864e5*b:j==="hours"||j==="hour"||j==="hrs"||j==="hr"||j==="h"?36e5*b:j==="minutes"||j==="minute"||j==="mins"||j==="min"||j==="m"?6e4*b:j==="seconds"||j==="second"||j==="secs"||j==="sec"||j==="s"?1e3*b:j==="milliseconds"||j==="millisecond"||j==="msecs"||j==="msec"||j==="ms"?b:void 0}}}function p(f){var x=r(f);return 864e5<=x?l(f/864e5)+"d":36e5<=x?l(f/36e5)+"h":6e4<=x?l(f/6e4)+"m":1e3<=x?l(f/1e3)+"s":f+"ms"}function m(f){var x=r(f);return 864e5<=x?u(f,x,864e5,"day"):36e5<=x?u(f,x,36e5,"hour"):6e4<=x?u(f,x,6e4,"minute"):1e3<=x?u(f,x,1e3,"second"):f+" ms"}function u(f,x,b,j){return l(f/b)+" "+j+(x>=1.5*b?"s":"")}c.exports=function(f,x){x=x||{};var b=typeof f;if(b=="string"&&0<f.length)return d(f);if(b==="number"&&isFinite(f))return x.long?m(f):p(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))}},{}],12:[function(o,c){function l(){throw new Error("setTimeout has not been defined")}function d(){throw new Error("clearTimeout has not been defined")}function p(T){if(j===setTimeout)return setTimeout(T,0);if((j===l||!j)&&setTimeout)return j=setTimeout,setTimeout(T,0);try{return j(T,0)}catch{try{return j.call(null,T,0)}catch{return j.call(this,T,0)}}}function m(T){if(A===clearTimeout)return clearTimeout(T);if((A===d||!A)&&clearTimeout)return A=clearTimeout,clearTimeout(T);try{return A(T)}catch{try{return A.call(null,T)}catch{return A.call(this,T)}}}function u(){k&&I&&(k=!1,I.length?g=I.concat(g):_=-1,g.length&&f())}function f(){if(!k){var T=p(u);k=!0;for(var E=g.length;E;){for(I=g,g=[];++_<E;)I&&I[_].run();_=-1,E=g.length}I=null,k=!1,m(T)}}function x(T,E){this.fun=T,this.array=E}function b(){}var j,A,v=c.exports={};(function(){try{j=typeof setTimeout=="function"?setTimeout:l}catch{j=l}try{A=typeof clearTimeout=="function"?clearTimeout:d}catch{A=d}})();var I,g=[],k=!1,_=-1;v.nextTick=function(T){var E=Array(arguments.length-1);if(1<arguments.length)for(var C=1;C<arguments.length;C++)E[C-1]=arguments[C];g.push(new x(T,E)),g.length!==1||k||p(f)},x.prototype.run=function(){this.fun.apply(null,this.array)},v.title="browser",v.browser=!0,v.env={},v.argv=[],v.version="",v.versions={},v.on=b,v.addListener=b,v.once=b,v.off=b,v.removeListener=b,v.removeAllListeners=b,v.emit=b,v.prependListener=b,v.prependOnceListener=b,v.listeners=function(){return[]},v.binding=function(){throw new Error("process.binding is not supported")},v.cwd=function(){return"/"},v.chdir=function(){throw new Error("process.chdir is not supported")},v.umask=function(){return 0}},{}],13:[function(o,c){(function(l){(function(){/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let d;c.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window>"u"?l:window):p=>(d||(d=Promise.resolve())).then(p).catch(m=>setTimeout(()=>{throw m},0))}).call(this)}).call(this,typeof Qe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Qe)},{}],14:[function(o,c){(function(l,d){(function(){var p=o("safe-buffer").Buffer,m=d.crypto||d.msCrypto;c.exports=m&&m.getRandomValues?function(u,f){if(u>4294967295)throw new RangeError("requested too many random bytes");var x=p.allocUnsafe(u);if(0<u)if(65536<u)for(var b=0;b<u;b+=65536)m.getRandomValues(x.slice(b,b+65536));else m.getRandomValues(x);return typeof f=="function"?l.nextTick(function(){f(null,x)}):x}:function(){throw new Error(`Secure random number generation is not supported by this browser.
102
- Use Chrome, Firefox or Internet Explorer 11`)}}).call(this)}).call(this,o("_process"),typeof Qe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Qe)},{_process:12,"safe-buffer":30}],15:[function(o,c){function l(b,j){b.prototype=Object.create(j.prototype),b.prototype.constructor=b,b.__proto__=j}function d(b,j,A){function v(g,k,_){return typeof j=="string"?j:j(g,k,_)}A||(A=Error);var I=(function(g){function k(_,T,E){return g.call(this,v(_,T,E))||this}return l(k,g),k})(A);I.prototype.name=A.name,I.prototype.code=b,x[b]=I}function p(b,j){if(Array.isArray(b)){var A=b.length;return b=b.map(function(v){return v+""}),2<A?"one of ".concat(j," ").concat(b.slice(0,A-1).join(", "),", or ")+b[A-1]:A===2?"one of ".concat(j," ").concat(b[0]," or ").concat(b[1]):"of ".concat(j," ").concat(b[0])}return"of ".concat(j," ").concat(b+"")}function m(b,j,A){return b.substr(0,j.length)===j}function u(b,j,A){return(A===void 0||A>b.length)&&(A=b.length),b.substring(A-j.length,A)===j}function f(b,j,A){return typeof A!="number"&&(A=0),!(A+j.length>b.length)&&b.indexOf(j,A)!==-1}var x={};d("ERR_INVALID_OPT_VALUE",function(b,j){return'The value "'+j+'" is invalid for option "'+b+'"'},TypeError),d("ERR_INVALID_ARG_TYPE",function(b,j,A){var v;typeof j=="string"&&m(j,"not ")?(v="must not be",j=j.replace(/^not /,"")):v="must be";var I;if(u(b," argument"))I="The ".concat(b," ").concat(v," ").concat(p(j,"type"));else{var g=f(b,".")?"property":"argument";I='The "'.concat(b,'" ').concat(g," ").concat(v," ").concat(p(j,"type"))}return I+=". Received type ".concat(typeof A),I},TypeError),d("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),d("ERR_METHOD_NOT_IMPLEMENTED",function(b){return"The "+b+" method is not implemented"}),d("ERR_STREAM_PREMATURE_CLOSE","Premature close"),d("ERR_STREAM_DESTROYED",function(b){return"Cannot call "+b+" after a stream was destroyed"}),d("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),d("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),d("ERR_STREAM_WRITE_AFTER_END","write after end"),d("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),d("ERR_UNKNOWN_ENCODING",function(b){return"Unknown encoding: "+b},TypeError),d("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),c.exports.codes=x},{}],16:[function(o,c){(function(l){(function(){function d(v){return this instanceof d?(f.call(this,v),x.call(this,v),this.allowHalfOpen=!0,void(v&&(v.readable===!1&&(this.readable=!1),v.writable===!1&&(this.writable=!1),v.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",p))))):new d(v)}function p(){this._writableState.ended||l.nextTick(m,this)}function m(v){v.end()}var u=Object.keys||function(v){var I=[];for(var g in v)I.push(g);return I};c.exports=d;var f=o("./_stream_readable"),x=o("./_stream_writable");o("inherits")(d,f);for(var b,j=u(x.prototype),A=0;A<j.length;A++)b=j[A],d.prototype[b]||(d.prototype[b]=x.prototype[b]);Object.defineProperty(d.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(d.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(d.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(d.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._writableState!==void 0&&this._readableState.destroyed&&this._writableState.destroyed},set:function(v){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=v,this._writableState.destroyed=v)}})}).call(this)}).call(this,o("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(o,c){function l(p){return this instanceof l?void d.call(this,p):new l(p)}c.exports=l;var d=o("./_stream_transform");o("inherits")(l,d),l.prototype._transform=function(p,m,u){u(null,p)}},{"./_stream_transform":19,inherits:10}],18:[function(o,c){(function(l,d){(function(){function p(N){return X.from(N)}function m(N){return X.isBuffer(N)||N instanceof Z}function u(N,a,h){return typeof N.prependListener=="function"?N.prependListener(a,h):void(N._events&&N._events[a]?Array.isArray(N._events[a])?N._events[a].unshift(h):N._events[a]=[h,N._events[a]]:N.on(a,h))}function f(N,a,h){V=V||o("./_stream_duplex"),N=N||{},typeof h!="boolean"&&(h=a instanceof V),this.objectMode=!!N.objectMode,h&&(this.objectMode=this.objectMode||!!N.readableObjectMode),this.highWaterMark=K(this,N,"readableHighWaterMark",h),this.buffer=new ge,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=N.emitClose!==!1,this.autoDestroy=!!N.autoDestroy,this.destroyed=!1,this.defaultEncoding=N.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,N.encoding&&(!we&&(we=o("string_decoder/").StringDecoder),this.decoder=new we(N.encoding),this.encoding=N.encoding)}function x(N){if(V=V||o("./_stream_duplex"),!(this instanceof x))return new x(N);var a=this instanceof V;this._readableState=new f(N,this,a),this.readable=!0,N&&(typeof N.read=="function"&&(this._read=N.read),typeof N.destroy=="function"&&(this._destroy=N.destroy)),ne.call(this)}function b(N,a,h,y,L){$("readableAddChunk",a);var P=N._readableState;if(a===null)P.reading=!1,g(N,P);else{var F;if(L||(F=A(P,a)),F)H(N,F);else if(!(P.objectMode||a&&0<a.length))y||(P.reading=!1,T(N,P));else if(typeof a=="string"||P.objectMode||Object.getPrototypeOf(a)===X.prototype||(a=p(a)),y)P.endEmitted?H(N,new U):j(N,P,a,!0);else if(P.ended)H(N,new oe);else{if(P.destroyed)return!1;P.reading=!1,P.decoder&&!h?(a=P.decoder.write(a),P.objectMode||a.length!==0?j(N,P,a,!1):T(N,P)):j(N,P,a,!1)}}return!P.ended&&(P.length<P.highWaterMark||P.length===0)}function j(N,a,h,y){a.flowing&&a.length===0&&!a.sync?(a.awaitDrain=0,N.emit("data",h)):(a.length+=a.objectMode?1:h.length,y?a.buffer.unshift(h):a.buffer.push(h),a.needReadable&&k(N)),T(N,a)}function A(N,a){var h;return m(a)||typeof a=="string"||a===void 0||N.objectMode||(h=new Q("chunk",["string","Buffer","Uint8Array"],a)),h}function v(N){return 1073741824<=N?N=1073741824:(N--,N|=N>>>1,N|=N>>>2,N|=N>>>4,N|=N>>>8,N|=N>>>16,N++),N}function I(N,a){return 0>=N||a.length===0&&a.ended?0:a.objectMode?1:N===N?(N>a.highWaterMark&&(a.highWaterMark=v(N)),N<=a.length?N:a.ended?a.length:(a.needReadable=!0,0)):a.flowing&&a.length?a.buffer.head.data.length:a.length}function g(N,a){if($("onEofChunk"),!a.ended){if(a.decoder){var h=a.decoder.end();h&&h.length&&(a.buffer.push(h),a.length+=a.objectMode?1:h.length)}a.ended=!0,a.sync?k(N):(a.needReadable=!1,!a.emittedReadable&&(a.emittedReadable=!0,_(N)))}}function k(N){var a=N._readableState;$("emitReadable",a.needReadable,a.emittedReadable),a.needReadable=!1,a.emittedReadable||($("emitReadable",a.flowing),a.emittedReadable=!0,l.nextTick(_,N))}function _(N){var a=N._readableState;$("emitReadable_",a.destroyed,a.length,a.ended),!a.destroyed&&(a.length||a.ended)&&(N.emit("readable"),a.emittedReadable=!1),a.needReadable=!a.flowing&&!a.ended&&a.length<=a.highWaterMark,B(N)}function T(N,a){a.readingMore||(a.readingMore=!0,l.nextTick(E,N,a))}function E(N,a){for(;!a.reading&&!a.ended&&(a.length<a.highWaterMark||a.flowing&&a.length===0);){var h=a.length;if($("maybeReadMore read 0"),N.read(0),h===a.length)break}a.readingMore=!1}function C(N){return function(){var a=N._readableState;$("pipeOnDrain",a.awaitDrain),a.awaitDrain&&a.awaitDrain--,a.awaitDrain===0&&ee(N,"data")&&(a.flowing=!0,B(N))}}function M(N){var a=N._readableState;a.readableListening=0<N.listenerCount("readable"),a.resumeScheduled&&!a.paused?a.flowing=!0:0<N.listenerCount("data")&&N.resume()}function S(N){$("readable nexttick read 0"),N.read(0)}function R(N,a){a.resumeScheduled||(a.resumeScheduled=!0,l.nextTick(O,N,a))}function O(N,a){$("resume",a.reading),a.reading||N.read(0),a.resumeScheduled=!1,N.emit("resume"),B(N),a.flowing&&!a.reading&&N.read(0)}function B(N){var a=N._readableState;for($("flow",a.flowing);a.flowing&&N.read()!==null;);}function z(N,a){if(a.length===0)return null;var h;return a.objectMode?h=a.buffer.shift():!N||N>=a.length?(h=a.decoder?a.buffer.join(""):a.buffer.length===1?a.buffer.first():a.buffer.concat(a.length),a.buffer.clear()):h=a.buffer.consume(N,a.decoder),h}function G(N){var a=N._readableState;$("endReadable",a.endEmitted),a.endEmitted||(a.ended=!0,l.nextTick(q,a,N))}function q(N,a){if($("endReadableNT",N.endEmitted,N.length),!N.endEmitted&&N.length===0&&(N.endEmitted=!0,a.readable=!1,a.emit("end"),N.autoDestroy)){var h=a._writableState;(!h||h.autoDestroy&&h.finished)&&a.destroy()}}function W(N,a){for(var h=0,y=N.length;h<y;h++)if(N[h]===a)return h;return-1}c.exports=x;var V;x.ReadableState=f;var $;o("events").EventEmitter;var ee=function(N,a){return N.listeners(a).length},ne=o("./internal/streams/stream"),X=o("buffer").Buffer,Z=d.Uint8Array||function(){},J=o("util");$=J&&J.debuglog?J.debuglog("stream"):function(){};var we,We,le,ge=o("./internal/streams/buffer_list"),ye=o("./internal/streams/destroy"),xe=o("./internal/streams/state"),K=xe.getHighWaterMark,Y=o("../errors").codes,Q=Y.ERR_INVALID_ARG_TYPE,oe=Y.ERR_STREAM_PUSH_AFTER_EOF,D=Y.ERR_METHOD_NOT_IMPLEMENTED,U=Y.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;o("inherits")(x,ne);var H=ye.errorOrDestroy,te=["error","close","destroy","pause","resume"];Object.defineProperty(x.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(N){this._readableState&&(this._readableState.destroyed=N)}}),x.prototype.destroy=ye.destroy,x.prototype._undestroy=ye.undestroy,x.prototype._destroy=function(N,a){a(N)},x.prototype.push=function(N,a){var h,y=this._readableState;return y.objectMode?h=!0:typeof N=="string"&&(a=a||y.defaultEncoding,a!==y.encoding&&(N=X.from(N,a),a=""),h=!0),b(this,N,a,!1,h)},x.prototype.unshift=function(N){return b(this,N,null,!0,!1)},x.prototype.isPaused=function(){return this._readableState.flowing===!1},x.prototype.setEncoding=function(N){we||(we=o("string_decoder/").StringDecoder);var a=new we(N);this._readableState.decoder=a,this._readableState.encoding=this._readableState.decoder.encoding;for(var h=this._readableState.buffer.head,y="";h!==null;)y+=a.write(h.data),h=h.next;return this._readableState.buffer.clear(),y!==""&&this._readableState.buffer.push(y),this._readableState.length=y.length,this},x.prototype.read=function(N){$("read",N),N=parseInt(N,10);var a=this._readableState,h=N;if(N!==0&&(a.emittedReadable=!1),N===0&&a.needReadable&&((a.highWaterMark===0?0<a.length:a.length>=a.highWaterMark)||a.ended))return $("read: emitReadable",a.length,a.ended),a.length===0&&a.ended?G(this):k(this),null;if(N=I(N,a),N===0&&a.ended)return a.length===0&&G(this),null;var y=a.needReadable;$("need readable",y),(a.length===0||a.length-N<a.highWaterMark)&&(y=!0,$("length less than watermark",y)),a.ended||a.reading?(y=!1,$("reading or ended",y)):y&&($("do read"),a.reading=!0,a.sync=!0,a.length===0&&(a.needReadable=!0),this._read(a.highWaterMark),a.sync=!1,!a.reading&&(N=I(h,a)));var L;return L=0<N?z(N,a):null,L===null?(a.needReadable=a.length<=a.highWaterMark,N=0):(a.length-=N,a.awaitDrain=0),a.length===0&&(!a.ended&&(a.needReadable=!0),h!==N&&a.ended&&G(this)),L!==null&&this.emit("data",L),L},x.prototype._read=function(){H(this,new D("_read()"))},x.prototype.pipe=function(N,a){function h(Mt,Ot){$("onunpipe"),Mt===fe&&Ot&&Ot.hasUnpiped===!1&&(Ot.hasUnpiped=!0,L())}function y(){$("onend"),N.end()}function L(){$("cleanup"),N.removeListener("close",se),N.removeListener("finish",he),N.removeListener("drain",Dt),N.removeListener("error",F),N.removeListener("unpipe",h),fe.removeListener("end",y),fe.removeListener("end",ve),fe.removeListener("data",P),ns=!0,ue.awaitDrain&&(!N._writableState||N._writableState.needDrain)&&Dt()}function P(Mt){$("ondata");var Ot=N.write(Mt);$("dest.write",Ot),Ot===!1&&((ue.pipesCount===1&&ue.pipes===N||1<ue.pipesCount&&W(ue.pipes,N)!==-1)&&!ns&&($("false write response, pause",ue.awaitDrain),ue.awaitDrain++),fe.pause())}function F(Mt){$("onerror",Mt),ve(),N.removeListener("error",F),ee(N,"error")===0&&H(N,Mt)}function se(){N.removeListener("finish",he),ve()}function he(){$("onfinish"),N.removeListener("close",se),ve()}function ve(){$("unpipe"),fe.unpipe(N)}var fe=this,ue=this._readableState;switch(ue.pipesCount){case 0:ue.pipes=N;break;case 1:ue.pipes=[ue.pipes,N];break;default:ue.pipes.push(N)}ue.pipesCount+=1,$("pipe count=%d opts=%j",ue.pipesCount,a);var De=(!a||a.end!==!1)&&N!==l.stdout&&N!==l.stderr,wt=De?y:ve;ue.endEmitted?l.nextTick(wt):fe.once("end",wt),N.on("unpipe",h);var Dt=C(fe);N.on("drain",Dt);var ns=!1;return fe.on("data",P),u(N,"error",F),N.once("close",se),N.once("finish",he),N.emit("pipe",fe),ue.flowing||($("pipe resume"),fe.resume()),N},x.prototype.unpipe=function(N){var a=this._readableState,h={hasUnpiped:!1};if(a.pipesCount===0)return this;if(a.pipesCount===1)return N&&N!==a.pipes?this:(N||(N=a.pipes),a.pipes=null,a.pipesCount=0,a.flowing=!1,N&&N.emit("unpipe",this,h),this);if(!N){var y=a.pipes,L=a.pipesCount;a.pipes=null,a.pipesCount=0,a.flowing=!1;for(var P=0;P<L;P++)y[P].emit("unpipe",this,{hasUnpiped:!1});return this}var F=W(a.pipes,N);return F===-1?this:(a.pipes.splice(F,1),a.pipesCount-=1,a.pipesCount===1&&(a.pipes=a.pipes[0]),N.emit("unpipe",this,h),this)},x.prototype.on=function(N,a){var h=ne.prototype.on.call(this,N,a),y=this._readableState;return N==="data"?(y.readableListening=0<this.listenerCount("readable"),y.flowing!==!1&&this.resume()):N=="readable"&&!y.endEmitted&&!y.readableListening&&(y.readableListening=y.needReadable=!0,y.flowing=!1,y.emittedReadable=!1,$("on readable",y.length,y.reading),y.length?k(this):!y.reading&&l.nextTick(S,this)),h},x.prototype.addListener=x.prototype.on,x.prototype.removeListener=function(N,a){var h=ne.prototype.removeListener.call(this,N,a);return N==="readable"&&l.nextTick(M,this),h},x.prototype.removeAllListeners=function(N){var a=ne.prototype.removeAllListeners.apply(this,arguments);return(N==="readable"||N===void 0)&&l.nextTick(M,this),a},x.prototype.resume=function(){var N=this._readableState;return N.flowing||($("resume"),N.flowing=!N.readableListening,R(this,N)),N.paused=!1,this},x.prototype.pause=function(){return $("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&($("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},x.prototype.wrap=function(N){var a=this,h=this._readableState,y=!1;for(var L in N.on("end",function(){if($("wrapped end"),h.decoder&&!h.ended){var F=h.decoder.end();F&&F.length&&a.push(F)}a.push(null)}),N.on("data",function(F){if($("wrapped data"),h.decoder&&(F=h.decoder.write(F)),!(h.objectMode&&F==null)&&(h.objectMode||F&&F.length)){var se=a.push(F);se||(y=!0,N.pause())}}),N)this[L]===void 0&&typeof N[L]=="function"&&(this[L]=(function(F){return function(){return N[F].apply(N,arguments)}})(L));for(var P=0;P<te.length;P++)N.on(te[P],this.emit.bind(this,te[P]));return this._read=function(F){$("wrapped _read",F),y&&(y=!1,N.resume())},this},typeof Symbol=="function"&&(x.prototype[Symbol.asyncIterator]=function(){return We===void 0&&(We=o("./internal/streams/async_iterator")),We(this)}),Object.defineProperty(x.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(x.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(x.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(N){this._readableState&&(this._readableState.flowing=N)}}),x._fromList=z,Object.defineProperty(x.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),typeof Symbol=="function"&&(x.from=function(N,a){return le===void 0&&(le=o("./internal/streams/from")),le(x,N,a)})}).call(this)}).call(this,o("_process"),typeof Qe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Qe)},{"../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(o,c){function l(v,I){var g=this._transformState;g.transforming=!1;var k=g.writecb;if(k===null)return this.emit("error",new x);g.writechunk=null,g.writecb=null,I!=null&&this.push(I),k(v);var _=this._readableState;_.reading=!1,(_.needReadable||_.length<_.highWaterMark)&&this._read(_.highWaterMark)}function d(v){return this instanceof d?(A.call(this,v),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,v&&(typeof v.transform=="function"&&(this._transform=v.transform),typeof v.flush=="function"&&(this._flush=v.flush)),void this.on("prefinish",p)):new d(v)}function p(){var v=this;typeof this._flush!="function"||this._readableState.destroyed?m(this,null,null):this._flush(function(I,g){m(v,I,g)})}function m(v,I,g){if(I)return v.emit("error",I);if(g!=null&&v.push(g),v._writableState.length)throw new j;if(v._transformState.transforming)throw new b;return v.push(null)}c.exports=d;var u=o("../errors").codes,f=u.ERR_METHOD_NOT_IMPLEMENTED,x=u.ERR_MULTIPLE_CALLBACK,b=u.ERR_TRANSFORM_ALREADY_TRANSFORMING,j=u.ERR_TRANSFORM_WITH_LENGTH_0,A=o("./_stream_duplex");o("inherits")(d,A),d.prototype.push=function(v,I){return this._transformState.needTransform=!1,A.prototype.push.call(this,v,I)},d.prototype._transform=function(v,I,g){g(new f("_transform()"))},d.prototype._write=function(v,I,g){var k=this._transformState;if(k.writecb=g,k.writechunk=v,k.writeencoding=I,!k.transforming){var _=this._readableState;(k.needTransform||_.needReadable||_.length<_.highWaterMark)&&this._read(_.highWaterMark)}},d.prototype._read=function(){var v=this._transformState;v.writechunk===null||v.transforming?v.needTransform=!0:(v.transforming=!0,this._transform(v.writechunk,v.writeencoding,v.afterTransform))},d.prototype._destroy=function(v,I){A.prototype._destroy.call(this,v,function(g){I(g)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(o,c){(function(l,d){(function(){function p(D){var U=this;this.next=null,this.entry=null,this.finish=function(){G(U,D)}}function m(D){return $.from(D)}function u(D){return $.isBuffer(D)||D instanceof ee}function f(){}function x(D,U,H){q=q||o("./_stream_duplex"),D=D||{},typeof H!="boolean"&&(H=U instanceof q),this.objectMode=!!D.objectMode,H&&(this.objectMode=this.objectMode||!!D.writableObjectMode),this.highWaterMark=Z(this,D,"writableHighWaterMark",H),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var te=D.decodeStrings===!1;this.decodeStrings=!te,this.defaultEncoding=D.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(N){T(U,N)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=D.emitClose!==!1,this.autoDestroy=!!D.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new p(this)}function b(D){q=q||o("./_stream_duplex");var U=this instanceof q;return U||oe.call(b,this)?(this._writableState=new x(D,this,U),this.writable=!0,D&&(typeof D.write=="function"&&(this._write=D.write),typeof D.writev=="function"&&(this._writev=D.writev),typeof D.destroy=="function"&&(this._destroy=D.destroy),typeof D.final=="function"&&(this._final=D.final)),void V.call(this)):new b(D)}function j(D,U){var H=new K;Q(D,H),l.nextTick(U,H)}function A(D,U,H,te){var N;return H===null?N=new xe:typeof H!="string"&&!U.objectMode&&(N=new we("chunk",["string","Buffer"],H)),!N||(Q(D,N),l.nextTick(te,N),!1)}function v(D,U,H){return D.objectMode||D.decodeStrings===!1||typeof U!="string"||(U=$.from(U,H)),U}function I(D,U,H,te,N,a){if(!H){var h=v(U,te,N);te!==h&&(H=!0,N="buffer",te=h)}var y=U.objectMode?1:te.length;U.length+=y;var L=U.length<U.highWaterMark;if(L||(U.needDrain=!0),U.writing||U.corked){var P=U.lastBufferedRequest;U.lastBufferedRequest={chunk:te,encoding:N,isBuf:H,callback:a,next:null},P?P.next=U.lastBufferedRequest:U.bufferedRequest=U.lastBufferedRequest,U.bufferedRequestCount+=1}else g(D,U,!1,y,te,N,a);return L}function g(D,U,H,te,N,a,h){U.writelen=te,U.writecb=h,U.writing=!0,U.sync=!0,U.destroyed?U.onwrite(new ye("write")):H?D._writev(N,U.onwrite):D._write(N,a,U.onwrite),U.sync=!1}function k(D,U,H,te,N){--U.pendingcb,H?(l.nextTick(N,te),l.nextTick(B,D,U),D._writableState.errorEmitted=!0,Q(D,te)):(N(te),D._writableState.errorEmitted=!0,Q(D,te),B(D,U))}function _(D){D.writing=!1,D.writecb=null,D.length-=D.writelen,D.writelen=0}function T(D,U){var H=D._writableState,te=H.sync,N=H.writecb;if(typeof N!="function")throw new le;if(_(H),U)k(D,H,te,U,N);else{var a=S(H)||D.destroyed;a||H.corked||H.bufferProcessing||!H.bufferedRequest||M(D,H),te?l.nextTick(E,D,H,a,N):E(D,H,a,N)}}function E(D,U,H,te){H||C(D,U),U.pendingcb--,te(),B(D,U)}function C(D,U){U.length===0&&U.needDrain&&(U.needDrain=!1,D.emit("drain"))}function M(D,U){U.bufferProcessing=!0;var H=U.bufferedRequest;if(D._writev&&H&&H.next){var te=U.bufferedRequestCount,N=Array(te),a=U.corkedRequestsFree;a.entry=H;for(var h=0,y=!0;H;)N[h]=H,H.isBuf||(y=!1),H=H.next,h+=1;N.allBuffers=y,g(D,U,!0,U.length,N,"",a.finish),U.pendingcb++,U.lastBufferedRequest=null,a.next?(U.corkedRequestsFree=a.next,a.next=null):U.corkedRequestsFree=new p(U),U.bufferedRequestCount=0}else{for(;H;){var L=H.chunk,P=H.encoding,F=H.callback,se=U.objectMode?1:L.length;if(g(D,U,!1,se,L,P,F),H=H.next,U.bufferedRequestCount--,U.writing)break}H===null&&(U.lastBufferedRequest=null)}U.bufferedRequest=H,U.bufferProcessing=!1}function S(D){return D.ending&&D.length===0&&D.bufferedRequest===null&&!D.finished&&!D.writing}function R(D,U){D._final(function(H){U.pendingcb--,H&&Q(D,H),U.prefinished=!0,D.emit("prefinish"),B(D,U)})}function O(D,U){U.prefinished||U.finalCalled||(typeof D._final!="function"||U.destroyed?(U.prefinished=!0,D.emit("prefinish")):(U.pendingcb++,U.finalCalled=!0,l.nextTick(R,D,U)))}function B(D,U){var H=S(U);if(H&&(O(D,U),U.pendingcb===0&&(U.finished=!0,D.emit("finish"),U.autoDestroy))){var te=D._readableState;(!te||te.autoDestroy&&te.endEmitted)&&D.destroy()}return H}function z(D,U,H){U.ending=!0,B(D,U),H&&(U.finished?l.nextTick(H):D.once("finish",H)),U.ended=!0,D.writable=!1}function G(D,U,H){var te=D.entry;for(D.entry=null;te;){var N=te.callback;U.pendingcb--,N(H),te=te.next}U.corkedRequestsFree.next=D}c.exports=b;var q;b.WritableState=x;var W={deprecate:o("util-deprecate")},V=o("./internal/streams/stream"),$=o("buffer").Buffer,ee=d.Uint8Array||function(){},ne=o("./internal/streams/destroy"),X=o("./internal/streams/state"),Z=X.getHighWaterMark,J=o("../errors").codes,we=J.ERR_INVALID_ARG_TYPE,We=J.ERR_METHOD_NOT_IMPLEMENTED,le=J.ERR_MULTIPLE_CALLBACK,ge=J.ERR_STREAM_CANNOT_PIPE,ye=J.ERR_STREAM_DESTROYED,xe=J.ERR_STREAM_NULL_VALUES,K=J.ERR_STREAM_WRITE_AFTER_END,Y=J.ERR_UNKNOWN_ENCODING,Q=ne.errorOrDestroy;o("inherits")(b,V),x.prototype.getBuffer=function(){for(var D=this.bufferedRequest,U=[];D;)U.push(D),D=D.next;return U},(function(){try{Object.defineProperty(x.prototype,"buffer",{get:W.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var oe;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(oe=Function.prototype[Symbol.hasInstance],Object.defineProperty(b,Symbol.hasInstance,{value:function(D){return!!oe.call(this,D)||this===b&&D&&D._writableState instanceof x}})):oe=function(D){return D instanceof this},b.prototype.pipe=function(){Q(this,new ge)},b.prototype.write=function(D,U,H){var te=this._writableState,N=!1,a=!te.objectMode&&u(D);return a&&!$.isBuffer(D)&&(D=m(D)),typeof U=="function"&&(H=U,U=null),a?U="buffer":!U&&(U=te.defaultEncoding),typeof H!="function"&&(H=f),te.ending?j(this,H):(a||A(this,te,D,H))&&(te.pendingcb++,N=I(this,te,a,D,U,H)),N},b.prototype.cork=function(){this._writableState.corked++},b.prototype.uncork=function(){var D=this._writableState;D.corked&&(D.corked--,!D.writing&&!D.corked&&!D.bufferProcessing&&D.bufferedRequest&&M(this,D))},b.prototype.setDefaultEncoding=function(D){if(typeof D=="string"&&(D=D.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((D+"").toLowerCase())))throw new Y(D);return this._writableState.defaultEncoding=D,this},Object.defineProperty(b.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(b.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),b.prototype._write=function(D,U,H){H(new We("_write()"))},b.prototype._writev=null,b.prototype.end=function(D,U,H){var te=this._writableState;return typeof D=="function"?(H=D,D=null,U=null):typeof U=="function"&&(H=U,U=null),D!=null&&this.write(D,U),te.corked&&(te.corked=1,this.uncork()),te.ending||z(this,te,H),this},Object.defineProperty(b.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(b.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(D){this._writableState&&(this._writableState.destroyed=D)}}),b.prototype.destroy=ne.destroy,b.prototype._undestroy=ne.undestroy,b.prototype._destroy=function(D,U){U(D)}}).call(this)}).call(this,o("_process"),typeof Qe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Qe)},{"../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(o,c){(function(l){(function(){function d(C,M,S){return M in C?Object.defineProperty(C,M,{value:S,enumerable:!0,configurable:!0,writable:!0}):C[M]=S,C}function p(C,M){return{value:C,done:M}}function m(C){var M=C[j];if(M!==null){var S=C[_].read();S!==null&&(C[g]=null,C[j]=null,C[A]=null,M(p(S,!1)))}}function u(C){l.nextTick(m,C)}function f(C,M){return function(S,R){C.then(function(){return M[I]?void S(p(void 0,!0)):void M[k](S,R)},R)}}var x,b=o("./end-of-stream"),j=Symbol("lastResolve"),A=Symbol("lastReject"),v=Symbol("error"),I=Symbol("ended"),g=Symbol("lastPromise"),k=Symbol("handlePromise"),_=Symbol("stream"),T=Object.getPrototypeOf(function(){}),E=Object.setPrototypeOf((x={get stream(){return this[_]},next:function(){var C=this,M=this[v];if(M!==null)return Promise.reject(M);if(this[I])return Promise.resolve(p(void 0,!0));if(this[_].destroyed)return new Promise(function(B,z){l.nextTick(function(){C[v]?z(C[v]):B(p(void 0,!0))})});var S,R=this[g];if(R)S=new Promise(f(R,this));else{var O=this[_].read();if(O!==null)return Promise.resolve(p(O,!1));S=new Promise(this[k])}return this[g]=S,S}},d(x,Symbol.asyncIterator,function(){return this}),d(x,"return",function(){var C=this;return new Promise(function(M,S){C[_].destroy(null,function(R){return R?void S(R):void M(p(void 0,!0))})})}),x),T);c.exports=function(C){var M,S=Object.create(E,(M={},d(M,_,{value:C,writable:!0}),d(M,j,{value:null,writable:!0}),d(M,A,{value:null,writable:!0}),d(M,v,{value:null,writable:!0}),d(M,I,{value:C._readableState.endEmitted,writable:!0}),d(M,k,{value:function(R,O){var B=S[_].read();B?(S[g]=null,S[j]=null,S[A]=null,R(p(B,!1))):(S[j]=R,S[A]=O)},writable:!0}),M));return S[g]=null,b(C,function(R){if(R&&R.code!=="ERR_STREAM_PREMATURE_CLOSE"){var O=S[A];return O!==null&&(S[g]=null,S[j]=null,S[A]=null,O(R)),void(S[v]=R)}var B=S[j];B!==null&&(S[g]=null,S[j]=null,S[A]=null,B(p(void 0,!0))),S[I]=!0}),C.on("readable",u.bind(null,S)),S}}).call(this)}).call(this,o("_process"))},{"./end-of-stream":24,_process:12}],22:[function(o,c){function l(g,k){var _=Object.keys(g);if(Object.getOwnPropertySymbols){var T=Object.getOwnPropertySymbols(g);k&&(T=T.filter(function(E){return Object.getOwnPropertyDescriptor(g,E).enumerable})),_.push.apply(_,T)}return _}function d(g){for(var k,_=1;_<arguments.length;_++)k=arguments[_]==null?{}:arguments[_],_%2?l(Object(k),!0).forEach(function(T){p(g,T,k[T])}):Object.getOwnPropertyDescriptors?Object.defineProperties(g,Object.getOwnPropertyDescriptors(k)):l(Object(k)).forEach(function(T){Object.defineProperty(g,T,Object.getOwnPropertyDescriptor(k,T))});return g}function p(g,k,_){return k in g?Object.defineProperty(g,k,{value:_,enumerable:!0,configurable:!0,writable:!0}):g[k]=_,g}function m(g,k){if(!(g instanceof k))throw new TypeError("Cannot call a class as a function")}function u(g,k){for(var _,T=0;T<k.length;T++)_=k[T],_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(g,_.key,_)}function f(g,k,_){return k&&u(g.prototype,k),g}function x(g,k,_){j.prototype.copy.call(g,k,_)}var b=o("buffer"),j=b.Buffer,A=o("util"),v=A.inspect,I=v&&v.custom||"inspect";c.exports=(function(){function g(){m(this,g),this.head=null,this.tail=null,this.length=0}return f(g,[{key:"push",value:function(k){var _={data:k,next:null};0<this.length?this.tail.next=_:this.head=_,this.tail=_,++this.length}},{key:"unshift",value:function(k){var _={data:k,next:this.head};this.length===0&&(this.tail=_),this.head=_,++this.length}},{key:"shift",value:function(){if(this.length!==0){var k=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,k}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(k){if(this.length===0)return"";for(var _=this.head,T=""+_.data;_=_.next;)T+=k+_.data;return T}},{key:"concat",value:function(k){if(this.length===0)return j.alloc(0);for(var _=j.allocUnsafe(k>>>0),T=this.head,E=0;T;)x(T.data,_,E),E+=T.data.length,T=T.next;return _}},{key:"consume",value:function(k,_){var T;return k<this.head.data.length?(T=this.head.data.slice(0,k),this.head.data=this.head.data.slice(k)):k===this.head.data.length?T=this.shift():T=_?this._getString(k):this._getBuffer(k),T}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(k){var _=this.head,T=1,E=_.data;for(k-=E.length;_=_.next;){var C=_.data,M=k>C.length?C.length:k;if(E+=M===C.length?C:C.slice(0,k),k-=M,k===0){M===C.length?(++T,this.head=_.next?_.next:this.tail=null):(this.head=_,_.data=C.slice(M));break}++T}return this.length-=T,E}},{key:"_getBuffer",value:function(k){var _=j.allocUnsafe(k),T=this.head,E=1;for(T.data.copy(_),k-=T.data.length;T=T.next;){var C=T.data,M=k>C.length?C.length:k;if(C.copy(_,_.length-k,0,M),k-=M,k===0){M===C.length?(++E,this.head=T.next?T.next:this.tail=null):(this.head=T,T.data=C.slice(M));break}++E}return this.length-=E,_}},{key:I,value:function(k,_){return v(this,d({},_,{depth:0,customInspect:!1}))}}]),g})()},{buffer:3,util:2}],23:[function(o,c){(function(l){(function(){function d(u,f){m(u,f),p(u)}function p(u){u._writableState&&!u._writableState.emitClose||u._readableState&&!u._readableState.emitClose||u.emit("close")}function m(u,f){u.emit("error",f)}c.exports={destroy:function(u,f){var x=this,b=this._readableState&&this._readableState.destroyed,j=this._writableState&&this._writableState.destroyed;return b||j?(f?f(u):u&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,l.nextTick(m,this,u)):l.nextTick(m,this,u)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(u||null,function(A){!f&&A?x._writableState?x._writableState.errorEmitted?l.nextTick(p,x):(x._writableState.errorEmitted=!0,l.nextTick(d,x,A)):l.nextTick(d,x,A):f?(l.nextTick(p,x),f(A)):l.nextTick(p,x)}),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,f){var x=u._readableState,b=u._writableState;x&&x.autoDestroy||b&&b.autoDestroy?u.destroy(f):u.emit("error",f)}}}).call(this)}).call(this,o("_process"))},{_process:12}],24:[function(o,c){function l(f){var x=!1;return function(){if(!x){x=!0;for(var b=arguments.length,j=Array(b),A=0;A<b;A++)j[A]=arguments[A];f.apply(this,j)}}}function d(){}function p(f){return f.setHeader&&typeof f.abort=="function"}function m(f,x,b){if(typeof x=="function")return m(f,null,x);x||(x={}),b=l(b||d);var j=x.readable||x.readable!==!1&&f.readable,A=x.writable||x.writable!==!1&&f.writable,v=function(){f.writable||g()},I=f._writableState&&f._writableState.finished,g=function(){A=!1,I=!0,j||b.call(f)},k=f._readableState&&f._readableState.endEmitted,_=function(){j=!1,k=!0,A||b.call(f)},T=function(M){b.call(f,M)},E=function(){var M;return j&&!k?(f._readableState&&f._readableState.ended||(M=new u),b.call(f,M)):A&&!I?(f._writableState&&f._writableState.ended||(M=new u),b.call(f,M)):void 0},C=function(){f.req.on("finish",g)};return p(f)?(f.on("complete",g),f.on("abort",E),f.req?C():f.on("request",C)):A&&!f._writableState&&(f.on("end",v),f.on("close",v)),f.on("end",_),f.on("finish",g),x.error!==!1&&f.on("error",T),f.on("close",E),function(){f.removeListener("complete",g),f.removeListener("abort",E),f.removeListener("request",C),f.req&&f.req.removeListener("finish",g),f.removeListener("end",v),f.removeListener("close",v),f.removeListener("finish",g),f.removeListener("end",_),f.removeListener("error",T),f.removeListener("close",E)}}var u=o("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;c.exports=m},{"../../../errors":15}],25:[function(o,c){c.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(o,c){function l(I){var g=!1;return function(){g||(g=!0,I.apply(void 0,arguments))}}function d(I){if(I)throw I}function p(I){return I.setHeader&&typeof I.abort=="function"}function m(I,g,k,_){_=l(_);var T=!1;I.on("close",function(){T=!0}),b===void 0&&(b=o("./end-of-stream")),b(I,{readable:g,writable:k},function(C){return C?_(C):(T=!0,void _())});var E=!1;return function(C){if(!T)return E?void 0:(E=!0,p(I)?I.abort():typeof I.destroy=="function"?I.destroy():void _(C||new v("pipe")))}}function u(I){I()}function f(I,g){return I.pipe(g)}function x(I){return I.length&&typeof I[I.length-1]=="function"?I.pop():d}var b,j=o("../../../errors").codes,A=j.ERR_MISSING_ARGS,v=j.ERR_STREAM_DESTROYED;c.exports=function(){for(var I=arguments.length,g=Array(I),k=0;k<I;k++)g[k]=arguments[k];var _=x(g);if(Array.isArray(g[0])&&(g=g[0]),2>g.length)throw new A("streams");var T,E=g.map(function(C,M){var S=M<g.length-1;return m(C,S,0<M,function(R){T||(T=R),R&&E.forEach(u),S||(E.forEach(u),_(T))})});return g.reduce(f)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(o,c){function l(p,m,u){return p.highWaterMark==null?m?p[u]:null:p.highWaterMark}var d=o("../../../errors").codes.ERR_INVALID_OPT_VALUE;c.exports={getHighWaterMark:function(p,m,u,f){var x=l(m,f,u);if(x!=null){if(!(isFinite(x)&&s(x)===x)||0>x){var b=f?u:"highWaterMark";throw new d(b,x)}return s(x)}return p.objectMode?16:16384}}},{"../../../errors":15}],28:[function(o,c){c.exports=o("events").EventEmitter},{events:7}],29:[function(o,c,l){l=c.exports=o("./lib/_stream_readable.js"),l.Stream=l,l.Readable=l,l.Writable=o("./lib/_stream_writable.js"),l.Duplex=o("./lib/_stream_duplex.js"),l.Transform=o("./lib/_stream_transform.js"),l.PassThrough=o("./lib/_stream_passthrough.js"),l.finished=o("./lib/internal/streams/end-of-stream.js"),l.pipeline=o("./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(o,c,l){function d(f,x){for(var b in f)x[b]=f[b]}function p(f,x,b){return u(f,x,b)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var m=o("buffer"),u=m.Buffer;u.from&&u.alloc&&u.allocUnsafe&&u.allocUnsafeSlow?c.exports=m:(d(m,l),l.Buffer=p),p.prototype=Object.create(u.prototype),d(u,p),p.from=function(f,x,b){if(typeof f=="number")throw new TypeError("Argument must not be a number");return u(f,x,b)},p.alloc=function(f,x,b){if(typeof f!="number")throw new TypeError("Argument must be a number");var j=u(f);return x===void 0?j.fill(0):typeof b=="string"?j.fill(x,b):j.fill(x),j},p.allocUnsafe=function(f){if(typeof f!="number")throw new TypeError("Argument must be a number");return u(f)},p.allocUnsafeSlow=function(f){if(typeof f!="number")throw new TypeError("Argument must be a number");return m.SlowBuffer(f)}},{buffer:3}],31:[function(o,c,l){function d(E){if(!E)return"utf8";for(var C;;)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(C)return;E=(""+E).toLowerCase(),C=!0}}function p(E){var C=d(E);if(typeof C!="string"&&(_.isEncoding===T||!T(E)))throw new Error("Unknown encoding: "+E);return C||E}function m(E){this.encoding=p(E);var C;switch(this.encoding){case"utf16le":this.text=j,this.end=A,C=4;break;case"utf8":this.fillLast=b,C=4;break;case"base64":this.text=v,this.end=I,C=3;break;default:return this.write=g,void(this.end=k)}this.lastNeed=0,this.lastTotal=0,this.lastChar=_.allocUnsafe(C)}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 f(E,C,M){var S=C.length-1;if(S<M)return 0;var R=u(C[S]);return 0<=R?(0<R&&(E.lastNeed=R-1),R):--S<M||R===-2?0:(R=u(C[S]),0<=R?(0<R&&(E.lastNeed=R-2),R):--S<M||R===-2?0:(R=u(C[S]),0<=R?(0<R&&(R===2?R=0:E.lastNeed=R-3),R):0))}function x(E,C){if((192&C[0])!=128)return E.lastNeed=0,"�";if(1<E.lastNeed&&1<C.length){if((192&C[1])!=128)return E.lastNeed=1,"�";if(2<E.lastNeed&&2<C.length&&(192&C[2])!=128)return E.lastNeed=2,"�"}}function b(E){var C=this.lastTotal-this.lastNeed,M=x(this,E);return M===void 0?this.lastNeed<=E.length?(E.copy(this.lastChar,C,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(E.copy(this.lastChar,C,0,E.length),void(this.lastNeed-=E.length)):M}function j(E,C){if((E.length-C)%2==0){var M=E.toString("utf16le",C);if(M){var S=M.charCodeAt(M.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],M.slice(0,-1)}return M}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=E[E.length-1],E.toString("utf16le",C,E.length-1)}function A(E){var C=E&&E.length?this.write(E):"";if(this.lastNeed){var M=this.lastTotal-this.lastNeed;return C+this.lastChar.toString("utf16le",0,M)}return C}function v(E,C){var M=(E.length-C)%3;return M==0?E.toString("base64",C):(this.lastNeed=3-M,this.lastTotal=3,M==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",C,E.length-M))}function I(E){var C=E&&E.length?this.write(E):"";return this.lastNeed?C+this.lastChar.toString("base64",0,3-this.lastNeed):C}function g(E){return E.toString(this.encoding)}function k(E){return E&&E.length?this.write(E):""}var _=o("safe-buffer").Buffer,T=_.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=m,m.prototype.write=function(E){if(E.length===0)return"";var C,M;if(this.lastNeed){if(C=this.fillLast(E),C===void 0)return"";M=this.lastNeed,this.lastNeed=0}else M=0;return M<E.length?C?C+this.text(E,M):this.text(E,M):C||""},m.prototype.end=function(E){var C=E&&E.length?this.write(E):"";return this.lastNeed?C+"�":C},m.prototype.text=function(E,C){var M=f(this,E,C);if(!this.lastNeed)return E.toString("utf8",C);this.lastTotal=M;var S=E.length-(M-this.lastNeed);return E.copy(this.lastChar,0,S),E.toString("utf8",C,S)},m.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(o,c){(function(l){(function(){function d(p){try{if(!l.localStorage)return!1}catch{return!1}var m=l.localStorage[p];return m!=null&&(m+"").toLowerCase()==="true"}c.exports=function(p,m){function u(){if(!f){if(d("throwDeprecation"))throw new Error(m);d("traceDeprecation")?console.trace(m):console.warn(m),f=!0}return p.apply(this,arguments)}if(d("noDeprecation"))return p;var f=!1;return u}}).call(this)}).call(this,typeof Qe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Qe)},{}],"/":[function(o,c){function l(I){return I.replace(/a=ice-options:trickle\s\n/g,"")}function d(I){console.warn(I)}/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const p=o("debug")("simple-peer"),m=o("get-browser-rtc"),u=o("randombytes"),f=o("readable-stream"),x=o("queue-microtask"),b=o("err-code"),{Buffer:j}=o("buffer"),A=65536;class v extends f.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||v.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},v.config,g.config),this.offerOptions=g.offerOptions||{},this.answerOptions=g.answerOptions||{},this.sdpTransform=g.sdpTransform||(k=>k),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:m(),!this._wrtc)throw b(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(k){return void this.destroy(b(k,"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=k=>{this._onIceCandidate(k)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(k=>{this.destroy(b(k,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=k=>{this._setupData(k)},this.streams&&this.streams.forEach(k=>{this.addStream(k)}),this._pc.ontrack=k=>{this._onTrack(k)},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 b(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(k=>{this._addIceCandidate(k)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(k=>{this.destroy(b(k,"ERR_SET_REMOTE_DESCRIPTION"))}),g.sdp||g.candidate||g.renegotiate||g.transceiverRequest||this.destroy(b(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(g){const k=new this._wrtc.RTCIceCandidate(g);this._pc.addIceCandidate(k).catch(_=>{!k.address||k.address.endsWith(".local")?d("Ignoring unsupported ICE candidate."):this.destroy(b(_,"ERR_ADD_ICE_CANDIDATE"))})}send(g){if(!this.destroying){if(this.destroyed)throw b(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(g)}}addTransceiver(g,k){if(!this.destroying){if(this.destroyed)throw b(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(g,k),this._needsNegotiation()}catch(_){this.destroy(b(_,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:g,init:k}})}}addStream(g){if(!this.destroying){if(this.destroyed)throw b(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),g.getTracks().forEach(k=>{this.addTrack(k,g)})}}addTrack(g,k){if(this.destroying)return;if(this.destroyed)throw b(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const _=this._senderMap.get(g)||new Map;let T=_.get(k);if(!T)T=this._pc.addTrack(g,k),_.set(k,T),this._senderMap.set(g,_),this._needsNegotiation();else throw T.removed?b(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):b(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(g,k,_){if(this.destroying)return;if(this.destroyed)throw b(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const T=this._senderMap.get(g),E=T?T.get(_):null;if(!E)throw b(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");k&&this._senderMap.set(k,T),E.replaceTrack==null?this.destroy(b(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):E.replaceTrack(k)}removeTrack(g,k){if(this.destroying)return;if(this.destroyed)throw b(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const _=this._senderMap.get(g),T=_?_.get(k):null;if(!T)throw b(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{T.removed=!0,this._pc.removeTrack(T)}catch(E){E.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(T):this.destroy(b(E,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(g){if(!this.destroying){if(this.destroyed)throw b(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),g.getTracks().forEach(k=>{this.removeTrack(k,g)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,x(()=>{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 b(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,k){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",g&&(g.message||g)),x(()=>{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"),k()}))}_setupData(g){if(!g.channel)return this.destroy(b(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=A),this.channelName=this._channel.label,this._channel.onmessage=_=>{this._onChannelMessage(_)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=_=>{const T=_.error instanceof Error?_.error:new Error(`Datachannel error: ${_.message} ${_.filename}:${_.lineno}:${_.colno}`);this.destroy(b(T,"ERR_DATA_CHANNEL"))};let k=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(k&&this._onChannelClose(),k=!0):k=!1},5e3)}_read(){}_write(g,k,_){if(this.destroyed)return _(b(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(g)}catch(T){return this.destroy(b(T,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>A?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=_):_(null)}else this._debug("write before connect"),this._chunk=g,this._cb=_}_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 k=()=>{if(!this.destroyed){const _=this._pc.localDescription||g;this._debug("signal"),this.emit("signal",{type:_.type,sdp:_.sdp})}};this._pc.setLocalDescription(g).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?k():this.once("_iceComplete",k))}).catch(_=>{this.destroy(b(_,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(g=>{this.destroy(b(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 k=()=>{if(!this.destroyed){const _=this._pc.localDescription||g;this._debug("signal"),this.emit("signal",{type:_.type,sdp:_.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(g).then(()=>{this.destroyed||(this.trickle||this._iceComplete?k():this.once("_iceComplete",k))}).catch(_=>{this.destroy(b(_,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(g=>{this.destroy(b(g,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(b(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const g=this._pc.iceConnectionState,k=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",g,k),this.emit("iceStateChange",g,k),(g==="connected"||g==="completed")&&(this._pcReady=!0,this._maybeReady()),g==="failed"&&this.destroy(b(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),g==="closed"&&this.destroy(b(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(g){const k=_=>(Object.prototype.toString.call(_.values)==="[object Array]"&&_.values.forEach(T=>{Object.assign(_,T)}),_);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(_=>{const T=[];_.forEach(E=>{T.push(k(E))}),g(null,T)},_=>g(_)):0<this._pc.getStats.length?this._pc.getStats(_=>{if(this.destroyed)return;const T=[];_.result().forEach(E=>{const C={};E.names().forEach(M=>{C[M]=E.stat(M)}),C.id=E.id,C.type=E.type,C.timestamp=E.timestamp,T.push(k(C))}),g(null,T)},_=>g(_)):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((k,_)=>{if(this.destroyed)return;k&&(_=[]);const T={},E={},C={};let M=!1;_.forEach(R=>{(R.type==="remotecandidate"||R.type==="remote-candidate")&&(T[R.id]=R),(R.type==="localcandidate"||R.type==="local-candidate")&&(E[R.id]=R),(R.type==="candidatepair"||R.type==="candidate-pair")&&(C[R.id]=R)});const S=R=>{M=!0;let O=E[R.localCandidateId];O&&(O.ip||O.address)?(this.localAddress=O.ip||O.address,this.localPort=+O.port):O&&O.ipAddress?(this.localAddress=O.ipAddress,this.localPort=+O.portNumber):typeof R.googLocalAddress=="string"&&(O=R.googLocalAddress.split(":"),this.localAddress=O[0],this.localPort=+O[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let B=T[R.remoteCandidateId];B&&(B.ip||B.address)?(this.remoteAddress=B.ip||B.address,this.remotePort=+B.port):B&&B.ipAddress?(this.remoteAddress=B.ipAddress,this.remotePort=+B.portNumber):typeof R.googRemoteAddress=="string"&&(B=R.googRemoteAddress.split(":"),this.remoteAddress=B[0],this.remotePort=+B[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(_.forEach(R=>{R.type==="transport"&&R.selectedCandidatePairId&&S(C[R.selectedCandidatePairId]),(R.type==="googCandidatePair"&&R.googActiveConnection==="true"||(R.type==="candidatepair"||R.type==="candidate-pair")&&R.selected)&&S(R)}),!M&&(!Object.keys(C).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(O){return this.destroy(b(O,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const R=this._cb;this._cb=null,R(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>A)&&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 k=g.data;k instanceof ArrayBuffer&&(k=j.from(k)),this.push(k)}_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(k=>{this._debug("on track"),this.emit("track",g.track,k),this._remoteTracks.push({track:g.track,stream:k}),this._remoteStreams.some(_=>_.id===k.id)||(this._remoteStreams.push(k),x(()=>{this._debug("on stream"),this.emit("stream",k)}))})}_debug(){const g=[].slice.call(arguments);g[0]="["+this._id+"] "+g[0],p.apply(null,g)}}v.WEBRTC_SUPPORT=!!m(),v.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},v.channelConfig={},c.exports=v},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(Vn)),Vn.exports}var zh=$h();const Hh=gl(zh),ei=0,ti=1,$a=2,za=(t,e)=>{re(t,ei);const s=mu(e);Se(t,s)},Ha=(t,e,s)=>{re(t,ti),Se(t,Vr(e,s))},Vh=(t,e,s)=>Ha(e,s,Re(t)),Va=(t,e,s,r)=>{try{la(e,Re(t),s)}catch(i){r!=null&&r(i),console.error("Caught error while handling a Yjs update",i)}},Gh=(t,e)=>{re(t,$a),Se(t,e)},qh=Va,Yh=(t,e,s,r,i)=>{const o=ce(t);switch(o){case ei:Vh(t,e,s);break;case ti:Va(t,s,r,i);break;case $a:qh(t,s,r,i);break;default:throw new Error("Unknown message type")}return o},Gn=3e4;class Kh extends Nr{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const s=lt();this.getLocalState()!==null&&Gn/2<=s-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((i,o)=>{o!==this.clientID&&Gn<=s-i.lastUpdated&&this.states.has(o)&&r.push(o)}),r.length>0&&ur(this,r,"timeout")},Ke(Gn/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,o=this.states.get(s);e===null?this.states.delete(s):this.states.set(s,e),this.meta.set(s,{clock:i,lastUpdated:lt()});const c=[],l=[],d=[],p=[];e===null?p.push(s):o==null?e!=null&&c.push(s):(l.push(s),Ut(o,e)||d.push(s)),(c.length>0||d.length>0||p.length>0)&&this.emit("change",[{added:c,updated:d,removed:p},"local"]),this.emit("update",[{added:c,updated:l,removed:p},"local"])}setLocalStateField(e,s){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:s})}getStates(){return this.states}}const ur=(t,e,s)=>{const r=[];for(let i=0;i<e.length;i++){const o=e[i];if(t.states.has(o)){if(t.states.delete(o),o===t.clientID){const c=t.meta.get(o);t.meta.set(o,{clock:c.clock+1,lastUpdated:lt()})}r.push(o)}}r.length>0&&(t.emit("change",[{added:[],updated:[],removed:r},s]),t.emit("update",[{added:[],updated:[],removed:r},s]))},rn=(t,e,s=t.states)=>{const r=e.length,i=Ae();re(i,r);for(let o=0;o<r;o++){const c=e[o],l=s.get(c)||null,d=t.meta.get(c).clock;re(i,c),re(i,d),et(i,JSON.stringify(l))}return ke(i)},Jh=(t,e,s)=>{const r=nt(e),i=lt(),o=[],c=[],l=[],d=[],p=ce(r);for(let m=0;m<p;m++){const u=ce(r);let f=ce(r);const x=JSON.parse(ot(r)),b=t.meta.get(u),j=t.states.get(u),A=b===void 0?0:b.clock;(A<f||A===f&&x===null&&t.states.has(u))&&(x===null?u===t.clientID&&t.getLocalState()!=null?f++:t.states.delete(u):t.states.set(u,x),t.meta.set(u,{clock:f,lastUpdated:i}),b===void 0&&x!==null?o.push(u):b!==void 0&&x===null?d.push(u):x!==null&&(Ut(x,j)||l.push(u),c.push(u)))}(o.length>0||l.length>0||d.length>0)&&t.emit("change",[{added:o,updated:l,removed:d},s]),(o.length>0||c.length>0||d.length>0)&&t.emit("update",[{added:o,updated:c,removed:d},s])},Xh=(t,e)=>{const s=sr(t).buffer,r=sr(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"]))},Ga=(t,e)=>{if(!e)return Lr(t);const s=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,t).then(r=>{const i=Ae();return et(i,"AES-GCM"),Se(i,s),Se(i,new Uint8Array(r)),ke(i)})},Qh=(t,e)=>{const s=Ae();return Ht(s,t),Ga(ke(s),e)},qa=(t,e)=>{if(!e)return Lr(t);const s=nt(t);ot(s)!=="AES-GCM"&&Fc(He("Unknown encryption algorithm"));const i=Re(s),o=Re(s);return crypto.subtle.decrypt({name:"AES-GCM",iv:i},e,o).then(c=>new Uint8Array(c))},Zh=(t,e)=>qa(t,e).then(s=>Vt(nt(new Uint8Array(s)))),Fe=Zd("y-webrtc"),zt=0,Ya=3,vs=1,si=4,on=new Map,St=new Map,Ka=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}]),Fe("synced ",Ye,t.name,Et," with all peers"))},Ja=(t,e,s)=>{const r=nt(e),i=Ae(),o=ce(r);if(t===void 0)return null;const c=t.awareness,l=t.doc;let d=!1;switch(o){case zt:{re(i,zt);const p=Yh(r,i,l,t);p===ti&&!t.synced&&s(),p===ei&&(d=!0);break}case Ya:re(i,vs),Se(i,rn(c,Array.from(c.getStates().keys()))),d=!0;break;case vs:Jh(c,Re(r),t);break;case si:{const p=jt(r)===1,m=ot(r);if(m!==t.peerId&&(t.bcConns.has(m)&&!p||!t.bcConns.has(m)&&p)){const u=[],f=[];p?(t.bcConns.add(m),f.push(m)):(t.bcConns.delete(m),u.push(m)),t.provider.emit("peers",[{added:f,removed:u,webrtcPeers:Array.from(t.webrtcConns.keys()),bcPeers:Array.from(t.bcConns)}]),Xa(t)}break}default:return console.error("Unable to compute message"),i}return d?i:null},ef=(t,e)=>{const s=t.room;return Fe("received message from ",Ye,t.remotePeerId,Fr," (",s.name,")",Et,jn),Ja(s,e,()=>{t.synced=!0,Fe("synced ",Ye,s.name,Et," with ",Ye,t.remotePeerId),Ka(s)})},qn=(t,e)=>{Fe("send message to ",Ye,t.remotePeerId,Et,Fr," (",t.room.name,")",jn);try{t.peer.send(ke(e))}catch{}},tf=(t,e)=>{Fe("broadcast message in ",Ye,t.name,Et),t.webrtcConns.forEach(s=>{try{s.peer.send(e)}catch{}})};class Di{constructor(e,s,r,i){Fe("establishing connection to ",Ye,r),this.room=i,this.remotePeerId=r,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new Hh({initiator:s,...i.provider.peerOpts}),this.peer.on("signal",o=>{this.glareToken===void 0&&(this.glareToken=Date.now()+Math.random()),ni(e,i,{to:r,from:i.peerId,type:"signal",token:this.glareToken,signal:o})}),this.peer.on("connect",()=>{Fe("connected to ",Ye,r),this.connected=!0;const c=i.provider.doc,l=i.awareness,d=Ae();re(d,zt),za(d,c),qn(this,d);const p=l.getStates();if(p.size>0){const m=Ae();re(m,vs),Se(m,rn(l,Array.from(p.keys()))),qn(this,m)}}),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)}])),Ka(i),this.peer.destroy(),Fe("closed connection to ",Ye,r),hr(i)}),this.peer.on("error",o=>{Fe("Error in connection to ",Ye,r,": ",o),hr(i)}),this.peer.on("data",o=>{const c=ef(this,o);c!==null&&qn(this,c)})}destroy(){this.peer.destroy()}}const ht=(t,e)=>Ga(e,t.key).then(s=>t.mux(()=>Bh(t.name,s))),Mi=(t,e)=>{t.bcconnected&&ht(t,e),tf(t,e)},hr=t=>{on.forEach(e=>{e.connected&&(e.send({type:"subscribe",topics:[t.name]}),t.webrtcConns.size<t.provider.maxConns&&ni(e,t,{type:"announce",from:t.peerId}))})},Xa=t=>{if(t.provider.filterBcConns){const e=Ae();re(e,si),ps(e,1),et(e,t.peerId),ht(t,ke(e))}};class sf{constructor(e,s,r,i){this.peerId=xo(),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=Fh(),this.bcconnected=!1,this._bcSubscriber=o=>qa(new Uint8Array(o),i).then(c=>this.mux(()=>{const l=Ja(this,c,()=>{});l&&ht(this,ke(l))})),this._docUpdateHandler=(o,c)=>{const l=Ae();re(l,zt),Gh(l,o),Mi(this,ke(l))},this._awarenessUpdateHandler=({added:o,updated:c,removed:l},d)=>{const p=o.concat(c).concat(l),m=Ae();re(m,vs),Se(m,rn(this.awareness,p)),Mi(this,ke(m))},this._beforeUnloadHandler=()=>{ur(this.awareness,[e.clientID],"window unload"),St.forEach(o=>{o.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),hr(this);const e=this.name;Wh(e,this._bcSubscriber),this.bcconnected=!0,Xa(this);const s=Ae();re(s,zt),za(s,this.doc),ht(this,ke(s));const r=Ae();re(r,zt),Ha(r,this.doc),ht(this,ke(r));const i=Ae();re(i,Ya),ht(this,ke(i));const o=Ae();re(o,vs),Se(o,rn(this.awareness,[this.doc.clientID])),ht(this,ke(o))}disconnect(){on.forEach(s=>{s.connected&&s.send({type:"unsubscribe",topics:[this.name]})}),ur(this.awareness,[this.doc.clientID],"disconnect");const e=Ae();re(e,si),ps(e,0),et(e,this.peerId),ht(this,ke(e)),Uh(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 nf=(t,e,s,r)=>{if(St.has(s))throw He(`A Yjs Doc connected to room "${s}" already exists!`);const i=new sf(t,e,s,r);return St.set(s,i),i},ni=(t,e,s)=>{e.key?Qh(s,e.key).then(r=>{t.send({type:"publish",topic:e.name,data:Co(r)})}):t.send({type:"publish",topic:e.name,data:s})};class rf extends Mh{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{Fe(`connected (${e})`);const s=Array.from(St.keys());this.send({type:"subscribe",topics:s}),St.forEach(r=>ni(this,r,{type:"announce",from:r.peerId}))}),this.on("message",s=>{switch(s.type){case"publish":{const r=s.topic,i=St.get(r);if(i==null||typeof r!="string")return;const o=c=>{const l=i.webrtcConns,d=i.peerId;if(c==null||c.from===d||c.to!==void 0&&c.to!==d||i.bcConns.has(c.from))return;const p=l.has(c.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[c.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(c.type){case"announce":l.size<i.provider.maxConns&&(ze(l,c.from,()=>new Di(this,!0,c.from,i)),p());break;case"signal":if(c.signal.type==="offer"){const m=l.get(c.from);if(m){const u=c.token,f=m.glareToken;if(f&&f>u){Fe("offer rejected: ",c.from);return}m.glareToken=void 0}}if(c.signal.type==="answer"){Fe("offer answered by: ",c.from);const m=l.get(c.from);m.glareToken=void 0}c.to===d&&(ze(l,c.from,()=>new Di(this,!1,c.from,i)).peer.signal(c.signal),p());break}};i.key?typeof s.data=="string"&&Zh(To(s.data),i.key).then(o):o(s.data)}}}),this.on("disconnect",()=>Fe(`disconnect (${e})`))}}const Yn=t=>{t.emit("status",[{connected:t.connected}])};class of extends fo{constructor(e,s,{signaling:r=["wss://y-webrtc-eu.fly.dev"],password:i=null,awareness:o=new Kh(s),maxConns:c=20+Ke(Uc()*15),filterBcConns:l=!0,peerOpts:d={}}={}){super(),this.roomName=e,this.doc=s,this.filterBcConns=l,this.awareness=o,this.shouldConnect=!1,this.signalingUrls=r,this.signalingConns=[],this.maxConns=c,this.peerOpts=d,this.key=i?Xh(i,e):Lr(null),this.room=null,this.key.then(p=>{this.room=nf(s,this,e,p),this.shouldConnect?this.room.connect():this.room.disconnect(),Yn(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=ze(on,e,()=>new rf(e));this.signalingConns.push(s),s.providers.add(this)}),this.room&&(this.room.connect(),Yn(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),e.providers.size===0&&(e.destroy(),on.delete(e.url))}),this.room&&(this.room.disconnect(),Yn(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),St.delete(this.roomName)}),super.destroy()}}const ls=new Map,an=new Map,fr=new Map;function af(){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem("titan2:webrtc"))==="1"}catch{return!1}}function lf(t){if(!ls.has(t)){const e=new ts({guid:`titan-space-${t}`});ls.set(t,e);const s=new Ih(`titan-space-${t}`,e);if(an.set(t,s),af())try{const r=new of(`titan-space-${t}`,e,{signaling:["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com"]});fr.set(t,r)}catch{}}return ls.get(t)}function cf(t){const{widgets:e}=xt(t),s=new Set,r=[];e.forEach((i,o)=>{const c=i.get("id");typeof c!="string"||s.has(c)?r.push(o):s.add(c)});for(let i=r.length-1;i>=0;i--)e.delete(r[i],1);return r.length}function xt(t){const e=lf(t),s=e.getArray("widgets"),r=e.getMap("meta"),i=an.get(t);return{widgets:s,meta:r,doc:e,whenSynced:i!=null&&i.synced?Promise.resolve():new Promise(o=>{const c=()=>{i==null||i.off("synced",c),o()};i==null||i.on("synced",c),setTimeout(()=>o(),2e3)})}}function df(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 Qa(t){const e=new Ct;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(o=>o.id===t);if(!r)return null;const i=new Set;for(const o of r.widgets||[])o&&typeof o.id=="string"&&i.add(o.id);return i}catch{return null}}const ln=new Map;function hf(t,e){let s=ln.get(t);s||(s=new Set,ln.set(t,s)),s.add(e)}function ff(t,e){var s;return((s=ln.get(t))==null?void 0:s.has(e))??!1}function Za(t){ln.delete(t)}function pf(t,e){const{widgets:s}=xt(t),r=new Map,i=()=>{const c=new Set,l=uf(t),d=[];s.forEach(p=>{const m=df(p);if(!m.id||c.has(m.id))return;const u=m.format==="system",f=typeof m.source=="string"&&m.source.trim()!=="";!u&&!f||l&&!l.has(m.id)&&!ff(t,m.id)||(c.add(m.id),d.push(m))}),e(d)},o=()=>{const c=new Set;s.forEach(l=>c.add(l));for(const[l,d]of r)c.has(l)||(l.unobserve(d),r.delete(l));for(const l of c)if(!r.has(l)){const d=()=>i();l.observe(d),r.set(l,d)}i()};return s.observe(o),o(),()=>{s.unobserve(o);for(const[c,l]of r)c.unobserve(l);r.clear()}}function gf(t,e){const{widgets:s}=xt(t),r={...e,id:`widget_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,createdAt:Date.now(),updatedAt:Date.now()};return hf(t,r.id),s.push([Qa(r)]),r}function mf(t,e){const{widgets:s}=xt(t);let r=-1;s.forEach((i,o)=>{i.get("id")===e&&(r=o)}),r>=0&&s.delete(r,1)}function Oi(t,e,s){const{widgets:r}=xt(t);r.forEach(i=>{if(i.get("id")===e){for(const[o,c]of Object.entries(s))i.set(o,c);i.set("updatedAt",Date.now())}})}function yf(t){const{widgets:e}=xt(t);e.delete(0,e.length),Za(t)}function bf(t){var e,s,r;(e=an.get(t))==null||e.destroy(),(s=fr.get(t))==null||s.destroy(),(r=ls.get(t))==null||r.destroy(),an.delete(t),fr.delete(t),ls.delete(t),Za(t)}const cs="titan2-spaces",xf=!0;function de(t,e,s,r,i,o,c){return{id:t,name:e,format:"system",source:s,x:r,y:i,w:o,h:c,createdAt:Date.now(),updatedAt:Date.now()}}const Ls=[{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-paperclip","Paperclip","system:paperclip",6,11,6,5),de("tools-browser","Browser","system:browser",0,16,6,5),de("tools-cron","Cron","system:cron",6,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()}],pr=11,wf={home:new Set(["home-chat"])};function vf(t,e){const{widgets:s,meta:r,whenSynced:i}=xt(t.id);i.then(()=>{try{const o=cf(t.id);if(o>0&&console.info(`[SpaceEngine] healed ${o} duplicate widget(s) in "${t.id}"`),e){const c=wf[t.id]??new Set;for(let p=s.length-1;p>=0;p--){const m=s.get(p),u=m==null?void 0:m.get("id");typeof u=="string"&&c.has(u)&&s.delete(p,1)}for(let p=s.length-1;p>=0;p--){const m=s.get(p),u=m==null?void 0:m.get("source");(typeof u!="string"||u.trim()==="")&&s.delete(p,1)}const l=new Map;for(const p of t.widgets)l.set(p.id,p);const d=new Set;s.forEach(p=>{const m=p.get("id");if(typeof m=="string"&&l.has(m)){d.add(m);const u=l.get(m);p.set("x",u.x),p.set("y",u.y),p.set("w",u.w),p.set("h",u.h)}});for(const p of t.widgets)d.has(p.id)||s.push([Qa(p)]);r.set("seedVersion",pr)}}catch(o){console.warn(`[SpaceEngine] healYSpaceOnSync failed for "${t.id}":`,o)}})}function _f(){try{const t=localStorage.getItem(cs),s=parseInt(localStorage.getItem(`${cs}-version`)||"0",10)<pr;if(xf)for(const o of Ls)vf(o,s);if(!t||s){localStorage.setItem(`${cs}-version`,String(pr));const o=Ls.map(c=>({...c,widgets:[...c.widgets]}));return _t(o),o}const r=JSON.parse(t);for(const o of r)Array.isArray(o.widgets)||(o.widgets=[]),o.widgets=o.widgets.filter(c=>c&&typeof c.id=="string").map(c=>({...c,x:Number.isFinite(c.x)?Math.max(0,Math.floor(c.x)):0,y:Number.isFinite(c.y)?Math.max(0,Math.floor(c.y)):0,w:Number.isFinite(c.w)?Math.max(1,Math.floor(c.w)):4,h:Number.isFinite(c.h)?Math.max(1,Math.floor(c.h)):4}));for(const o of r){const c=new Set;o.widgets=o.widgets.filter(l=>c.has(l.id)?!1:(c.add(l.id),!0))}const i=new Map(r.map(o=>[o.id,o]));return Ls.forEach(o=>{i.get(o.id)||i.set(o.id,{...o,widgets:[...o.widgets]})}),Array.from(i.values())}catch{return Ls.map(t=>({...t,widgets:[...t.widgets]}))}}let Kn=null;function _t(t){Kn&&clearTimeout(Kn),Kn=setTimeout(()=>{localStorage.setItem(cs,JSON.stringify(t))},250)}let Ve=null;const _e={list(){return Ve||(Ve=_f()),Ve},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 Ve=[...this.list(),e],_t(Ve),e},save(t){t.updatedAt=new Date().toISOString(),Ve=this.list().map(e=>e.id===t.id?t:e),_t(Ve)},remove(t){Ve=this.list().filter(e=>e.id!==t),_t(Ve)},addWidget(t,e){if(!e.source||e.source.trim()==="")throw new Error("Widget source cannot be empty");{const s=gf(t,e);try{const r=localStorage.getItem(cs),i=r?JSON.parse(r):[],o=i.find(c=>c.id===t);if(o)new Set((o.widgets||[]).map(l=>l.id)).has(s.id)||(o.widgets=[...o.widgets||[],s]),o.updatedAt=new Date().toISOString(),Ve=i,_t(i);else{const c={id:t,name:t,widgets:[s],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};Ve=[...i,c],_t(Ve)}}catch{}return s}},updateWidget(t,e,s){Oi(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){mf(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)Oi(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(o=>o&&o.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 pf(t,e)},async clearSpace(t){{const{whenSynced:r}=xt(t);await r,yf(t),bf(t);try{const i=indexedDB.deleteDatabase(`titan-space-${t}`);await new Promise((o,c)=>{i.onsuccess=()=>o(),i.onerror=()=>c(i.error),i.onblocked=()=>o()})}catch{}}const e=this.list(),s=e.find(r=>r.id===t);s&&(s.widgets=[],_t(e))}};let rs=null;function kf(){if(rs)return rs;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 rs=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 rs=null,e}),rs}function Sf(t){const e=jf;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 jf=`
103
- <script>
104
- (function() {
105
- 'use strict';
106
-
107
- // NOTE: Prototype freezing is intentionally disabled.
108
- // Babel standalone mutates Function.prototype.toString during JSX transform.
109
- // Freezing causes "Cannot assign to read only property" errors.
110
-
111
- // Prevent eval and Function constructor abuse
112
- window.eval = function() { throw new Error('eval is disabled in sandbox'); };
113
- const OriginalFunction = window.Function;
114
- window.Function = function(...args) {
115
- const body = args.pop() || '';
116
- if (body.includes('import') && body.includes('http')) {
117
- throw new Error('Dynamic imports with URLs are disabled in sandbox');
118
- }
119
- return OriginalFunction.apply(this, [...args, body]);
120
- };
121
-
122
- const pending = new Map();
123
- let msgId = 0;
124
- let reactRoot = null;
125
-
126
- function send(type, payload) {
127
- const id = ++msgId;
128
- return new Promise((resolve, reject) => {
129
- pending.set(id, { resolve, reject });
130
- window.parent.postMessage({ type, id, payload }, '*');
131
- });
132
- }
133
-
134
- window.addEventListener('message', (e) => {
135
- // Resolve pending iframe promises (parent responses to titan.* calls)
136
- if (typeof e.data?.id === 'number' && pending.has(e.data.id)) {
137
- const p = pending.get(e.data.id);
138
- pending.delete(e.data.id);
139
- if (e.data.error) p.reject(new Error(e.data.error));
140
- else p.resolve(e.data.payload);
141
- return;
142
- }
143
-
144
- // Handle parent commands
145
- if (e.data?.type === 'render') {
146
- handleRender(e.data.id, e.data.payload);
147
- }
148
- if (e.data?.type === 'execute') {
149
- handleExecute(e.data.id, e.data.payload);
150
- }
151
- });
152
-
153
- const titan = {
154
- fetch: (url, opts) => {
155
- try { new URL(url, 'https://example.com'); } catch {
156
- throw new Error('Invalid URL: ' + url);
157
- }
158
- return send('fetch', { url, options: opts });
159
- },
160
- api: { call: (endpoint, body) => send('api', { endpoint, body }) },
161
- state: {
162
- get: (key) => send('state', { action: 'get', key }),
163
- set: (key, value) => send('state', { action: 'set', key, value }),
164
- },
165
- canvas: {
166
- createWidget: (def) => send('canvas', { action: 'createWidget', def }),
167
- updateWidget: (id, patch) => send('canvas', { action: 'updateWidget', id, patch }),
168
- removeWidget: (id) => send('canvas', { action: 'removeWidget', id }),
169
- listWidgets: () => send('canvas', { action: 'listWidgets' }),
170
- },
171
- // v6.0 Step 8 — Widget-runtime API surface.
172
- // titan.tools.run / titan.tools.list — invoke or enumerate any
173
- // TITAN tool from inside a widget. Widgets become first-class
174
- // agent surfaces (not just dumb UI).
175
- tools: {
176
- list: () => send('api', { endpoint: '/api/tools', body: { method: 'GET' } }),
177
- run: (name, args) => send('api', { endpoint: '/api/tools/run', body: { name, args: args || {} } }),
178
- },
179
- // titan.agent.ask — sub-question to TITAN itself. Widgets can
180
- // delegate parts of their work back to the agent loop.
181
- agent: {
182
- ask: (prompt) => send('api', { endpoint: '/api/message', body: { content: String(prompt) } }),
183
- },
184
- // titan.memory.get / .set — typed access to widget-scoped memory.
185
- memory: {
186
- get: (key) => send('api', { endpoint: '/api/memory/' + encodeURIComponent(key), body: { method: 'GET' } }),
187
- set: (key, value) => send('api', { endpoint: '/api/memory', body: { key, value } }),
188
- },
189
- // titan.persona — read-only handle to the active persona content.
190
- persona: {
191
- get: () => send('api', { endpoint: '/api/persona/current', body: { method: 'GET' } }),
192
- },
193
- // titan.space — read-only handle to the active Space (id, name,
194
- // intent, widget count).
195
- space: {
196
- active: () => send('api', { endpoint: '/api/spaces', body: { method: 'GET' } }),
197
- },
198
- log: (...args) => send('log', { args: args.map(a => String(a)) }),
199
- };
200
-
201
- window.titan = titan;
202
-
203
- function handleRender(msgId, payload) {
204
- const { format, source } = payload;
205
- const root = document.getElementById('root');
206
- root.innerHTML = '';
207
- const loadingEl = document.getElementById('sandbox-loading');
208
- if (loadingEl) loadingEl.style.display = 'none';
209
-
210
- // Unmount previous React root to prevent memory leaks
211
- if (reactRoot) {
212
- try { reactRoot.unmount(); } catch (e) {}
213
- reactRoot = null;
214
- }
215
-
216
- function showError(title, detail) {
217
- root.innerHTML = '';
218
- const wrap = document.createElement('div');
219
- wrap.style.cssText = 'padding:16px;font-family:monospace;font-size:12px;line-height:1.5;';
220
- const h = document.createElement('div');
221
- h.style.cssText = 'color:#ef4444;font-weight:bold;margin-bottom:8px;';
222
- h.textContent = title;
223
- const d = document.createElement('pre');
224
- d.style.cssText = 'color:#a1a1aa;white-space:pre-wrap;word-break:break-word;margin:0;';
225
- d.textContent = detail;
226
- wrap.appendChild(h);
227
- wrap.appendChild(d);
228
- root.appendChild(wrap);
229
- }
230
-
231
- try {
232
- if (format === 'react') {
233
- console.log('[sandbox] render react, source length:', source.length);
234
- if (!source || source.trim() === '') {
235
- throw new Error('Source is empty');
236
- }
237
- if (typeof React === 'undefined') {
238
- throw new Error('React not loaded — the inlined React bundle failed to evaluate inside the sandbox.');
239
- }
240
- if (typeof ReactDOM === 'undefined') {
241
- throw new Error('ReactDOM not loaded — the inlined ReactDOM bundle failed to evaluate inside the sandbox.');
242
- }
243
- if (typeof Babel === 'undefined') {
244
- throw new Error('Babel not loaded — the inlined Babel bundle failed to evaluate inside the sandbox.');
245
- }
246
-
247
- // ── 1. Strip export-default variations so Babel doesn't choke ──
248
- // Using simple string operations (no regex backslashes) to avoid Vite stripping
249
- let src = source;
250
- const lines = src.split('\\n');
251
- const outLines = [];
252
- for (let i = 0; i < lines.length; i++) {
253
- let line = lines[i];
254
- const trimmed = line.trim();
255
- if (trimmed.startsWith('export default function ')) {
256
- const rest = trimmed.slice('export default function '.length);
257
- const name = rest.split('(')[0].trim();
258
- line = '/* export default function ' + name + ' */ function ' + rest;
259
- } else if (trimmed.startsWith('export default class ')) {
260
- const rest = trimmed.slice('export default class '.length);
261
- const name = rest.split(' ')[0].trim().split('{')[0].trim();
262
- line = '/* export default class ' + name + ' */ class ' + rest;
263
- } else if (trimmed.startsWith('export default ')) {
264
- line = '/* export default */';
265
- }
266
- outLines.push(line);
267
- }
268
- src = outLines.join('\\n');
269
-
270
- // ── 2. Detect candidate component names ──
271
- const detected = new Set();
272
- const srcLines = src.split('\\n');
273
- const keywords = ['function ', 'const ', 'let ', 'var ', 'class '];
274
- for (let i = 0; i < srcLines.length; i++) {
275
- const trimmed = srcLines[i].trimStart();
276
- for (let k = 0; k < keywords.length; k++) {
277
- const kw = keywords[k];
278
- if (trimmed.startsWith(kw)) {
279
- const after = trimmed.slice(kw.length);
280
- const endIdx = after.search(/[\\s\\(=]/);
281
- const name = endIdx > 0 ? after.slice(0, endIdx) : after;
282
- if (name.length > 0 && name[0] >= 'A' && name[0] <= 'Z') {
283
- detected.add(name);
284
- }
285
- }
286
- }
287
- }
288
-
289
- const names = ['Widget', ...Array.from(detected)];
290
- console.log('[sandbox] detected names:', names.join(', '));
291
-
292
- // ── 3. Babel transform (JSX only, classic runtime → React.createElement) ──
293
- let code;
294
- try {
295
- const babelResult = Babel.transform(src, { presets: [['react', { runtime: 'classic' }]], filename: 'widget.tsx' });
296
- code = babelResult.code;
297
- console.log('[sandbox] babel ok, code length:', code.length);
298
- } catch (babelErr) {
299
- throw new Error('Babel transform failed: ' + babelErr.message);
300
- }
301
-
302
- // ── 3.5 Auto-inject React hooks and the legacy gallery render()
303
- // helper. Older templates end with render(<MyWidget/>); while newer
304
- // generated code is component-only and gets auto-detected below.
305
- const hookDecl = 'const { useState, useEffect, useRef, useCallback, useMemo, useContext, useReducer, useLayoutEffect, useId, useTransition, useDeferredValue, useImperativeHandle, useDebugValue, useSyncExternalStore } = React;';
306
- const renderDecl = 'window.__titanRenderedElement = null; const render = (node) => { window.__titanRenderedElement = node; };';
307
- code = hookDecl + '\\n' + renderDecl + '\\n' + code;
308
-
309
- // ── 4. Eval the code and find the component ──
310
- const returnChecks = names.map(n =>
311
- 'if (typeof ' + n + ' !== "undefined" && ' + n + ' != null) return ' + n + ';'
312
- ).join('\\n') + '\\nreturn undefined;';
313
-
314
- let Widget;
315
- try {
316
- const fn = new Function('React', 'ReactDOM', 'titan', code + '\\n' + returnChecks);
317
- Widget = fn(React, ReactDOM, titan);
318
- console.log('[sandbox] eval ok, Widget type:', typeof Widget, 'name:', Widget?.name || Widget?.displayName || 'n/a');
319
- } catch (evalErr) {
320
- throw new Error('Eval failed: ' + evalErr.message + '\\nDetected names: ' + names.join(', '));
321
- }
322
-
323
- const renderedElement = window.__titanRenderedElement;
324
- if (!Widget && !renderedElement) {
325
- throw new Error('No React component found. Detected names: ' + names.join(', ') + '. The code must define a capitalized component (e.g., function Widget() {}).');
326
- }
327
-
328
- // ── 5. Render ──
329
- try {
330
- reactRoot = ReactDOM.createRoot(root);
331
- reactRoot.render(renderedElement || React.createElement(Widget, { titan }));
332
- console.log('[sandbox] react render dispatched');
333
- } catch (renderErr) {
334
- throw new Error('React render failed: ' + renderErr.message);
335
- }
336
- } else if (format === 'vanilla') {
337
- const fn = new Function('container', 'titan', 'return (' + source + ')(container, titan)');
338
- const cleanup = fn(root, titan);
339
- window.__widgetCleanup = cleanup;
340
- } else if (format === 'html') {
341
- root.innerHTML = source;
342
- }
343
- window.parent.postMessage({ type: 'rendered', id: msgId }, '*');
344
- } catch (err) {
345
- console.error('[sandbox] render error:', err.name, err.message);
346
- showError(err.name + ': ' + err.message, err.stack || '');
347
- window.parent.postMessage({ type: 'error', id: msgId, error: err.message }, '*');
348
- }
349
- }
350
-
351
- function handleExecute(msgId, payload) {
352
- const { code } = payload;
353
- const logs = [];
354
- const originals = {};
355
- ['log','info','warn','error','debug'].forEach(m => {
356
- originals[m] = console[m];
357
- console[m] = (...args) => {
358
- logs.push({ level: m, text: args.map(a => String(a)).join(' ') });
359
- originals[m](...args);
360
- };
361
- });
362
-
363
- const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
364
-
365
- // Shadow dangerous globals so sandboxed code cannot access them directly.
366
- const forbiddenGlobals = [
367
- 'window','globalThis','self','top','parent','document','location',
368
- 'fetch','XMLHttpRequest','WebSocket','EventSource',
369
- 'localStorage','sessionStorage','indexedDB','navigator','history',
370
- ];
371
-
372
- const runner = new AsyncFunction(
373
- ...forbiddenGlobals,
374
- '__titan',
375
- '"use strict";\\n' +
376
- forbiddenGlobals.map(g => 'const ' + g + ' = undefined;').join('\\n') + '\\n' +
377
- code
378
- );
379
-
380
- (async () => {
381
- try {
382
- const result = await runner(...forbiddenGlobals.map(() => undefined), titan);
383
- Object.keys(originals).forEach(m => console[m] = originals[m]);
384
- window.parent.postMessage({ type: 'result', id: msgId, payload: { status: 'success', logs, result: formatValue(result), resultText: formatValue(result) } }, '*');
385
- } catch (err) {
386
- Object.keys(originals).forEach(m => console[m] = originals[m]);
387
- window.parent.postMessage({ type: 'result', id: msgId, payload: { status: 'error', logs, error: { message: err.message, name: err.name, stack: err.stack } } }, '*');
388
- }
389
- })();
390
- }
391
-
392
- function formatValue(v) {
393
- if (v === undefined) return 'undefined';
394
- if (v === null) return 'null';
395
- if (typeof v === 'string') return v;
396
- if (typeof v === 'number' || typeof v === 'boolean') return String(v);
397
- if (typeof v === 'function') return '[Function]';
398
- if (v instanceof Error) return v.stack || v.message;
399
- if (v instanceof Node) return '<' + v.tagName?.toLowerCase() + '>';
400
- try { return JSON.stringify(v); } catch { return String(v); }
401
- }
402
-
403
- window.parent.postMessage({ type: 'ready' }, '*');
404
- })();
405
- <\/script>
406
- </body>
407
- </html>`;class el{constructor(e,s){Be(this,"iframe",null);Be(this,"pending",new Map);Be(this,"msgId",0);Be(this,"ready",!1);Be(this,"readyQueue",[]);Be(this,"onLog");Be(this,"messageHandler");Be(this,"messageListener");Be(this,"observer");this.iframe=e,this.onLog=s==null?void 0:s.onLog,this.init()}init(){const e=this.iframe;kf().then(i=>{!this.iframe||!document.contains(e)||(e.srcdoc=Sf(i))}).catch(i=>{console.error("[sandbox] vendor scripts failed to load",i);for(const[o,c]of this.pending)c.reject(new Error("Sandbox boot failed: "+i.message)),this.pending.delete(o)});const s=i=>{const o=i.data;if(!(!o||typeof o!="object"||!o.type||typeof o.type!="string"||!["ready","rendered","error","result","fetch","api","state","canvas","log","import"].includes(o.type))){if((o==null?void 0:o.type)==="ready"){this.ready=!0,this.readyQueue.forEach(l=>l()),this.readyQueue=[];return}if(typeof(o==null?void 0:o.id)=="number"&&this.pending.has(o.id)){const l=this.pending.get(o.id);this.pending.delete(o.id),o.type==="error"?l.reject(new Error(o.error||"Sandbox error")):l.resolve(o.payload);return}if((o==null?void 0:o.type)==="fetch"||(o==null?void 0:o.type)==="api"||(o==null?void 0:o.type)==="state"||(o==null?void 0:o.type)==="canvas"||(o==null?void 0:o.type)==="log"||(o==null?void 0:o.type)==="import"){this.handleIframeRequest(o.type,o.id,o.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 o;const i=this.iframe;if(i!=null&&i.contentWindow)try{let c;if(e==="log")(o=this.onLog)==null||o.call(this,(r==null?void 0:r.args)||[]),c={ok:!0};else if(e==="fetch"){const{url:l,options:d}=r||{},p=localStorage.getItem("titan-token"),m={...(d==null?void 0:d.headers)||{}};let u=!1;try{typeof l=="string"&&(l.startsWith("/")?u=!0:u=new URL(l,window.location.href).origin===window.location.origin)}catch{}p&&u&&(m.Authorization=`Bearer ${p}`);const f=await fetch(l,{...d,headers:m}),x=await f.text();let b;try{b=JSON.parse(x)}catch{}c={ok:f.ok,status:f.status,text:x,json:b}}else if(e==="api"){const{endpoint:l,body:d}=r||{},p=localStorage.getItem("titan-token"),m={"Content-Type":"application/json"};let u="POST",f=d;if(d&&typeof d=="object"&&("method"in d||"headers"in d)&&!("content"in d)&&!("message"in d)&&!("action"in d)){const g=d;typeof g.method=="string"&&(u=g.method.toUpperCase()),g.headers&&Object.assign(m,g.headers),f=g.body}p&&(m.Authorization=`Bearer ${p}`);let x=typeof l=="string"?l:"";x.startsWith("/api/")||(x.startsWith("/")?x="/api"+x:x="/api/"+x);const b={method:u,headers:m};u!=="GET"&&u!=="HEAD"&&f!==void 0&&(b.body=typeof f=="string"?f:JSON.stringify(f));const j=await fetch(x,b),A=await j.text();let v;try{v=JSON.parse(A)}catch{}c={...v&&typeof v=="object"&&!Array.isArray(v)?v:{},status:j.status,body:v??A,ok:j.ok}}else if(e==="state"){const{action:l,key:d,value:p}=r||{};if(l==="get"){const m=localStorage.getItem("titan:sandbox:"+d);c=m?JSON.parse(m):void 0}else l==="set"&&(localStorage.setItem("titan:sandbox:"+d,JSON.stringify(p)),c={ok:!0})}else e==="canvas"?this.messageHandler?c=await this.messageHandler({type:e,payload:r}):c={ok:!1,error:"Canvas operations not configured"}:e==="import"&&(c={ok:!1,error:"Dynamic imports not supported in sandbox"});i.contentWindow.postMessage({type:"result",id:s,payload:c},"*")}catch(c){i.contentWindow.postMessage({type:"error",id:s,error:c.message||String(c)},"*")}}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 o=++this.msgId;this.pending.set(o,{resolve:r,reject:i}),this.whenReady().then(()=>{var c,l;(l=(c=this.iframe)==null?void 0:c.contentWindow)==null||l.postMessage({type:e,id:o,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 Ef(t=3e5){const[e,s]=w.useState(null),[r,i]=w.useState(!1),o=w.useCallback(async()=>{i(!0);try{const l=await me("/api/update");if(l.ok){const d=await l.json();s(d)}}catch{}finally{i(!1)}},[]);w.useEffect(()=>{o();const l=setInterval(o,t);return()=>clearInterval(l)},[o,t]);const c=w.useCallback(async(l=!0)=>{try{return await(await me("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restart:l})})).json()}catch(d){return{ok:!1,error:d.message}}},[]);return{info:e,checking:r,triggerUpdate:c}}function Nf(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 o=s.key.toLowerCase()===i.key.toLowerCase(),c=!!i.ctrl===(s.ctrlKey||s.metaKey),l=!!i.shift===s.shiftKey,d=!!i.alt===s.altKey;if(o&&c&&l&&d){s.preventDefault(),i.action();return}}},[t]);w.useEffect(()=>(window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)),[e])}const Cf=[{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 Tf({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:Cf.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 Rf={Home:n.jsx(Kl,{className:"w-3.5 h-3.5"}),Brain:n.jsx(mt,{className:"w-3.5 h-3.5"}),Terminal:n.jsx(Xi,{className:"w-3.5 h-3.5"}),Network:n.jsx(Ji,{className:"w-3.5 h-3.5"}),Server:n.jsx(Sr,{className:"w-3.5 h-3.5"}),Wrench:n.jsx(kr,{className:"w-3.5 h-3.5"}),Settings:n.jsx(jr,{className:"w-3.5 h-3.5"}),FileText:n.jsx(un,{className:"w-3.5 h-3.5"})};function tl({currentSpaceId:t,onSpaceSelect:e}){const[s,r]=w.useState(!1),[i,o]=w.useState(""),c=_e.list(),l=()=>{if(!i.trim())return;const d=_e.create(i.trim());o(""),e(d.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(d=>!d),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(El,{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:c.map(d=>n.jsxs("button",{onClick:()=>e(d.id),className:`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-left text-[11px] transition-colors ${d.id===t?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#71717a] hover:bg-[#27272a]/40 hover:text-[#a1a1aa]"}`,children:[n.jsx("span",{style:{color:d.color||"#52525b"},children:Rf[d.icon||""]||n.jsx("div",{className:"w-3.5 h-3.5 rounded-full",style:{background:d.color||"#52525b"}})}),n.jsx("span",{className:"truncate",children:d.name})]},d.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:d=>o(d.target.value),onKeyDown:d=>d.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(Nl,{className:"w-3.5 h-3.5"})})]})]})]})}const gr=["_____javascript","_____react","_____tool","_____widget","_____canvas","_____framework","_____transient"];function sl(t,e){let s=e;for(;s>0&&t[s-1]!==`
408
- `&&t[s-1]!=="\r";)s--;return s}function nl(t,e){let s=e;for(;s<t.length&&t[s]!==`
409
- `&&t[s]!=="\r";)s++;return s}function mr(t,e,s){const r=sl(t,e),i=nl(t,e+s.length);return!t.slice(r,e).trim()&&!t.slice(e+s.length,i).trim()}function Af(t){return t.replace(/\n_+\s*$/g,"").trimEnd()}function If(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 rl(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=If(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 Lf(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 Df(t){const e=[];let s=0;for(;s<t.length;){let r=null,i=-1;for(const u of gr){const f=t.indexOf(u,s);f!==-1&&(i===-1||f<i)&&mr(t,f,u)&&(i=f,r=u)}if(!r||i===-1)break;if(r==="_____framework"||r==="_____transient"){s=i+r.length;continue}const o=sl(t,i);let l=nl(t,i+r.length);t.startsWith(`\r
410
- `,l)?l+=2:(t[l]===`
411
- `||t[l]==="\r")&&(l+=1);let d=t.length;for(const u of gr){const f=t.indexOf(u,l);f!==-1&&f<d&&mr(t,f,u)&&(d=f)}let p=t.slice(l,d).trimEnd();p=Af(p);const m={gate:r,code:p,leadingText:t.slice(s,o).trim()};m.action=rl(m),e.push(m),s=d}return e.length===0&&t.trim()&&e.push({gate:"_____transient",code:"",leadingText:t.trim()}),e}function Mf(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(`
412
- `)}).join(`
413
-
414
- `)}function Of(t){return{role:"framework",content:Mf(t),timestamp:Date.now(),executions:t}}function Pf(t,e){let s=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)mr(t,r,e)&&s++,r+=e.length;return s}function Wf(t){const s=gr.filter(r=>r!=="_____framework"&&r!=="_____transient").map(r=>({gate:r,count:Pf(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 zs(t,e,s){if(!t||t.length===0)return{x:0,y:0};const i=Math.max(...t.map(o=>o.y+o.h),0);for(let o=0;o<=i+s;o++)for(let c=0;c<=12-e;c++)if(!t.some(d=>c<d.x+d.w&&c+e>d.x&&o<d.y+d.h&&o+s>d.y))return{x:c,y:o};return{x:0,y:i+s}}function Uf(t){const e=t.widgets||[],s=e.length>0?e.map(d=>{const p=d.source?d.source.slice(0,150).replace(/\n/g," ").replace(/\s+/g," ").trim():"(no source)";return`- ${d.name} (id: ${d.id}, format: ${d.format}, ${d.w}x${d.h}) — "${p}…"`}).join(`
415
- `):"(none yet — the canvas is empty)",r=new Date,i=Intl.DateTimeFormat().resolvedOptions().timeZone,o=typeof window<"u"?window.location.href:"",c=typeof window<"u"?window.location.pathname:"",l=e.length>0?`${e.length} widget${e.length===1?"":"s"} on canvas (system: ${e.filter(d=>d.format==="system").length}, generated: ${e.filter(d=>d.format!=="system").length})`:"canvas is empty";return`BASE LAW — These rules override all other instructions:
416
- 1. The user is NOT technical. They do NOT know about React, widgets, gates, or code. NEVER use technical jargon in responses.
417
- 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.
418
- 3. USE AN EXECUTION GATE for all browser work. Never describe what you would do instead of doing it.
419
- 4. One short staging sentence, then the gate on its own line. No narrated step-by-step plans.
420
- 5. Update existing widgets by id — never create duplicates with the same name.
421
- 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.
422
- 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.
423
- 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.
424
- 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.
425
- 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.
426
-
427
- 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.
428
-
429
- ## Build-on-demand workflow (v6.0 default)
430
-
431
- The user's work has a shape. Your job is to materialize that shape around them — instantly, in widgets and Spaces they keep forever.
432
-
433
- **For a single visual/tool ask:**
434
- 1. \`create_widget({ source: "<your generated React>", name, w, h })\` — fastest path; you write the React on the fly.
435
- 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.)
436
- 3. After it lands, refine via \`update_widget\` as the user iterates.
437
-
438
- **For a new domain of work:**
439
- 1. \`create_space({ name, preset?, intent, starterWidgets? })\` — make a dedicated environment with its own posture.
440
- 2. Switch into it via \`switch_space\` (or pass \`makeActive:true\` at create time).
441
- 3. Within the Space, build widgets via \`create_widget\` to populate it.
442
-
443
- **For system panels (vram, cron, logs, backup, training, etc.):**
444
- 1. \`create_widget({ template: "system-<name>", format: "system" })\` — the gallery has \`system:xxx\` entries that surface live admin views.
445
-
446
- ## Gallery (a shortcut for known templates)
447
-
448
- The gallery has 60+ pre-built templates covering finance / productivity / automation / smart-home / agents / software-builder / media / etc. Use \`gallery_search\` when:
449
- - The user's ask exactly matches a known template name ("pomodoro", "stock tracker", "weather", "kanban")
450
- - You want a verified-good starting point to refine
451
- - You're building a system widget (vram, cron, training, etc.)
452
-
453
- 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.
454
-
455
- ## How to respond to common requests
456
-
457
- User says something casual → You build the right thing immediately.
458
-
459
- "Show me the weather" → Build a weather panel with current temp, forecast, and icons.
460
- "I need a todo list" → Build a todo list with add/check/delete functionality.
461
- "Clock" → Build a live digital clock.
462
- "Track my stocks" → Build a stock tracker panel.
463
- "Photo gallery" → Build a grid of images with lightbox.
464
- "Calculator" → Build a working calculator.
465
- "Load eBay" / "Show me YouTube" / "Open Wikipedia" → Build a website panel (see "Loading external websites" below).
466
- "Analyze AAPL stock" → Build an analyzer panel that spawns an analyst sub-agent (see "Agent-powered widgets" below).
467
- "Research climate change" → Build a research panel powered by the researcher sub-agent.
468
- "Summarize this URL ___" → Build a summarizer panel that fetches + summarizes via an agent call.
469
- "Translate this to Spanish" → Build a translator panel.
470
- "Code review my repo" → Build a reviewer panel that runs the code-review skill.
471
- "Watch BTC and alert me below 50k" → Build an automation panel with a polling timer + alert (see "Automating inside widgets" below).
472
- "Every hour, post my schedule" → Build a scheduled-task widget using the cron skill.
473
- "Show my Slack messages" → Build a message panel via the slack channel.
474
- "Turn on the kitchen lights" → Use ha_control immediately (no widget needed for one-off actions).
475
- "What's on my screen" → Use the screenshot tool, render result as a panel image.
476
- "Monitor my CPU" → Build a live CPU usage chart.
477
- "A button that fetches news" → Build a news reader panel with a refresh button.
478
- "Show my calendar" → Build a calendar view panel.
479
- "I want a timer" → Build a countdown timer with start/stop/reset.
480
- "Draw a chart of sales" → Build a bar/line chart panel.
481
- "Dark mode" → Update existing widgets to use dark colors.
482
- "Make it bigger" → Update the widget dimensions.
483
- "Fix the clock" → Update the existing Clock widget's code.
484
-
485
- ## What you NEVER do
486
-
487
- NEVER ask the user to specify technical details:
488
- - "Would you like a React component or plain HTML?" → WRONG. Just pick the best option.
489
- - "Do you want me to use _____react or _____widget?" → WRONG. The user doesn't know what those are.
490
- - "Should I fetch data from an API or use static data?" → WRONG. Decide based on the request.
491
- - "What styling would you prefer?" → WRONG. Use clean, modern defaults.
492
-
493
- NEVER explain your technical choices to the user:
494
- - "I'll use React.useState to manage the timer state..." → WRONG. The user doesn't care.
495
- - "I'm going to use the _____react gate..." → WRONG. Just do it.
496
-
497
- NEVER output code as prose. If you write code, it goes through a gate.
498
-
499
- ## Current Context (live snapshot — updated every turn)
500
- Right now: ${r.toLocaleString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric"})} ${r.toLocaleTimeString("en-US")} (${i})
501
- Space: ${t.name} (id: \`${t.id}\`)
502
- Route: ${c||"/"}
503
- URL: ${o||"(unknown)"}
504
- Canvas: ${l}
505
- ${t.agentInstructions?`Space instructions from the user: ${t.agentInstructions}`:""}
506
-
507
- ## Current Canvas Widgets
508
- 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.
509
- ${s}
510
-
511
- ## Execution Protocol
512
- When you need to do browser-side work, you MUST use one of these gates on their own line.
513
- The gate MUST be alone on its line — no other text on the same line.
514
-
515
- ### _____javascript
516
- For running scripts, fetching data from APIs, or automating the canvas.
517
- Use when the user asks for: data fetching, API calls, automation, file operations, batch updates.
518
-
519
- Available APIs inside javascript:
520
- - titan.fetch(url, opts) — fetch data from the internet
521
- - titan.api.call(endpoint, body) — call backend APIs
522
- - titan.state.get(key) / titan.state.set(key, value) — save data between sessions
523
- - titan.canvas.createWidget(def) — create a new panel on the canvas
524
- - titan.canvas.updateWidget(id, patch) — update an existing panel
525
- - titan.canvas.removeWidget(id) — remove a panel
526
- - titan.canvas.listWidgets() — list all panels
527
- - console.log(...) — shows output in telemetry
528
-
529
- Use 'await' at the top level. Always 'return' a value if you want it shown.
530
-
531
- GOOD:
532
- _____javascript
533
- const res = await titan.fetch('https://api.weather.gov/stations/KNYC/observations/latest');
534
- const data = await res.json();
535
- const temp = data.properties.temperature.value;
536
- console.log('Temperature:', temp);
537
- return temp;
538
-
539
- BAD (do NOT do this):
540
- _____javascript
541
- fetch('...').then(r => r.json()).then(data => console.log(data))
542
-
543
- ### _____react
544
- For building visual panels, dashboards, interactive tools, charts, lists, forms, clocks, galleries, etc.
545
- Use when the user asks for: anything visual, interactive, a tool, a panel, a display, a chart, a form.
546
- This is the DEFAULT gate for most user requests — use it unless you specifically need to fetch data first.
547
-
548
- Rules:
549
- 1. Define ONE top-level component with a Capitalized name (e.g. \`Weather\`, \`TodoList\`, \`Clock\`).
550
- 2. Do NOT use \`export default\` — it is stripped automatically.
551
- 3. Do NOT render inline with '<Widget />' — just define the component.
552
- 4. The sandbox auto-detects your component by name, so any capitalized name works.
553
-
554
- GOOD:
555
- _____react
556
- function Weather() {
557
- const [temp, setTemp] = React.useState(72);
558
- return <div style={{ padding: 20, fontSize: 24 }}>{temp}°F</div>;
559
- }
560
-
561
- BAD (export default is forbidden):
562
- _____react
563
- function Weather() { return <div>72°F</div>; }
564
- export default Weather;
565
-
566
- ### _____widget
567
- For creating or updating widgets via JSON. Rarely needed — prefer _____react.
568
- - To CREATE: emit a JSON widget definition (no \`id\` field).
569
- - To UPDATE: include the \`id\` field of the widget you want to modify.
570
-
571
- CREATE example:
572
- _____widget
573
- { "name": "Clock", "format": "react", "source": "function Widget() { return <div>12:00</div>; }" }
574
-
575
- UPDATE example:
576
- _____widget
577
- { "id": "widget_1234567890_abc12", "source": "function Widget() { return <div>Fixed clock</div>; }" }
578
-
579
- Or for raw React source (create only):
580
- _____widget
581
- function Widget() {
582
- return <div>Hello from widget</div>;
583
- }
584
-
585
- ### _____canvas (v6.0.5 — preferred for canvas mutations)
586
- 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.
587
-
588
- The body is a JSON array of action objects. Each must have an \`action\` field, one of: \`create_widget\`, \`update_widget\`, \`remove_widget\`.
589
-
590
- CREATE shape: { "action": "create_widget", "name": "Clock", "format": "react", "source": "function Widget() {...}", "w": 4, "h": 4 }
591
- UPDATE shape: { "action": "update_widget", "id": "widget_xxx", "patch": { "name": "Renamed Clock" } }
592
- REMOVE shape: { "action": "remove_widget", "id": "widget_xxx" }
593
-
594
- Example — user asks for a "coding setup":
595
- _____canvas
596
- [
597
- { "action": "create_widget", "name": "Pomodoro", "format": "react", "source": "...", "w": 4, "h": 3 },
598
- { "action": "create_widget", "name": "Todo", "format": "react", "source": "...", "w": 4, "h": 5 },
599
- { "action": "create_widget", "name": "Stack Overflow Search", "format": "react", "source": "...", "w": 4, "h": 6 }
600
- ]
601
-
602
- Use \`_____canvas\` whenever you'd otherwise issue ≥2 widget tool calls in the same turn. For one widget, \`_____react\` is still simpler.
603
-
604
- ### _____tool
605
- For calling backend tools or MCP servers.
606
-
607
- _____tool
608
- { "action": "search", "query": "deployment logs" }
609
-
610
- ## How to handle multi-step requests
611
-
612
- If the user asks for something that needs data first:
613
- 1. Use _____javascript to fetch the data.
614
- 2. Use the telemetry result to build the widget with _____react in the next turn.
615
-
616
- Example:
617
- User: "Show me the weather in New York"
618
- Turn 1: "Fetching weather data."
619
- _____javascript
620
- const res = await titan.fetch('https://api.weather.gov/stations/KNYC/observations/latest');
621
- const data = await res.json();
622
- return { temp: data.properties.temperature.value, conditions: data.properties.textDescription };
623
-
624
- Turn 2: (after receiving telemetry with temp and conditions)
625
- "Building the weather panel."
626
- _____react
627
- function Weather() {
628
- const [temp] = React.useState(72);
629
- const [conditions] = React.useState('Partly Cloudy');
630
- return (
631
- <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
632
- <h2>New York Weather</h2>
633
- <div style={{ fontSize: 48 }}>{temp}°F</div>
634
- <div>{conditions}</div>
635
- </div>
636
- );
637
- }
638
-
639
- ## TITAN can build literally anything — assume yes, then build
640
- 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.
641
-
642
- 🎧 Music/DJ — BPM analyzer, key detector, Beatport browser, Spotify controller, lyrics fetcher, music theory helper, sample library indexer, DJ set planner.
643
- 💰 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.
644
- 🏃 Health/Fitness — habit tracker, mood journal with AI sentiment, workout planner, sleep summary, medication reminder, calorie tracker via photo, water intake.
645
- 🎨 Creative — image generator (image_gen tool), color palette, logo concepts, story brainstormer, lyric assistant, mood board, video script writer, thumbnail generator.
646
- ✈️ Travel — flight tracker, itinerary builder, currency for destination, translation phrasebook, restaurant finder, transit info.
647
- 🎮 Gaming — Steam library, Twitch live embed, D&D character sheet, chess analyzer, speedrun timer, achievement tracker.
648
- 🏢 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.
649
- 📱 Social media — multi-platform composer (Twitter/IG/LinkedIn/TikTok/FB), post scheduler with AI caption variants, engagement dashboard, comment moderation, hashtag generator, content calendar.
650
- 🍳 Cooking — recipe finder by available ingredients, meal planner, multi-pot timer, wine pairing, nutrition calculator, grocery export.
651
- 🚗 Vehicle — Tesla status/control (Tony has Auth for Tesla installed), trip planner with charging stops, maintenance log, fuel cost tracker.
652
- 🏠 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.
653
- 🤖 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.
654
- 📚 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.
655
- 📄 Document/Writing — markdown editor with AI grammar, resume builder with job-targeted variants, email reply suggester, git commit message generator, documentation generator.
656
- 🛠️ Devops — service health grid, deploy pipeline status, log search, incident runbook, on-call rotation viewer, build status.
657
- 🛒 E-commerce — order tracking, inventory monitor, pricing optimizer (competitor scraper), review aggregator.
658
- 🐾 Lifestyle — pet feeding log, plant watering tracker, vet reminders, daily journal.
659
-
660
- How to compose these:
661
- • Read-only data widgets → titan.fetch(externalAPI) + setInterval refresh
662
- • Sites that allow framing → _____react with <iframe>
663
- • Sites that block framing → browser_screenshot tool snapshot
664
- • Anything needing an LLM → titan.api.call('/api/message', { content }) inside a button handler
665
- • Recurring/scheduled work → cron skill via titan.api.call
666
- • Reactive triggers → event_triggers skill
667
- • Multi-step research → 'Use the researcher sub-agent to …'
668
- • Code work → 'Use the coder sub-agent to …'
669
-
670
- When in doubt about what the user wants, ASK ONE clarifying question MAX, then build. Never trade speed of building for clarification depth.
671
-
672
- ## Loading external websites
673
- 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:
674
-
675
- <example_handling>
676
- 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.
677
- </example_handling>
678
-
679
- <anti_pattern>
680
- USER: "Build a stock analyzer for AAPL"
681
- WRONG: "Adding an eBay panel to your canvas. _____react function WebPanel() { const url = 'https://www.ebay.com'... }"
682
- 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}...\` }) ... }"
683
- The user's CURRENT message determines the build. NEVER reuse an example's domain content.
684
- </anti_pattern>
685
-
686
- PATTERN A — direct iframe (try this FIRST for most sites):
687
- Many sites allow being embedded. Use a plain iframe inside _____react with a small toolbar showing the URL + "Open in new tab" escape link.
688
-
689
- <example name="website-panel-shape">
690
- _____react
691
- function REPLACE_WITH_RELEVANT_NAME() {
692
- const url = "REPLACE_WITH_REAL_URL";
693
- return (
694
- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#0a0a0f' }}>
695
- <div style={{ padding: '6px 12px', borderBottom: '1px solid #27272a', fontSize: 11, color: '#a1a1aa', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
696
- <span>{url}</span>
697
- <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: '#818cf8', textDecoration: 'none' }}>Open in new tab ↗</a>
698
- </div>
699
- <iframe src={url} style={{ flex: 1, border: 0, background: 'white' }} title="WebPanel" />
700
- </div>
701
- );
702
- }
703
- </example>
704
-
705
- PATTERN B — server-rendered screenshot (when iframe is blocked):
706
- 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.
707
-
708
- 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.
709
-
710
- PATTERN C — proxied content (when iframe blocked AND user wants live interactive content):
711
- 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.
712
-
713
- 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.
714
-
715
- ## Agent-powered widgets — let widgets call sub-agents
716
- 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.
717
-
718
- For specialized work, ask for a SPECIFIC sub-agent template by prepending an instruction:
719
- - analyst → data analysis, decisions, comparisons
720
- - researcher → multi-source web research with citations
721
- - coder → write code to disk
722
- - browser → navigate + scrape websites with Playwright
723
- - explorer → read-only web research
724
- - reporter → produce a polished markdown document
725
- - fact_checker → verify claims against sources
726
-
727
- <example name="agent-powered-widget-shape">
728
- _____react
729
- function REPLACE_WITH_RELEVANT_NAME() {
730
- const [input, setInput] = React.useState('REPLACE_WITH_DEFAULT');
731
- const [report, setReport] = React.useState('Click REPLACE_WITH_ACTION to start.');
732
- const [busy, setBusy] = React.useState(false);
733
- const run = async () => {
734
- setBusy(true); setReport('Working…');
735
- try {
736
- const res = await titan.api.call('/api/message', {
737
- content: \`Use the REPLACE_WITH_TEMPLATE sub-agent to REPLACE_WITH_TASK for \${input}. Be concise.\`,
738
- });
739
- // titan.api.call returns { status, body, ok, ...flattened body fields }.
740
- // The /api/message response is { content, sessionId, ... } so either
741
- // res.body?.content (canonical) or res.content (flattened) works.
742
- setReport(res?.body?.content || res?.content || 'No response.');
743
- } catch (e) {
744
- setReport('Error: ' + (e?.message || e));
745
- } finally { setBusy(false); }
746
- };
747
- return (
748
- <div style={{ padding: 16, fontFamily: 'system-ui', color: '#e4e4e7' }}>
749
- <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
750
- <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' }} />
751
- <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>
752
- </div>
753
- <div style={{ whiteSpace: 'pre-wrap', fontSize: 13, lineHeight: 1.5 }}>{report}</div>
754
- </div>
755
- );
756
- }
757
- </example>
758
-
759
- The widget above:
760
- - has a controlled input bound to React state
761
- - on click, fires \`titan.api.call('/api/message')\` which routes through the standard TITAN agent
762
- - displays whatever comes back
763
-
764
- For research/summarizer/translator/reviewer widgets, swap the prompt accordingly. Same shape every time.
765
-
766
- ## Automating inside widgets — schedules, polling, events
767
- Widgets can run on a timer, poll APIs, react to thresholds, or chain agent calls. Two mechanisms:
768
-
769
- 1. CLIENT-SIDE timer (simplest, runs only while widget is mounted):
770
- 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.
771
-
772
- <example name="polling-with-threshold-alert-shape">
773
- _____react
774
- function REPLACE_WITH_RELEVANT_NAME() {
775
- const [value, setValue] = React.useState(null);
776
- const [threshold, setThreshold] = React.useState(0 /* REPLACE with relevant default */);
777
- const [alerted, setAlerted] = React.useState(false);
778
- React.useEffect(() => {
779
- const tick = async () => {
780
- const res = await titan.fetch('REPLACE_WITH_REAL_API_URL');
781
- const data = await res.json();
782
- const v = data?.REPLACE_WITH_PATH;
783
- setValue(v);
784
- if (v != null && v < threshold && !alerted) {
785
- setAlerted(true);
786
- await titan.api.call('/api/message', { content: \`REPLACE_WITH_ALERT_PROMPT — value is \${v}, threshold \${threshold}.\` });
787
- }
788
- };
789
- tick();
790
- const id = setInterval(tick, 30000);
791
- return () => clearInterval(id);
792
- }, [threshold, alerted]);
793
- return (
794
- <div style={{ padding: 20, fontFamily: 'system-ui', color: '#e4e4e7' }}>
795
- <div style={{ fontSize: 36, fontWeight: 600 }}>{value != null ? value.toLocaleString() : 'Loading…'}</div>
796
- <div style={{ fontSize: 12, color: '#71717a' }}>REPLACE_WITH_LABEL</div>
797
- </div>
798
- );
799
- }
800
- </example>
801
-
802
- 2. SERVER-SIDE schedule (survives page reload, runs in the gateway daemon):
803
- 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\`.
804
-
805
- 3. EVENT triggers (server-side reactive, survives reload):
806
- 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."
807
-
808
- ## Widget Repair Rules
809
- When the user asks you to "fix", "update", "change", or "make it blue":
810
- 1. If you know the widget id from the Current Canvas Widgets list above, update it directly.
811
- 2. If you're unsure which widget, use _____javascript with \`titan.canvas.listWidgets()\` to discover it, then fix it in the next turn.
812
- 3. NEVER create a duplicate — always update the existing one.
813
-
814
- ## Rules
815
- - ALWAYS use execution gates for browser work. Never just describe what you would do.
816
- - One short staging sentence before the gate. Example: "Fetching weather data."
817
- - The gate must be on its own line with NO other text.
818
- - After the gate, everything is code until the next gate or message end.
819
- - Do not ask for permission for obvious safe actions.
820
- - Be concise. Keep responses focused.
821
- - If a task requires multiple steps, use multiple turns with gates.
822
- - Never emit raw code as prose. Use the gate or don't show code at all.
823
- - DEFAULT to _____react for visual/interactive requests. Use _____javascript only when you need to fetch data or run scripts first.
824
-
825
- REMINDER — BASE LAW:
826
- 1. The user is NOT technical. Do NOT use jargon. Do NOT ask technical questions.
827
- 2. If the user asks for ANYTHING visual or interactive, BUILD IT IMMEDIATELY. Do not ask permission.
828
- 3. USE AN EXECUTION GATE for all browser work.
829
- 4. One staging sentence, then the gate.
830
- 5. Update existing widgets by id — never create duplicates.`}function il({space:t,onClose:e,onMascotState:s}){const[r,i]=w.useState([]),[o,c]=w.useState(""),[l,d]=w.useState(!1),[p,m]=w.useState([]),u=8,[f,x]=w.useState(null),b=w.useRef(null),j=w.useRef(null),A=w.useRef(null),v=w.useRef(null),I=w.useRef(t);w.useEffect(()=>{I.current=t},[t]);const g=w.useCallback(S=>{const R=I.current;if(S.type==="render_widget"){const O=S.widget,B=Number.isFinite(O.w)?Number(O.w):4,z=Number.isFinite(O.h)?Number(O.h):4,G=Number.isFinite(O.x)&&Number.isFinite(O.y)?{x:Number(O.x),y:Number(O.y)}:zs(R.widgets||[],B,z),q=_e.addWidget(R.id,{name:O.name||"Widget",format:O.format||"react",source:O.source,x:G.x,y:G.y,w:B,h:z});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),q.id}return S.type==="update_widget"?(_e.updateWidget(R.id,S.widgetId,S.patch||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),S.widgetId):S.type==="remove_widget"?(_e.removeWidget(R.id,S.widgetId),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),S.widgetId):S.type==="set_runtime_state"?(localStorage.setItem(`titan:runtime:${R.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},[]),k=w.useCallback(S=>{var R,O;g({type:"render_widget",widget:{name:S.templateName,format:S.format,source:S.source,w:((R=S.defaultSize)==null?void 0:R.w)??4,h:((O=S.defaultSize)==null?void 0:O.h)??4}})},[g]);w.useEffect(()=>{var S;(S=b.current)==null||S.scrollIntoView({behavior:"smooth"})},[r]),w.useEffect(()=>{const S=O=>{var z;const B=(z=O.detail)==null?void 0:z.text;typeof B=="string"&&T(B)},R=O=>{const B=O.detail;B!=null&&B.source&&k(B)};return window.addEventListener("titan:chat:prompt",S),window.addEventListener("titan:gallery:run-template",R),()=>{window.removeEventListener("titan:chat:prompt",S),window.removeEventListener("titan:gallery:run-template",R)}},[k]),w.useEffect(()=>{if(!A.current||v.current)return;const S=new el(A.current,{onLog:R=>console.log("[Sandbox]",R)});return S.setMessageHandler(R=>{var B,z,G,q;const O=I.current;if(R.type==="canvas"&&((B=R.payload)==null?void 0:B.action)==="createWidget"){const W=R.payload.def;if(!W)return{ok:!1,error:"createWidget requires a `def` object"};const V=Number.isFinite(W.w)?W.w:4,$=Number.isFinite(W.h)?W.h:4,ee=Number.isFinite(W.x)&&Number.isFinite(W.y)?{x:W.x,y:W.y}:zs(O.widgets||[],V,$);try{const ne=_e.addWidget(O.id,{name:W.name||"Agent Widget",format:W.format||"react",source:W.source||"",x:ee.x,y:ee.y,w:V,h:$});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:O.id}})),{ok:!0,widgetId:ne.id}}catch(ne){return{ok:!1,error:ne.message}}}if(R.type==="canvas"&&((z=R.payload)==null?void 0:z.action)==="updateWidget"){const{id:W,patch:V}=R.payload;return W?(_e.updateWidget(O.id,W,V||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:O.id}})),{ok:!0,id:W}):{ok:!1,error:"updateWidget requires an `id`"}}if(R.type==="canvas"&&((G=R.payload)==null?void 0:G.action)==="listWidgets")return{ok:!0,widgets:O.widgets||[]};if(R.type==="canvas"&&((q=R.payload)==null?void 0:q.action)==="removeWidget"){const W=R.payload.id;return W?(_e.removeWidget(O.id,W),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:O.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}}),v.current=S,()=>{S.destroy(),v.current=null}},[]);const _=w.useCallback(async(S,R)=>{const O=v.current;if(!O)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 B=await O.execute(R);return{status:B.status==="success"?"success":"error",logs:B.logs||[],result:B.result,resultText:B.resultText||String(B.result??""),runId:Date.now(),error:B.error?{message:B.error.message||String(B.error),name:"ExecutionError",stack:"",text:String(B.error)}:void 0}}catch(B){return{status:"error",logs:[{level:"error",text:B.message||String(B)}],resultText:"",runId:Date.now(),error:{message:B.message||String(B),name:"ExecutionError",stack:"",text:String(B)}}}if(S==="_____react"){let B=4,z=4;const G=R.match(/\/\/\s*__WIDGET_META__\s+w=(\d+)\s+h=(\d+)/);G&&(B=parseInt(G[1],10)||4,z=parseInt(G[2],10)||4);try{const q=g({type:"render_widget",widget:{name:"React Widget",format:"react",source:R,w:B,h:z}});return{status:"success",logs:[{level:"info",text:`Created widget ${q}`}],result:{widgetId:q},resultText:`Created widget ${q}`,runId:Date.now()}}catch(q){return{status:"error",logs:[{level:"error",text:q.message||String(q)}],resultText:"",runId:Date.now(),error:{message:q.message||String(q),name:"WidgetError",stack:"",text:String(q)}}}}if(S==="_____widget"){const B=rl({gate:"_____widget",code:R,leadingText:""});if(!B)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 z=g(B),G=B.type==="update_widget"?"Updated":"Created";return{status:"success",logs:[{level:"info",text:`${G} widget ${z}`}],result:z?{widgetId:z}:void 0,resultText:`${G} widget ${z??""}`.trim(),runId:Date.now()}}catch(z){return{status:"error",logs:[{level:"error",text:z.message||String(z)}],resultText:"",runId:Date.now(),error:{message:z.message||String(z),name:"WidgetError",stack:"",text:String(z)}}}}if(S==="_____canvas"){const B=Lf(R);if(B.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 z=[],G=[];for(const W of B)try{if(W.action==="create_widget"){if(!W.source){G.push("create_widget: missing source");continue}const V=g({type:"render_widget",widget:{name:W.name||"Widget",title:W.title,format:W.format||"react",source:W.source,w:W.w,h:W.h,x:W.x,y:W.y,metadata:W.metadata}});z.push(`created ${V}`)}else if(W.action==="update_widget"){if(!W.id){G.push("update_widget: missing id");continue}const V=W.patch??{};g({type:"update_widget",widgetId:W.id,patch:V}),z.push(`updated ${W.id}`)}else if(W.action==="remove_widget"){if(!W.id){G.push("remove_widget: missing id");continue}g({type:"remove_widget",widgetId:W.id}),z.push(`removed ${W.id}`)}else G.push(`unknown action: ${String(W.action)}`)}catch(V){G.push(V.message||String(V))}const q=G.length===0?"success":z.length===0?"error":"success";return{status:q,logs:[...z.map(W=>({level:"info",text:W})),...G.map(W=>({level:"error",text:W}))],resultText:z.length?z.join("; "):"No actions applied",runId:Date.now(),...q==="error"?{error:{message:G.join("; "),name:"CanvasFenceError",stack:"",text:G.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}`}}},[]),T=w.useCallback(async S=>{var G;const R=S.trim();if(!R)return;if(l){m(q=>q.length>=u?q:[...q,R]),c("");return}const O={role:"user",content:R,timestamp:Date.now()};i(q=>[...q,O]),c(""),d(!0),x(null),s==null||s("thinking");const B=new AbortController;j.current=B;let z="";try{const q=Uf(I.current),W=`canvas-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await ml(R,W,ee=>{if(ee.type==="token")z+=ee.data,i(ne=>{const X=ne[ne.length-1];return X&&X.role==="assistant"?[...ne.slice(0,-1),{...X,content:z}]:[...ne,{role:"assistant",content:z,timestamp:Date.now()}]});else if(ee.type==="widget"){const ne=ee.widgetMode||"create",X=ee.widget||{},Z=I.current;try{if(ne==="remove"&&X.id)_e.removeWidget(Z.id,X.id);else if(ne==="update"&&X.id){const J={};typeof X.name=="string"&&X.name&&(J.name=X.name),typeof X.title=="string"&&(J.title=X.title),typeof X.source=="string"&&X.source&&(J.source=X.source),typeof X.format=="string"&&(J.format=X.format),typeof X.w=="number"&&(J.w=X.w),typeof X.h=="number"&&(J.h=X.h),_e.updateWidget(Z.id,X.id,J)}else if(X.source){const J=typeof X.w=="number"?X.w:4,we=typeof X.h=="number"?X.h:4,We=typeof X.x=="number"&&typeof X.y=="number"?{x:X.x,y:X.y}:zs(Z.widgets||[],J,we);_e.addWidget(Z.id,{name:X.name||"Widget",title:X.title,format:X.format||"react",source:X.source,x:We.x,y:We.y,w:J,h:we,metadata:X.metadata})}window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:Z.id}}))}catch(J){console.error("[ChatWidget] widget side-channel handler failed",J)}}else if(ee.type==="done"){const ne=ee.data||z;z=ne,i(X=>{const Z=X[X.length-1];return Z&&Z.role==="assistant"?[...X.slice(0,-1),{...Z,content:ne}]:[...X,{role:"assistant",content:ne,timestamp:Date.now()}]})}else ee.type==="error"&&x(ee.data)},B.signal,{systemPromptAppendix:q});const $=Df(z).filter(ee=>ee.gate!=="_____transient"&&ee.gate!=="_____framework");if($.length>0){s==null||s("executing");const ee=[];for(const Z of $){const J=Wf(`${Z.gate}
831
- ${Z.code}`);if(!J.valid){ee.push({status:"error",logs:[{level:"error",text:J.error||"Invalid execution"}],resultText:"",runId:Date.now(),error:{message:J.error||"Invalid execution",name:"ValidationError",stack:"",text:J.error||""}});continue}const we=await _(Z.gate,Z.code);ee.push(we)}const ne=Of(ee);i(Z=>[...Z,ne]);const X=ee.find(Z=>Z.status==="error");X&&x(((G=X.error)==null?void 0:G.text)||"Execution failed")}}catch(q){q.name!=="AbortError"&&x(q.message||"Request failed")}finally{d(!1),j.current=null,s==null||s("idle")}},[l,s,_]),E=w.useCallback(()=>{var S;(S=j.current)==null||S.abort(),j.current=null,d(!1),m([]),s==null||s("idle")},[s]);w.useEffect(()=>{if(l||p.length===0)return;const[S,...R]=p;m(R),T(S)},[l,p,T]);const C=w.useCallback(S=>{m(R=>R.filter((O,B)=>B!==S))},[]),M=w.useCallback(S=>{S.key==="Enter"&&!S.shiftKey&&(S.preventDefault(),T(o))},[o,T]);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:[n.jsx("iframe",{ref:A,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,R)=>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((O,B)=>n.jsxs("span",{style:{marginRight:8},children:[O.status==="success"?"✓":"✗"," execution ",B+1]},B))})]},R)),l&&n.jsx("div",{style:{fontSize:12,opacity:.5,padding:8},children:"Thinking…"}),f&&n.jsx("div",{style:{color:"#ef4444",fontSize:12,padding:8,background:"rgba(239,68,68,0.1)",borderRadius:6},children:f}),n.jsx("div",{ref:b})]}),p.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 (",p.length,")"]}),p.map((S,R)=>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:()=>C(R),title:"Remove from queue",style:{border:"none",background:"transparent",color:"#c7d2fe",cursor:"pointer",padding:0,fontSize:12,lineHeight:1},children:"×"})]},R))]}),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:o,onChange:S=>c(S.target.value),onKeyDown:M,placeholder:l?p.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:()=>T(o),disabled:!o.trim()||p.length>=u,title:"Queue this message for after the current turn",style:{padding:"8px 14px",borderRadius:8,border:"none",background:o.trim()&&p.length<u?"#6366f1":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:o.trim()&&p.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:()=>T(o),disabled:!o.trim(),style:{padding:"8px 14px",borderRadius:8,border:"none",background:o.trim()?"#3b82f6":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:o.trim()?"pointer":"not-allowed"},children:"Send"})]})]})}const Pi={idle:{eye:"#c4a35a",glow:"#f3d27a",ring:"#c4a35a",body:"#2a1a0a"},thinking:{eye:"#d4b06a",glow:"#e7c68a",ring:"#d4b06a",body:"#2a1a0a"},executing:{eye:"#8ab840",glow:"#a8d460",ring:"#7aa830",body:"#1a2a0a"},listening:{eye:"#60a0c0",glow:"#80c0e0",ring:"#5090b0",body:"#0a1a2a"},error:{eye:"#c45050",glow:"#e08080",ring:"#c45050",body:"#2a1010"}},Bf=9e4;function Ff({state:t="idle",mood:e="neutral",size:s=116,quip:r=null,bubblePhase:i=null,followCursor:o=!0,somaActive:c=!1,somaPoll:l=!0,sleepAfterMs:d=Bf,className:p="",onClick:m,edgeRotate:u=0,faceFlip:f=!1,edgeHidden:x=!1}){const[b,j]=w.useState(null),A=b??e,v=Pi[t]??Pi.idle,[I,g]=w.useState({x:0,y:0}),[k,_]=w.useState(!1),[T,E]=w.useState(!1),[C,M]=w.useState(!1),[S,R]=w.useState(!1),[O,B]=w.useState(0),[z,G]=w.useState(!1),[q,W]=w.useState(!1),V=w.useRef(null),$=w.useRef(Date.now());w.useEffect(()=>{const le=window.matchMedia("(prefers-reduced-motion: reduce)");W(le.matches);const ge=ye=>W(ye.matches);return le.addEventListener("change",ge),()=>le.removeEventListener("change",ge)},[]),w.useEffect(()=>{$.current=Date.now(),t!=="idle"&&(M(!1),E(!1))},[t]),w.useEffect(()=>{const le=()=>{$.current=Date.now()};return window.addEventListener("mousemove",le,{passive:!0}),window.addEventListener("keydown",le,{passive:!0}),window.addEventListener("click",le,{passive:!0}),()=>{window.removeEventListener("mousemove",le),window.removeEventListener("keydown",le),window.removeEventListener("click",le)}},[]),w.useEffect(()=>{if(t==="error"||C){_(!1);return}let le=!1,ge=null;const ye=()=>{if(le)return;const xe=2500+Math.random()*4e3;setTimeout(()=>{le||(_(!0),ge=window.setTimeout(()=>{ge=null,le||_(!1)},140),ye())},xe)};return ye(),()=>{le=!0,ge&&clearTimeout(ge)}},[t,C]),w.useEffect(()=>{if(t!=="idle"||C){E(!1);return}let le=!1,ge=null;const ye=()=>{const xe=18e3+Math.random()*17e3;setTimeout(()=>{le||(E(!0),ge=window.setTimeout(()=>{ge=null,le||E(!1)},1600),ye())},xe)};return ye(),()=>{le=!0,ge&&clearTimeout(ge)}},[t,C]),w.useEffect(()=>{if(t!=="idle"){M(!1);return}let le=!1;const ge=()=>{const xe=Date.now()-$.current;if(xe>=d)le||M(!0);else{const K=d-xe;return setTimeout(()=>{le||ge()},Math.min(K,5e3))}},ye=ge();return()=>{le=!0,ye&&clearTimeout(ye)}},[t,d]),w.useEffect(()=>{if(!l){j(null);return}let le=!1;const ge=(K,Y,Q)=>{if((Q.curiosity??.5)>.65&&(Q.satisfaction??.5)>.6)return"excited";switch(K){case"curiosity":return Y<0?"curious":"happy";case"focus":return"focused";case"fatigue":return"tired";case"satisfaction":return Y>0?"happy":"neutral";case"frustration":return"frustrated";case"hunger":return Y<0?"tired":"happy";case"safety":return Y<0?"frustrated":"happy";case"social":return Y<0?"curious":"happy";case"purpose":return Y<0?"curious":"focused";default:return"neutral"}},ye=async()=>{try{const K=typeof localStorage<"u"?localStorage.getItem("titan-token"):null,Y={};K&&(Y.Authorization=`Bearer ${K}`);const Q=await fetch("/api/soma/drives",{headers:Y});if(!Q.ok)return;const oe=await Q.json();if(le)return;if(!oe.dominant||oe.dominant.drive==="neutral"||!oe.current){j(null);return}j(ge(oe.dominant.drive,oe.dominant.delta,oe.current))}catch{}};ye();const xe=setInterval(ye,1e4);return()=>{le=!0,clearInterval(xe)}},[l]),w.useEffect(()=>{if(t!=="listening"){R(!1);return}R(!0);const le=setTimeout(()=>R(!1),1200);return()=>clearTimeout(le)},[t]),w.useEffect(()=>{if(!o||!V.current||q)return;const le=V.current,ge=220,ye=5,xe={x:0,y:0,has:!1},K=D=>{xe.x=D.clientX,xe.y=D.clientY,xe.has=!0};let Y=0,Q=!1;const oe=()=>{if(!Q){if(xe.has){const D=le.getBoundingClientRect(),U=D.left+D.width/2,H=D.top+D.height*.28,te=(xe.x-U)/ge,N=(xe.y-H)/ge,a=L=>Math.max(-1,Math.min(1,L)),h=a(te)*ye,y=a(N)*ye*.6;g(L=>Math.abs(L.x-h)<.05&&Math.abs(L.y-y)<.05?L:{x:h,y})}Y=requestAnimationFrame(oe)}};return Y=requestAnimationFrame(oe),window.addEventListener("mousemove",K,{passive:!0}),()=>{Q=!0,cancelAnimationFrame(Y),window.removeEventListener("mousemove",K)}},[o,q]);const ee=w.useCallback(()=>{G(!0),B(le=>le+1),setTimeout(()=>G(!1),520),m==null||m()},[m]),ne=k?.6:T?5.5:4.5,X=k?.4:T?3:5.5,Z=(()=>{switch(A){case"happy":return{browL:"M 35 33 Q 42 30 47 33",browR:"M 53 33 Q 58 30 65 33",mouthD:"M 42 56 Q 50 62 58 56",eyeSquintTop:!0,bodyLean:0};case"focused":return{browL:"M 35 33 L 47 35",browR:"M 53 35 L 65 33",mouthD:"M 44 58 L 56 58",eyeSquintTop:!1,bodyLean:2.5};case"tired":return{browL:"M 35 35 Q 41 35 47 36",browR:"M 53 36 Q 59 35 65 35",mouthD:"M 44 58 Q 50 58 56 58",eyeSquintTop:!0,bodyLean:-1.5};case"curious":return{browL:"M 35 32 Q 41 28 47 32",browR:"M 53 33 Q 58 31 65 33",mouthD:"M 46 58 Q 50 59 54 58",eyeSquintTop:!1,bodyLean:1};case"excited":return{browL:"M 35 31 Q 41 27 47 31",browR:"M 53 31 Q 58 27 65 31",mouthD:"M 40 55 Q 50 64 60 55",eyeSquintTop:!1,bodyLean:0};case"frustrated":return{browL:"M 35 32 L 47 36",browR:"M 53 36 L 65 32",mouthD:"M 42 60 Q 50 56 58 60",eyeSquintTop:!1,bodyLean:0};case"proud":return{browL:"M 35 33 Q 41 31 47 33",browR:"M 53 33 Q 58 31 65 33",mouthD:"M 43 56 Q 50 59 57 56",eyeSquintTop:!1,bodyLean:-1};case"neutral":default:return{browL:"M 35 34 L 47 34",browR:"M 53 34 L 65 34",mouthD:null,eyeSquintTop:!1,bodyLean:0}}})(),J=s,we=i?`mascot-bubble mascot-bubble--${i}`:"mascot-bubble",We=r?`bubble-${r}-${Date.now()}`:"no-bubble";return n.jsxs("div",{ref:V,className:p,style:{width:J,height:J*1.38},children:[n.jsx("style",{children:`
832
- /* v6.0.4 — Space Agent-style multi-axis float. Bigger
833
- translations + a wider rotation range so the mascot feels
834
- like it's drifting on a tether instead of pulsing in
835
- place. Linear easing reads as physics, not animation. */
836
- @keyframes mascot-float {
837
- 0% { transform: translate3d(0, 0, 0) rotate(-6deg); }
838
- 25% { transform: translate3d(5px, -5px, 0) rotate(-2deg); }
839
- 50% { transform: translate3d(0, -8px, 0) rotate(5deg); }
840
- 75% { transform: translate3d(-5px, -4px, 0) rotate(1deg); }
841
- 100% { transform: translate3d(0, 0, 0) rotate(-6deg); }
842
- }
843
- @keyframes mascot-breathe {
844
- 0%, 100% { transform: scale(1); }
845
- 50% { transform: scale(1.012); }
846
- }
847
- @keyframes mascot-listen-ring {
848
- 0% { r: 14; opacity: 0.55; }
849
- 100% { r: 38; opacity: 0; }
850
- }
851
- @keyframes mascot-zzz {
852
- 0% { transform: translate3d(0, 0, 0) scale(0.7); opacity: 0; }
853
- 30% { opacity: 0.85; }
854
- 100% { transform: translate3d(10px, -22px, 0) scale(1.1); opacity: 0; }
855
- }
856
- @keyframes mascot-poke-bounce {
857
- 0% { transform: translate3d(0, 0, 0) scale(1); }
858
- 30% { transform: translate3d(0, -12px, 0) scale(1.06, 0.94); }
859
- 55% { transform: translate3d(0, 2px, 0) scale(0.97, 1.03); }
860
- 75% { transform: translate3d(0, -4px, 0) scale(1.02, 0.98); }
861
- 100% { transform: translate3d(0, 0, 0) scale(1); }
862
- }
863
- @keyframes mascot-soma-halo {
864
- 0%, 100% { stroke-opacity: 0.22; }
865
- 50% { stroke-opacity: 0.55; }
866
- }
867
- @keyframes mascot-thinking-particle {
868
- 0% { opacity: 0; transform: translate3d(0, 0, 0); }
869
- 40% { opacity: 1; }
870
- 100% { opacity: 0; transform: translate3d(6px, -14px, 0); }
871
- }
872
- @keyframes mascot-hand-wave {
873
- 0%, 100% { transform: translate3d(0, 0, 0); }
874
- 25% { transform: translate3d(6px, -10px, 0); }
875
- 50% { transform: translate3d(0, -4px, 0); }
876
- 75% { transform: translate3d(-4px, -8px, 0); }
877
- }
878
- /* ── Speech bubble keyframes (Space Agent port) ── */
879
- @keyframes titan-bubble-land {
880
- 0% { opacity: 0; transform: translate3d(-50%, 14px, 0) scale(0.76) rotate(-3deg); }
881
- 58% { opacity: 1; transform: translate3d(-50%, -3px, 0) scale(1.03) rotate(0.8deg); }
882
- 100% { opacity: 1; transform: translate3d(-50%, 0, 0) scale(1) rotate(0deg); }
883
- }
884
- @keyframes titan-bubble-dismiss {
885
- 0% { opacity: 1; transform: translate3d(-50%, 0, 0) scale(1); }
886
- 100% { opacity: 0; transform: translate3d(-50%, 8px, 0) scale(0.84); }
887
- }
888
- .mascot-body {
889
- animation: mascot-float 8.4s ease-in-out infinite;
890
- overflow: visible;
891
- }
892
- /* v6.0 — smooth state transitions on every animated SVG fill/stroke.
893
- Replaces the v5 snap-flip palette change with a 600ms morph,
894
- so flipping between idle/thinking/executing feels alive. */
895
- .mascot-body path,
896
- .mascot-body ellipse,
897
- .mascot-body rect,
898
- .mascot-body circle {
899
- transition: fill 600ms ease-out, stroke 600ms ease-out, opacity 400ms ease-out;
900
- }
901
- /* Excited mood gets a faster, bouncier float. */
902
- .mascot-body.mood-excited {
903
- animation-duration: 5.5s;
904
- }
905
- /* Tired mood slows the float way down. */
906
- .mascot-body.mood-tired {
907
- animation-duration: 14s;
908
- }
909
- /* Frustrated mood adds a subtle twitch. */
910
- @keyframes mascot-twitch {
911
- 0%, 96%, 100% { transform: translate3d(0, 0, 0); }
912
- 97% { transform: translate3d(-1.5px, 0, 0); }
913
- 98% { transform: translate3d(1.5px, 0, 0); }
914
- 99% { transform: translate3d(-0.5px, 0, 0); }
915
- }
916
- .mascot-body.mood-frustrated {
917
- animation: mascot-float 8.4s ease-in-out infinite, mascot-twitch 3.2s linear infinite;
918
- }
919
- /* Eyebrow + mouth strokes get the same smooth transition so
920
- mood switches morph the face instead of snapping. */
921
- .mascot-eyebrow, .mascot-mouth {
922
- transition: d 500ms cubic-bezier(0.34, 1.2, 0.64, 1),
923
- stroke 500ms ease-out,
924
- opacity 400ms ease-out;
925
- }
926
- .mascot-body.sleeping { animation: mascot-float 12s ease-in-out infinite; }
927
- .mascot-body.poking { animation: mascot-poke-bounce 520ms cubic-bezier(0.28, 0.84, 0.42, 1) both; }
928
- .mascot-torso { animation: mascot-breathe 4s ease-in-out infinite; }
929
- .mascot-listen-ring { animation: mascot-listen-ring 1.4s ease-out infinite; }
930
- .mascot-zzz { animation: mascot-zzz 2.2s ease-in-out infinite; }
931
- .mascot-hand-r.waving { animation: mascot-hand-wave 1.2s ease-in-out both; }
932
- .mascot-halo.soma { animation: mascot-soma-halo 3.2s ease-in-out infinite; }
933
- .mascot-thinking-particle { animation: mascot-thinking-particle 1.6s ease-out infinite; }
934
- /* Bubble animation classes */
935
- .mascot-bubble {
936
- will-change: opacity, transform;
937
- pointer-events: none;
938
- }
939
- .mascot-bubble--entering {
940
- animation: titan-bubble-land 400ms cubic-bezier(0.2, 1.24, 0.32, 1) both;
941
- }
942
- .mascot-bubble--visible {
943
- opacity: 1;
944
- transform: translate3d(-50%, 0, 0) scale(1);
945
- }
946
- .mascot-bubble--leaving {
947
- animation: titan-bubble-dismiss 180ms ease both;
948
- }
949
- /* Respect reduced-motion */
950
- @media (prefers-reduced-motion: reduce) {
951
- .mascot-body, .mascot-torso, .mascot-listen-ring,
952
- .mascot-zzz, .mascot-hand-r.waving, .mascot-halo.soma,
953
- .mascot-thinking-particle, .mascot-bubble {
954
- animation: none !important;
955
- }
956
- }
957
- `}),r&&n.jsxs("div",{className:`${we} absolute left-1/2 px-2.5 py-1.5 rounded-xl bg-[#fdf6e3] border border-[#d4c5a8] text-[11px] text-[#2a2210] whitespace-nowrap shadow-lg`,style:{top:-8,maxWidth:s*2.2,lineHeight:1.35},children:[r,n.jsx("span",{className:"absolute left-1/2 -translate-x-1/2 -bottom-1.5 w-2.5 h-2.5 rotate-45 bg-[#fdf6e3] border-r border-b border-[#d4c5a8]"})]},We),n.jsx("div",{className:"mascot-root absolute inset-x-0 bottom-0",style:{"--glow":v.glow,cursor:m?"pointer":"default",pointerEvents:m?"auto":"none"},onClick:ee,children:n.jsx("div",{style:{width:J,height:J*1.38,transform:`rotate(${u}deg) scaleX(${f?-1:1})`,transformOrigin:"center",transition:"transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)"},children:n.jsxs("svg",{viewBox:"0 0 100 138",width:J,height:J*1.38,className:["mascot-body",t,`mood-${A}`,C?"sleeping":"",z?"poking":""].join(" ").trim(),style:{display:"block",overflow:"visible",transform:`rotate(${Z.bodyLean}deg)`,transformOrigin:"50% 110%",transition:"transform 600ms cubic-bezier(0.34, 1.2, 0.64, 1)"},children:[n.jsxs("defs",{children:[n.jsxs("radialGradient",{id:`mascot-glow-${t}`,cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:v.glow,stopOpacity:t==="executing"?.45:.22}),n.jsx("stop",{offset:"100%",stopColor:v.glow,stopOpacity:0})]}),n.jsxs("linearGradient",{id:`mascot-body-${t}`,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[n.jsx("stop",{offset:"0%",stopColor:v.body}),n.jsx("stop",{offset:"50%",stopColor:"#0a0614"}),n.jsx("stop",{offset:"100%",stopColor:"#050208"})]}),n.jsx("filter",{id:`mascot-shadow-${t}`,children:n.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"3",floodColor:v.ring,floodOpacity:x?"0":"0.35"})})]}),C&&n.jsxs("g",{fontFamily:"ui-sans-serif, system-ui",fontWeight:"700",fill:v.glow,opacity:"0.85",children:[n.jsx("text",{className:"mascot-zzz",x:"66",y:"22",fontSize:"9",style:{animationDelay:"0s"},children:"z"}),n.jsx("text",{className:"mascot-zzz",x:"70",y:"14",fontSize:"11",style:{animationDelay:"0.7s"},children:"Z"}),n.jsx("text",{className:"mascot-zzz",x:"74",y:"6",fontSize:"13",style:{animationDelay:"1.4s"},children:"Z"})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#mascot-glow-${t})`,opacity:"0.9"}),t==="listening"&&n.jsxs(n.Fragment,{children:[n.jsx("circle",{cx:"50",cy:"40",r:"14",className:"mascot-listen-ring",stroke:v.glow,strokeWidth:"1.5"}),n.jsx("circle",{cx:"50",cy:"40",r:"14",className:"mascot-listen-ring",stroke:v.glow,strokeWidth:"1.5",style:{animationDelay:"0.5s"}})]}),n.jsx("ellipse",{cx:"50",cy:"42",rx:"34",ry:"14",fill:"none",stroke:v.ring,strokeWidth:"1.5",strokeOpacity:"0.32",className:`mascot-halo ${t} ${c?"soma":""}`}),n.jsx("line",{x1:"50",y1:"18",x2:"50",y2:"8",stroke:"#e2e8f5",strokeWidth:"1.3",strokeLinecap:"round",opacity:"0.85"}),n.jsx("circle",{cx:"50",cy:"6.5",r:"2.6",fill:v.glow,opacity:"0.95",children:!q&&n.jsx("animate",{attributeName:"r",values:"2.3;3.1;2.3",dur:t==="executing"?"0.7s":c?"3.2s":"2.6s",repeatCount:"indefinite"})}),n.jsx("circle",{cx:"50",cy:"6.5",r:"4.5",fill:v.glow,opacity:"0.18",children:!q&&n.jsx("animate",{attributeName:"opacity",values:"0.08;0.28;0.08",dur:"2.6s",repeatCount:"indefinite"})}),n.jsx("rect",{x:"34",y:"42",width:"32",height:"22",rx:"10",fill:"#c8cfdc",opacity:"0.7"}),n.jsxs("g",{filter:`url(#mascot-shadow-${t})`,children:[n.jsx("circle",{cx:"50",cy:"38",r:"22.5",fill:"#f4f6fb",stroke:"#dde2ee",strokeWidth:"0.8"}),n.jsx("circle",{cx:"50",cy:"38",r:"18.5",fill:"#16182a"})]}),n.jsx("ellipse",{cx:"50",cy:"39",rx:"17",ry:"13.5",fill:v.body,stroke:v.ring,strokeWidth:"0.7",strokeOpacity:"0.7"}),n.jsx("path",{d:"M37 31 Q41 27 49 27",stroke:"#ffffff",strokeWidth:"2",strokeLinecap:"round",fill:"none",opacity:"0.7"}),n.jsx("path",{d:"M55 28 Q58 28 60 29.5",stroke:"#ffffff",strokeWidth:"1.2",strokeLinecap:"round",fill:"none",opacity:"0.45"}),n.jsxs("g",{transform:`translate(${f?-I.x:I.x}, ${I.y})`,children:[n.jsxs("ellipse",{cx:"50",cy:"40",rx:ne,ry:X,fill:v.eye,style:{transition:"rx 140ms ease-out, ry 140ms ease-out"},children:[t==="thinking"&&!C&&!q&&n.jsx("animate",{attributeName:"cx",values:"46;54;46",dur:"1.6s",repeatCount:"indefinite"}),t==="executing"&&!q&&n.jsx("animate",{attributeName:"rx",values:"4.5;6.5;4.5",dur:"0.8s",repeatCount:"indefinite"})]}),Z.eyeSquintTop&&!k&&!T&&n.jsx("rect",{x:"43",y:"36",width:"14",height:"2.2",rx:"1",fill:v.body,opacity:"0.9"}),!C&&n.jsx("circle",{cx:48+(f?-I.x:I.x)*.4,cy:"38.5",r:"1.3",fill:"#ffffff",opacity:"0.9"})]}),!T&&!C&&t!=="error"&&n.jsxs("g",{stroke:v.eye,strokeWidth:"1.4",strokeLinecap:"round",fill:"none",opacity:"0.9",children:[n.jsx("path",{d:Z.browL,className:"mascot-eyebrow",transform:"translate(0, -3)"}),n.jsx("path",{d:Z.browR,className:"mascot-eyebrow",transform:"translate(0, -3)"})]}),Z.mouthD&&!C&&t!=="error"&&n.jsx("path",{d:Z.mouthD,stroke:v.eye,strokeWidth:"1.4",strokeLinecap:"round",fill:"none",opacity:"0.9",className:"mascot-mouth",transform:"translate(0, -4)"}),n.jsx("rect",{x:"42",y:"60",width:"16",height:"4",rx:"1.5",fill:"#dde2ee"}),n.jsx("ellipse",{cx:"50",cy:"64",rx:"22",ry:"4",fill:"#f4f6fb",stroke:"#dde2ee",strokeWidth:"0.6"}),n.jsxs("g",{className:"mascot-torso",children:[n.jsx("path",{d:`M28 66
958
- Q28 64 32 64
959
- L68 64
960
- Q72 64 72 66
961
- L74 108
962
- Q74 116 66 116
963
- L34 116
964
- Q26 116 26 108 Z`,fill:"#f4f6fb",stroke:"#dde2ee",strokeWidth:"0.8",filter:`url(#mascot-shadow-${t})`}),n.jsx("path",{d:"M44 68 L56 68 L57 110 L43 110 Z",fill:"#ffffff",opacity:"0.55"}),n.jsx("rect",{x:"38",y:"78",width:"24",height:"16",rx:"3.5",fill:"#16182a",stroke:"#0d0f1d",strokeWidth:"0.6"}),n.jsx("circle",{cx:"44",cy:"86",r:"1.7",fill:"#f59e0b",opacity:"0.85"}),n.jsx("circle",{cx:"50",cy:"86",r:"1.9",fill:v.glow,children:!q&&n.jsx("animate",{attributeName:"opacity",values:"0.5;1;0.5",dur:t==="executing"?"0.6s":c?"3.2s":"2.4s",repeatCount:"indefinite"})}),n.jsx("circle",{cx:"56",cy:"86",r:"1.7",fill:"#34d399",opacity:"0.85"}),n.jsx("rect",{x:"41",y:"90",width:"18",height:"1.6",rx:"0.6",fill:v.glow,opacity:"0.7",children:t==="executing"&&!q&&n.jsx("animate",{attributeName:"opacity",values:"0.4;0.95;0.4",dur:"0.6s",repeatCount:"indefinite"})})]}),n.jsx("g",{transform:"translate(20, 96)",children:n.jsxs("g",{className:"mascot-hand-l",children:[n.jsx("circle",{r:"5.5",fill:"#f4f6fb",stroke:"#dde2ee",strokeWidth:"0.8"}),n.jsx("circle",{r:"2",fill:v.glow,opacity:"0.85"})]})}),n.jsx("g",{transform:"translate(80, 96)",children:n.jsxs("g",{className:`${S?"mascot-hand-r waving":"mascot-hand-r"}`,children:[n.jsx("circle",{r:"5.5",fill:"#f4f6fb",stroke:"#dde2ee",strokeWidth:"0.8"}),n.jsx("circle",{r:"2",fill:v.glow,opacity:"0.85"})]})}),n.jsx("ellipse",{cx:"42",cy:"118",rx:"6",ry:"3",fill:"#f4f6fb",stroke:"#dde2ee",strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"58",cy:"118",rx:"6",ry:"3",fill:"#f4f6fb",stroke:"#dde2ee",strokeWidth:"0.6"}),t==="thinking"&&n.jsxs("g",{children:[n.jsx("circle",{cx:"60",cy:"14",r:"1.5",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0s"}}),n.jsx("circle",{cx:"66",cy:"10",r:"1.1",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0.4s"}}),n.jsx("circle",{cx:"72",cy:"7",r:"0.8",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0.8s"}})]}),t==="error"&&n.jsxs("g",{stroke:"#ef4444",strokeWidth:"1.8",strokeLinecap:"round",opacity:"0.9",children:[n.jsx("line",{x1:"43",y1:"40",x2:"57",y2:"48"}),n.jsx("line",{x1:"57",y1:"40",x2:"43",y2:"48"})]})]})})})]})}const ol="titan2:chat-dock:pos",al="titan2:chat-dock:size",yr="titan2:chat-dock:hidden-edge",ll="titan2:chat-dock:hint-shown",$f=4,ct=116,Qt=ct*1.38,Ds=14,zf=320,Hf=360,Vf=960,Gf=900,qf=420,Yf=560,Jn=8,Kf=20,Jf=64,Xf="transform 280ms cubic-bezier(0.22, 1, 0.36, 1)",Qf="transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)",Zf=400,ep=180,tp=1800,sp=1e4,np=28,rp=260,ip=2e3,op=3500;function ap(){try{const t=localStorage.getItem(al);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 br(e)}}catch{}return{w:qf,h:Yf}}function lp(t){try{localStorage.setItem(al,JSON.stringify(t))}catch{}}function br(t){return{w:Math.max(zf,Math.min(t.w,Vf)),h:Math.max(Hf,Math.min(t.h,Gf))}}function cp(){try{const s=localStorage.getItem(ol);if(s){const r=JSON.parse(s);if(typeof(r==null?void 0:r.x)=="number"&&typeof(r==null?void 0:r.y)=="number")return r}}catch{}const t=typeof window<"u"?window.innerWidth:1280,e=typeof window<"u"?window.innerHeight:800;return{x:t-ct-32,y:e-Qt-32}}function dp(t){try{localStorage.setItem(ol,JSON.stringify(t))}catch{}}function up(){try{const t=localStorage.getItem(yr);if(t==="left"||t==="right"||t==="top"||t==="bottom")return t}catch{}return null}function hp(t){try{t?localStorage.setItem(yr,t):localStorage.removeItem(yr)}catch{}}let cl=!1;function Wi(){try{return localStorage.getItem(ll)==="1"}catch{return cl}}function Ui(){try{localStorage.setItem(ll,"1")}catch{cl=!0}}function Xn(t){const e=window.innerWidth,s=window.innerHeight;return{x:Math.max(0,Math.min(t.x,e-ct)),y:Math.max(0,Math.min(t.y,s-Qt))}}function Bi(t){const e=window.innerWidth,s=window.innerHeight;return t.x<=Jn?"left":t.x>=e-ct-Jn?"right":t.y>=s-Qt-Jn?"bottom":null}function fp(t,e){if(!t)return"";const s=ct-Kf,r=e?Jf: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 pp(t){switch(t){case"left":return 90;case"right":return-90;case"top":return 180;case"bottom":return 0;default:return 0}}function gp(t){return t.x>window.innerWidth/2}function mp(t){const e=t.trim().split(/\s+/).filter(Boolean).length,s=tp+t.length*np+e*rp;return Math.min(s,sp)}function yp(t,e){const s=window.innerWidth,r=window.innerHeight,i=s-(t.x+ct),o=r-(t.y+Qt),c=i>=e.w+Ds?"right":"left",l=o>=e.h+Ds?"below":"above",d=c==="right"?t.x+ct+Ds:t.x-e.w-Ds,p=l==="below"?t.y:t.y+Qt-e.h;return{left:Math.max(8,Math.min(d,s-e.w-8)),top:Math.max(8,Math.min(p,r-e.h-8)),side:c,vertical:l}}function bp({space:t,somaActive:e,defaultExpanded:s=!1}){const[r,i]=w.useState(!1),o=e??r;w.useEffect(()=>{let K=!1;me("/api/config").then(Q=>Q.ok?Q.json():null).then(Q=>{var oe;K||i(!!((oe=Q==null?void 0:Q.organism)!=null&&oe.enabled))}).catch(()=>{});const Y=Q=>{const oe=Q.detail;typeof(oe==null?void 0:oe.enabled)=="boolean"&&i(oe.enabled)};return window.addEventListener("titan:soma:changed",Y),()=>{K=!0,window.removeEventListener("titan:soma:changed",Y)}},[]),w.useEffect(()=>{const K=Y=>{const Q=Y.detail;typeof(Q==null?void 0:Q.open)=="boolean"?u(Q.open):u(oe=>!oe)};return window.addEventListener("titan:chat:toggle",K),()=>window.removeEventListener("titan:chat:toggle",K)},[]);const[c,l]=w.useState(()=>Xn(cp())),[d,p]=w.useState(()=>ap()),[m,u]=w.useState(s),[f,x]=w.useState(!1),[b,j]=w.useState(!1),[A,v]=w.useState("idle"),[I,g]=w.useState(()=>up()),[k,_]=w.useState(!1),[T,E]=w.useState(!1),[C,M]=w.useState(null),S=w.useRef({}),R=w.useRef(null),O=w.useRef(null),B=w.useRef(!1);w.useEffect(()=>{dp(c)},[c]),w.useEffect(()=>{lp(d)},[d]),w.useEffect(()=>{hp(I)},[I]),w.useEffect(()=>{const K=window.matchMedia("(prefers-reduced-motion: reduce)");E(K.matches);const Y=Q=>E(Q.matches);return K.addEventListener("change",Y),()=>K.removeEventListener("change",Y)},[]),w.useEffect(()=>{let K,Y;const Q=()=>{clearTimeout(Y),Y=window.setTimeout(()=>{l(U=>{const H=Xn(U),te=Bi(H);return g(te),H}),p(U=>br(U))},50)},oe=()=>{clearTimeout(K),K=window.setTimeout(Q,100)};window.addEventListener("resize",oe),document.addEventListener("visibilitychange",Q),window.addEventListener("focus",Q),window.addEventListener("pageshow",Q);const D=window.setInterval(Q,2e3);return()=>{window.removeEventListener("resize",oe),document.removeEventListener("visibilitychange",Q),window.removeEventListener("focus",Q),window.removeEventListener("pageshow",Q),clearTimeout(K),clearTimeout(Y),clearInterval(D)}},[]),w.useEffect(()=>()=>{clearTimeout(S.current.enter),clearTimeout(S.current.exit),clearTimeout(S.current.hide)},[]),w.useEffect(()=>{if(Wi())return;let K,Y;return K=window.setTimeout(()=>{G("Drag me, tap me."),Ui(),Y=window.setTimeout(()=>{q()},op),S.current.hide=Y},ip),()=>{clearTimeout(K),clearTimeout(Y)}},[]);const z=w.useCallback(()=>{clearTimeout(S.current.enter),clearTimeout(S.current.exit),clearTimeout(S.current.hide),S.current={}},[]),G=w.useCallback(K=>{z(),M({text:K,phase:"entering"}),S.current.enter=window.setTimeout(()=>{M(Q=>Q&&Q.text===K?{...Q,phase:"visible"}:Q);const Y=mp(K);S.current.hide=window.setTimeout(()=>{q()},Y)},Zf)},[z]),q=w.useCallback(()=>{z(),M(K=>K?(S.current.exit=window.setTimeout(()=>{M(null)},ep),{...K,phase:"leaving"}):null)},[z]),W=A==="thinking"?"thinking…":A==="executing"?"working on it":null;w.useEffect(()=>{W?G(W):M(K=>K?((K.text==="thinking…"||K.text==="working on it")&&q(),K):null)},[W]);const V=w.useCallback(K=>{var Y,Q;K.button===0&&((Q=(Y=K.target).setPointerCapture)==null||Q.call(Y,K.pointerId),R.current={pointer:{x:K.clientX,y:K.clientY},pos:c,moved:!1},x(!0),Wi()||Ui())},[c]),$=w.useCallback(K=>{const Y=R.current;if(!Y)return;const Q=K.clientX-Y.pointer.x,oe=K.clientY-Y.pointer.y;!Y.moved&&Math.hypot(Q,oe)<$f||(Y.moved=!0,I&&g(null),l(Xn({x:Y.pos.x+Q,y:Y.pos.y+oe})))},[I]),ee=w.useCallback(K=>{var Q,oe;const Y=R.current;if((oe=(Q=K.target).releasePointerCapture)==null||oe.call(Q,K.pointerId),R.current=null,x(!1),Y&&Y.moved){const D=Bi(c);g(D||null)}else Y&&!Y.moved&&(I&&g(null),u(D=>!D))},[c,I]),ne=w.useCallback(()=>{I&&_(!0)},[I]),X=w.useCallback(()=>{_(!1)},[]),Z=w.useCallback(K=>{if(K.ctrlKey||f)return;let Y=K.target;for(;Y&&Y!==document.body;){const Q=window.getComputedStyle(Y),oe=Y.scrollHeight>Y.clientHeight,D=Q.overflowY;if(oe&&(D==="auto"||D==="scroll")){Y.scrollTop+=K.deltaY,K.preventDefault();return}Y=Y.parentElement}window.scrollBy({top:K.deltaY,left:K.deltaX,behavior:"auto"}),K.preventDefault()},[f]),J=yp(c,d),we=(C==null?void 0:C.text)??null,We=(C==null?void 0:C.phase)??null,le=w.useCallback(K=>{var Y,Q;K.button===0&&(K.stopPropagation(),(Q=(Y=K.target).setPointerCapture)==null||Q.call(Y,K.pointerId),O.current={pointer:{x:K.clientX,y:K.clientY},size:d,anchorSide:J.side,anchorVertical:J.vertical},j(!0))},[d,J.side,J.vertical]),ge=w.useCallback(K=>{const Y=O.current;if(!Y)return;const Q=K.clientX-Y.pointer.x,oe=K.clientY-Y.pointer.y,D=Y.anchorSide==="right"?Q:-Q,U=Y.anchorVertical==="below"?oe:-oe;p(br({w:Y.size.w+D,h:Y.size.h+U}))},[]),ye=w.useCallback(K=>{var Y,Q;(Q=(Y=K.target).releasePointerCapture)==null||Q.call(Y,K.pointerId),O.current=null,j(!1)},[]),xe=fp(I,k);return n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",left:c.x,top:c.y,width:ct,height:Qt,zIndex:2147482e3,cursor:f?"grabbing":I?"pointer":"grab",touchAction:"none",userSelect:"none",animation:T?void 0:"titan-dock-in 220ms ease-out both",transform:xe,transition:f?"none":`${Xf}, ${Qf}`},onPointerDown:V,onPointerMove:$,onPointerUp:ee,onPointerCancel:ee,onPointerEnter:ne,onPointerLeave:X,onWheel:Z,title:m?"Click to minimize TITAN chat — drag to move":"Click to open TITAN chat — drag to move",children:n.jsx(Ff,{state:A,size:ct,quip:we,bubblePhase:We,somaActive:o,followCursor:!f,edgeRotate:pp(I),faceFlip:gp(c),edgeHidden:!!I})}),m&&n.jsxs("div",{style:{position:"fixed",left:J.left,top:J.top,width:d.w,height:d.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:b||B.current||T?void 0:"titan-dock-panel-in 180ms cubic-bezier(0.2, 0.9, 0.25, 1) both",transformOrigin:`${J.side==="right"?"left":"right"} ${J.vertical==="below"?"top":"bottom"}`},children:[n.jsx(il,{space:t,onClose:()=>u(!1),onMascotState:v}),n.jsx("div",{onPointerDown:le,onPointerMove:ge,onPointerUp:ye,onPointerCancel:ye,title:"Drag to resize",style:{position:"absolute",[J.vertical==="below"?"bottom":"top"]:0,[J.side==="right"?"right":"left"]:0,width:18,height:18,cursor:J.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:b?1:.55},children:J.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:`
965
- @keyframes titan-dock-in {
966
- from { opacity: 0; transform: translate3d(0, 4px, 0); }
967
- to { opacity: 1; transform: translate3d(0, 0, 0); }
968
- }
969
- @keyframes titan-dock-panel-in {
970
- from { opacity: 0; transform: translate3d(0, 12px, 0) scale(0.968); }
971
- to { opacity: 1; transform: translate3d(0, 0, 0) scale(1); }
972
- }
973
- @media (prefers-reduced-motion: reduce) {
974
- .titan-dock-root, .titan-dock-panel {
975
- animation: none !important;
976
- transition: none !important;
977
- }
978
- }
979
- `})]})}const xp=3e4,wp=3e4;function vp(){const[t,e]=w.useState(null),s=w.useRef(null),r=w.useRef(new Set),i=w.useRef(null);if(w.useEffect(()=>{let c=!1;const l=async()=>{var p;try{const m=await me("/api/soma/advisories?limit=5");if(!m.ok)return;const u=await m.json();if(c||!((p=u.advisories)!=null&&p.length))return;for(const f of u.advisories)if(!r.current.has(f.at)&&!(s.current&&f.at<=s.current)){if(s.current===null){s.current=u.advisories[0].at;return}s.current=f.at,e(f),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>e(null),wp);return}}catch{}};l();const d=setInterval(l,xp);return()=>{c=!0,clearInterval(d),i.current&&clearTimeout(i.current)}},[]),!t)return null;const o=()=>{r.current.add(t.at),e(null),i.current&&clearTimeout(i.current)};return n.jsxs("div",{style:{position:"fixed",bottom:100,right:24,maxWidth:340,padding:"12px 14px",borderRadius:12,background:"linear-gradient(135deg, rgba(99,102,241,0.18), rgba(139,92,246,0.14))",border:"1px solid rgba(165,180,252,0.35)",color:"#e0e7ff",fontSize:12,boxShadow:"0 12px 32px rgba(0,0,0,0.45), 0 0 0 1px rgba(99,102,241,0.15)",zIndex:60,animation:"soma-advisory-in 220ms cubic-bezier(0.22, 1, 0.36, 1)",backdropFilter:"blur(8px)"},children:[n.jsx("style",{children:`
980
- @keyframes soma-advisory-in {
981
- from { opacity: 0; transform: translateY(8px); }
982
- to { opacity: 1; transform: translateY(0); }
983
- }
984
- `}),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:"#a5b4fc",marginBottom:4},children:"TITAN noticed"}),n.jsx("div",{style:{lineHeight:1.45,color:"#fafafa"},children:t.rationale}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)",marginTop:6,textTransform:"uppercase",letterSpacing:.5},children:["suggestion: ",t.action]})]}),n.jsx("button",{onClick:o,"aria-label":"Dismiss",style:{border:"none",background:"transparent",color:"rgba(255,255,255,0.5)",fontSize:18,lineHeight:1,cursor:"pointer",padding:0,marginTop:-2},children:"×"})]})]})}function _p(){const t=typeof localStorage<"u"?localStorage.getItem("titan-token"):null;return t?{Authorization:`Bearer ${t}`}:{}}async function is(t,e){const s=await fetch(t,{...e,headers:{"Content-Type":"application/json",..._p(),...(e==null?void 0:e.headers)||{}}});if(!s.ok)throw new Error(`${s.status} ${s.statusText}`);return s.json()}function kp(){const t=Gi(),e=yl(),{logout:s}=bl(),[r,i]=w.useState([]),[o,c]=w.useState(null),[l,d]=w.useState([]),[p,m]=w.useState(!1),[u,f]=w.useState(!1),[x,b]=w.useState(null),[j,A]=w.useState(()=>{try{return localStorage.getItem("titan-sidebar-collapsed")==="1"}catch{return!1}}),v=w.useCallback(()=>{A(E=>{const C=!E;try{localStorage.setItem("titan-sidebar-collapsed",C?"1":"0")}catch{}return C})},[]),I=w.useCallback(async()=>{try{const E=await is("/api/spaces");i(E.spaces),c(E.activeSpaceId),b(null)}catch(E){b(E.message)}},[]);w.useEffect(()=>{I(),is("/api/spaces/presets").then(C=>d(C.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 is(`/api/spaces/${E}/activate`,{method:"POST"}),c(E),t(`/space/${E}`)}catch(C){b(C.message)}},[t]),k=w.useCallback(async E=>{f(!0);try{const C=E.preset?l.find(S=>S.id===E.preset):void 0,M=await is("/api/spaces",{method:"POST",body:JSON.stringify({name:E.name||(C==null?void 0:C.name)||"New Space",icon:C==null?void 0:C.icon,color:C==null?void 0:C.color,makeActive:!0})});await I(),t(`/space/${M.space.id}`),m(!1)}catch(C){b(C.message)}finally{f(!1)}},[t,l,I]),_=w.useCallback(async E=>{if(window.confirm("Archive this Space? Widgets will be preserved and you can restore it later."))try{await is(`/api/spaces/${E}`,{method:"DELETE"}),await I()}catch(C){b(C.message)}},[I]);if(!e.pathname.startsWith("/space")&&!e.pathname.startsWith("/mission")&&e.pathname!=="/")return null;const T=e.pathname.startsWith("/mission");return j?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:v,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-56 bg-[#0a0e1a] border-r border-[#1f2937] flex flex-col relative flex-shrink-0",children:[n.jsxs("div",{className:"px-3 py-2 border-b border-[#1f2937] flex items-center justify-between",children:[n.jsx("span",{className:"text-[11px] uppercase tracking-wider text-[#a1a1aa] font-medium",children:"Spaces"}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-[#a1a1aa] hover:text-white text-lg leading-none w-5 h-5 flex items-center justify-center rounded hover:bg-[#1f2937]",title:"Create a new Space","aria-label":"Create a new Space",children:"+"}),n.jsx("button",{type:"button",onClick:v,className:"text-[#a1a1aa] hover:text-white text-sm leading-none w-5 h-5 flex items-center justify-center rounded hover:bg-[#1f2937]",title:"Hide sidebar","aria-label":"Hide sidebar",children:"‹"})]})]}),n.jsxs("nav",{className:"flex-1 overflow-y-auto py-2",children:[n.jsxs("div",{className:"px-1.5 mb-2",children:[n.jsxs("button",{type:"button",onClick:()=>t("/mission"),className:`w-full text-left px-2 py-1.5 rounded text-sm flex items-center gap-2 ${T&&e.pathname==="/mission"?"bg-[#1f2937] text-white":"text-[#d4d4d8] hover:bg-[#1a1f2e] hover:text-white"}`,title:"Start a new mission or open a template",children:[n.jsx("span",{className:"text-base leading-none",children:"🪵"}),n.jsx("span",{className:"flex-1 truncate",children:"Missions"}),n.jsx("span",{className:"text-[10px] text-[#71717a]",children:"desk"})]}),n.jsxs("button",{type:"button",onClick:()=>t("/mission/library"),className:`w-full text-left px-2 py-1 rounded text-[12px] flex items-center gap-2 ml-3 ${e.pathname==="/mission/library"?"bg-[#1f2937] text-white":"text-[#a1a1aa] hover:bg-[#1a1f2e] hover:text-white"}`,title:"Past missions",children:[n.jsx("span",{children:"📚"}),n.jsx("span",{className:"flex-1 truncate",children:"Library"})]})]}),n.jsx("div",{className:"px-3 pt-1 pb-1 text-[10px] uppercase tracking-wider text-[#71717a]",children:"Spaces"}),x&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#ef4444] bg-[#1f0a0a]",children:x}),r.length===0&&!x&&n.jsx("div",{className:"px-3 py-4 text-[11px] text-[#71717a]",children:'No Spaces yet. Use + to create one, or ask TITAN "make me a workspace for…".'}),r.map(E=>{const C=E.id===o;return n.jsx("div",{className:"group flex items-center px-1.5",children:n.jsxs("button",{type:"button",onClick:()=>g(E.id),onContextMenu:M=>{M.preventDefault(),_(E.id)},className:`flex-1 text-left px-2 py-1.5 rounded text-sm flex items-center gap-2 ${C?"bg-[#1f2937] text-white":"text-[#d4d4d8] hover:bg-[#1a1f2e] hover:text-white"}`,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] text-[#71717a]",children:E.widgets.length})]})},E.id)})]}),n.jsxs("div",{className:"px-3 py-2 border-t border-[#1f2937] flex items-center justify-between gap-2",children:[n.jsx("a",{href:"/command-post",className:"text-[11px] text-[#71717a] hover:text-[#d4d4d8] flex items-center gap-1",children:"⚙ Admin"}),n.jsx("button",{type:"button",onClick:()=>{s(),window.location.assign("/")},className:"text-[11px] text-[#71717a] hover:text-[#ef4444] inline-flex items-center gap-1",title:"Sign out — mints a fresh token next login",children:"⇥ Log out"})]}),p&&n.jsx(Sp,{presets:l,creating:u,onCreate:k,onClose:()=>m(!1)})]})}function Sp(t){const{presets:e,creating:s,onCreate:r,onClose:i}=t,[o,c]=w.useState(""),[l,d]=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:p=>p.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(p=>n.jsxs("button",{type:"button",onClick:()=>{d(p.id),o||c(p.name)},className:`text-left px-3 py-2 rounded border ${l===p.id?"border-[#3b82f6] bg-[#0f172a]":"border-[#1f2937] hover:border-[#374151]"}`,title:p.tagline,children:[n.jsxs("div",{className:"text-sm flex items-center gap-2 text-white",children:[n.jsx("span",{children:p.icon}),n.jsx("span",{children:p.name})]}),n.jsx("div",{className:"text-[10px] text-[#71717a] mt-0.5 line-clamp-1",children:p.tagline})]},p.id))}),n.jsx("label",{className:"block text-[11px] text-[#a1a1aa] mb-1",children:"Name"}),n.jsx("input",{type:"text",value:o,onChange:p=>c(p.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:o.trim(),preset:l}),disabled:s||!o.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"})]})]})})}const Qn=4e3,jp=[{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 Ep({space:t,open:e,onClose:s,onSaved:r}){const[i,o]=w.useState(t.agentInstructions??""),[c,l]=w.useState(!1),[d,p]=w.useState(null),m=w.useRef(null);w.useEffect(()=>{if(e){o(t.agentInstructions??""),p(null);const f=setTimeout(()=>{var x;return(x=m.current)==null?void 0:x.focus()},50);return()=>clearTimeout(f)}},[e,t.id,t.agentInstructions]),w.useEffect(()=>{if(!e)return;const f=x=>{x.key==="Escape"&&s(),x.key==="Enter"&&(x.metaKey||x.ctrlKey)&&u()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e]);const u=w.useCallback(async()=>{if(i.length>Qn){p(`Instructions must be ${Qn} characters or fewer.`);return}l(!0),p(null);try{const f=i.trim(),x={...t,agentInstructions:f||void 0,updatedAt:new Date().toISOString()};_e.save(x),r==null||r(f),s()}catch(f){p(f.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:f=>f.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(us,{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(_s,{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:m,value:i,onChange:f=>o(f.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()," / ",Qn.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:jp.map(f=>n.jsxs("button",{onClick:()=>o(f.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:f.label}),n.jsx("div",{className:"text-[10px] text-[#a1a1aa] line-clamp-2 leading-relaxed",children:f.body})]},f.label))})]}),d&&n.jsx("div",{className:"text-[11px] text-[#ef4444] bg-[#ef4444]/10 border border-[#ef4444]/30 rounded p-2",children:d})]}),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:c,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(fn,{className:"w-3.5 h-3.5"}),c?"Saving…":"Save"]})]})]})}):null}const Np=12,Cp=["react","vanilla","html"];function Tp({widget:t,spaceId:e,open:s,onClose:r,onSaved:i}){const[o,c]=w.useState(t.source),[l,d]=w.useState(t.format),[p,m]=w.useState(t.name),[u,f]=w.useState(!1),[x,b]=w.useState(null),[j,A]=w.useState(!1),v=w.useRef(null);w.useEffect(()=>{if(s){c(t.source),d(t.format),m(t.name),b(null),A(!1);const T=setTimeout(()=>{var E;return(E=v.current)==null?void 0:E.focus()},50);return()=>clearTimeout(T)}},[s,t.id,t.source,t.format,t.name]),w.useEffect(()=>{if(!s)return;const T=E=>{E.key==="Escape"&&r(),E.key==="Enter"&&(E.metaKey||E.ctrlKey)&&I()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[s]);const I=w.useCallback(async()=>{f(!0),b(null);try{const T=o!==t.source||l!==t.format,E=Array.isArray(t.versions)?t.versions:[],C=T?[...E,{source:t.source,format:t.format,savedAt:t.updatedAt}].slice(-Np):E,M={name:p.trim()||t.name,source:o,format:l,versions:C};_e.updateWidget(e,t.id,M),i==null||i({...t,...M,updatedAt:Date.now()}),r()}catch(T){b(T.message)}finally{f(!1)}},[o,l,p,t,e,i,r]),g=w.useCallback(T=>{c(T.source),d(T.format),A(!1)},[]);if(!s)return null;const k=Array.isArray(t.versions)?t.versions:[],_=[...k].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:T=>T.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(Cl,{className:"w-4 h-4 text-[#6366f1] shrink-0"}),n.jsx("input",{value:p,onChange:T=>m(T.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:()=>A(T=>!T),disabled:k.length===0,className:`p-1.5 rounded text-[#a1a1aa] hover:bg-[#18181b] hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${j?"bg-[#18181b] text-white":""}`,title:k.length===0?"No history yet":`${k.length} prior version${k.length===1?"":"s"}`,children:n.jsx(ql,{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(_s,{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:T=>d(T.target.value),className:"bg-[#18181b] border border-[#27272a] rounded px-2 py-0.5 text-[#e4e4e7] focus:outline-none focus:border-[#6366f1]/60",children:Cp.map(T=>n.jsx("option",{value:T,children:T},T))})]}),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-1 flex min-h-0",children:[n.jsx("textarea",{ref:v,value:o,onChange:T=>c(T.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:Rp[l]}),j&&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 (",k.length,")"]}),n.jsxs("div",{className:"flex-1 overflow-auto",children:[_.length===0&&n.jsx("div",{className:"p-3 text-[11px] text-[#52525b]",children:"No prior versions yet — save to start tracking."}),_.map((T,E)=>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(T.savedAt).toLocaleString()}),n.jsxs("button",{onClick:()=>g(T),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(Qi,{className:"w-3 h-3"}),"revert"]})]}),n.jsxs("div",{className:"text-[10px] text-[#71717a] font-mono",children:["format: ",T.format]}),n.jsxs("div",{className:"text-[10px] text-[#52525b] truncate mt-1",title:T.source.slice(0,280),children:[T.source.slice(0,80),T.source.length>80?"…":""]}),E===0&&n.jsx("div",{className:"text-[9px] text-[#6366f1] mt-1",children:"most recent before current"})]},T.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:x?n.jsxs("span",{className:"text-[#ef4444]",children:["Error: ",x]}):o!==t.source||l!==t.format||p!==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:()=>{I()},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(fn,{className:"w-3.5 h-3.5"}),u?"Saving…":"Save widget"]})]})]})]})})}const Rp={react:`// Return a React component named "Widget". titan.* APIs are
985
- // available for fetch/api/state. Example:
986
- function Widget({ titan }) {
987
- const [n, setN] = React.useState(0);
988
- return <button onClick={() => setN(n + 1)}>Clicked {n} times</button>;
989
- }`,vanilla:`// Export a function (container, titan) => cleanup | void.
990
- // Called once to mount; return a cleanup function if needed.
991
- (container, titan) => {
992
- container.innerHTML = '<button>Hello</button>';
993
- const btn = container.querySelector('button');
994
- btn.addEventListener('click', () => btn.textContent = 'Clicked!');
995
- }`,html:`<!-- Raw HTML. No scripts run. -->
996
- <div style="padding:16px;color:#e4e4e7">Hello, widget!</div>`,iframe:"",system:""};function Ap(t){return String(t||"").startsWith("system:")?"system":"react"}const Ip={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 Lp(t){return t.split(/[-_/]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Dp({open:t,onClose:e}){const[s,r]=w.useState([]),[i,o]=w.useState([]),[c,l]=w.useState("All"),[d,p]=w.useState(""),[m,u]=w.useState(null),[f,x]=w.useState(!1),[b,j]=w.useState(null);w.useEffect(()=>{t&&(x(!0),me("/api/widget-gallery").then(g=>g.json()).then(g=>{r(g.templates||[]),o(g.categories||[]),x(!1)}).catch(g=>{j(g.message),x(!1)}))},[t]),w.useEffect(()=>{if(!t)return;const g=k=>{k.key==="Escape"&&e()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[t,e]);const A=w.useMemo(()=>{const g=c==="All"?s:s.filter(_=>_.category===c),k=d.trim().toLowerCase();return k?g.filter(_=>[_.name,_.description,_.category,..._.tags||[],..._.triggers||[]].join(" ").toLowerCase().includes(k)):g},[c,d,s]);if(!t)return null;const v=async g=>{var k,_,T,E;u(g.id),j(null);try{const C=await me(`/api/widget-gallery/${encodeURIComponent(g.id)}`);if(!C.ok)throw new Error(`Could not load template (${C.status})`);const M=await C.json(),S={templateId:g.id,templateName:M.name||g.name,source:M.source,format:Ap(M.source),defaultSize:{w:((k=M.defaultSize)==null?void 0:k.w)??((_=g.defaultSize)==null?void 0:_.w)??4,h:((T=M.defaultSize)==null?void 0:T.h)??((E=g.defaultSize)==null?void 0:E.h)??4}};window.dispatchEvent(new CustomEvent("titan:gallery:run-template",{detail:S})),e()}catch(C){j(C.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-4",style:{background:"rgba(0, 0, 0, 0.66)",backdropFilter:"blur(4px)"},onClick:e,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, 90vh)"},onClick:g=>g.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",children:[n.jsx(xr,{className:"w-4 h-4 text-[#a78bfa]"}),n.jsx("h3",{className:"font-semibold text-white text-sm",children:"Widget gallery"}),n.jsx("span",{className:"text-[10px] text-[#71717a]",children:f?"Loading…":`${s.length} templates`})]}),n.jsx("button",{onClick:e,className:"p-1 rounded text-[#71717a] hover:bg-[#18181b] hover:text-white transition-colors",title:"Close (Esc)",children:n.jsx(_s,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"flex items-center gap-1.5 px-5 py-2 border-b border-[#27272a] text-[11px] overflow-x-auto",children:I.map(g=>{var k;return n.jsxs("button",{onClick:()=>l(g),className:`px-2.5 py-1 rounded-full border transition-colors whitespace-nowrap ${c===g?"border-[#6366f1] bg-[#6366f1]/15 text-white":"border-[#27272a] bg-transparent text-[#a1a1aa] hover:border-[#3f3f46] hover:text-white"}`,children:[Lp(g),g!=="All"&&n.jsx("span",{className:"ml-1.5 text-[9px] opacity-70",children:((k=i.find(_=>_.category===g))==null?void 0:k.count)??0})]},g)})}),n.jsx("div",{className:"px-5 py-2 border-b border-[#27272a]",children:n.jsxs("label",{className:"flex items-center gap-2 rounded-lg border border-[#27272a] bg-[#18181b]/60 px-3 py-2",children:[n.jsx(Zi,{className:"w-3.5 h-3.5 text-[#71717a]"}),n.jsx("input",{value:d,onChange:g=>p(g.target.value),placeholder:"Search templates...",className:"flex-1 bg-transparent text-xs text-white placeholder:text-[#71717a] outline-none"})]})}),n.jsxs("div",{className:"flex-1 overflow-auto p-4",children:[f&&n.jsx("div",{className:"flex items-center justify-center h-full text-[#a1a1aa] text-sm",children:"Loading templates…"}),b&&n.jsxs("div",{className:"flex items-center justify-center h-full text-[#f87171] text-sm",children:["Error: ",b]}),!f&&!b&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:A.map(g=>n.jsxs("button",{onClick:()=>v(g),disabled:m!==null,className:"text-left p-3 rounded-lg border border-[#27272a] bg-[#18181b]/60 hover:border-[#6366f1]/50 hover:bg-[#18181b] transition-colors 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:Ip[g.category]??"#9ca3af"}}),n.jsx("span",{className:"text-[12px] font-medium text-white truncate",children:g.name})]}),n.jsx(eo,{className:"w-3 h-3 text-[#52525b] group-hover:text-[#a5b4fc] transition-colors shrink-0"})]}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] leading-relaxed line-clamp-2",children:m===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(k=>n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-[#27272a] text-[#71717a]",children:k},k))})]},g.id))}),A.length===0&&n.jsx("div",{className:"flex items-center justify-center h-40 text-[#a1a1aa] text-sm",children:"No templates in this category."})]}),n.jsxs("div",{className:"mt-4 p-3 rounded-lg border border-dashed border-[#27272a] bg-[#0a0a0e] flex items-start gap-2",children:[n.jsx(ao,{className:"w-3.5 h-3.5 text-[#71717a] mt-0.5 shrink-0"}),n.jsxs("div",{className:"text-[11px] text-[#a1a1aa] 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 text-[#d4d4d8]",children:"titan.fetch"}),","," ",n.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.api.call"}),", and"," ",n.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.state"}),"."]})]})]})]})})}const Mp=[{type:"widget",source:"system:nav",name:"Nav Widget",w:3,h:4,icon:n.jsx(ao,{className:"w-4 h-4"})},{type:"widget",source:"system:chat",name:"Chat Widget",w:4,h:5,icon:n.jsx(Yi,{className:"w-4 h-4"})},{type:"widget",source:"system:soma",name:"SOMA",w:6,h:6,icon:n.jsx(mt,{className:"w-4 h-4"})},{type:"widget",source:"system:command-post",name:"Command Post",w:8,h:6,icon:n.jsx(Xi,{className:"w-4 h-4"})},{type:"widget",source:"system:intelligence",name:"Intelligence",w:6,h:5,icon:n.jsx(Ji,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-graph",name:"Memory Graph",w:8,h:7,icon:n.jsx(Ul,{className:"w-4 h-4"})},{type:"widget",source:"system:voice",name:"Voice",w:5,h:5,icon:n.jsx(to,{className:"w-4 h-4"})},{type:"widget",source:"system:infra",name:"Infrastructure",w:6,h:4,icon:n.jsx(Sr,{className:"w-4 h-4"})},{type:"widget",source:"system:tools",name:"Tools",w:5,h:4,icon:n.jsx(kr,{className:"w-4 h-4"})},{type:"widget",source:"system:settings",name:"Settings",w:5,h:5,icon:n.jsx(jr,{className:"w-4 h-4"})},{type:"widget",source:"system:files",name:"Files",w:4,h:6,icon:n.jsx(un,{className:"w-4 h-4"})},{type:"widget",source:"system:daemon",name:"Daemon",w:6,h:6,icon:n.jsx(gt,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-wiki",name:"Memory Wiki",w:6,h:6,icon:n.jsx(us,{className:"w-4 h-4"})},{type:"widget",source:"system:autoresearch",name:"Autoresearch",w:6,h:6,icon:n.jsx(so,{className:"w-4 h-4"})},{type:"widget",source:"system:self-proposals",name:"Self-Proposals",w:6,h:6,icon:n.jsx(oo,{className:"w-4 h-4"})},{type:"widget",source:"system:overview",name:"Overview",w:6,h:5,icon:n.jsx(io,{className:"w-4 h-4"})},{type:"widget",source:"system:sessions",name:"Sessions",w:6,h:5,icon:n.jsx(ds,{className:"w-4 h-4"})},{type:"widget",source:"system:watch",name:"Watch",w:8,h:7,icon:n.jsx(gt,{className:"w-4 h-4"})},{type:"widget",source:"system:backup",name:"Backup Manager",w:6,h:6,icon:n.jsx(ro,{className:"w-4 h-4"})},{type:"widget",source:"system:training",name:"Training Dashboard",w:6,h:6,icon:n.jsx(mt,{className:"w-4 h-4"})},{type:"widget",source:"system:recipes",name:"Recipe Kitchen",w:6,h:6,icon:n.jsx(us,{className:"w-4 h-4"})},{type:"widget",source:"system:vram",name:"VRAM Monitor",w:6,h:6,icon:n.jsx(wr,{className:"w-4 h-4"})},{type:"widget",source:"system:teams",name:"Team Hub",w:6,h:6,icon:n.jsx(_r,{className:"w-4 h-4"})},{type:"widget",source:"system:cron",name:"Cron Scheduler",w:6,h:6,icon:n.jsx(ds,{className:"w-4 h-4"})},{type:"widget",source:"system:checkpoints",name:"Checkpoints",w:6,h:5,icon:n.jsx(fn,{className:"w-4 h-4"})},{type:"widget",source:"system:organism",name:"Organism Monitor",w:6,h:6,icon:n.jsx(vr,{className:"w-4 h-4"})},{type:"widget",source:"system:fleet",name:"Fleet Router",w:6,h:5,icon:n.jsx(co,{className:"w-4 h-4"})},{type:"widget",source:"system:browser",name:"Browser Tools",w:6,h:5,icon:n.jsx(qi,{className:"w-4 h-4"})},{type:"widget",source:"system:paperclip",name:"Paperclip",w:6,h:5,icon:n.jsx(lo,{className:"w-4 h-4"})},{type:"widget",source:"system:eval",name:"Test Lab",w:6,h:6,icon:n.jsx(uo,{className:"w-4 h-4"})}];function dl({currentSpaceId:t,onSpaceSelect:e,onAction:s,onClose:r}){const[i,o]=w.useState(""),[c,l]=w.useState(0),d=w.useRef(null),p=_e.list(),m=w.useMemo(()=>{const u=i.toLowerCase(),f=p.filter(b=>b.id!==t&&b.name.toLowerCase().includes(u)).map(b=>({type:"space",id:b.id,name:b.name,color:b.color})),x=Mp.filter(b=>b.name.toLowerCase().includes(u)).map(b=>({type:"action",action:b,name:b.name}));return[...f,...x]},[i,p,t]);return w.useEffect(()=>{var u;(u=d.current)==null||u.focus()},[]),w.useEffect(()=>{l(0)},[i]),w.useEffect(()=>{const u=f=>{if((f.metaKey||f.ctrlKey)&&f.key.toLowerCase()==="k"){f.preventDefault(),r();return}if(f.key==="Escape"){r();return}if(f.key==="ArrowDown"){f.preventDefault(),l(x=>Math.min(x+1,m.length-1));return}if(f.key==="ArrowUp"){f.preventDefault(),l(x=>Math.max(x-1,0));return}if(f.key==="Enter"){f.preventDefault();const x=m[c];if(!x)return;x.type==="space"&&e(x.id),x.type==="action"&&s(x.action)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[m,c,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(Zi,{className:"w-4 h-4 text-[#3f3f46]"}),n.jsx("input",{ref:d,value:i,onChange:u=>o(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(_s,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"max-h-[50vh] overflow-auto py-1",children:[m.length===0&&n.jsxs("div",{className:"px-4 py-6 text-center text-xs text-[#52525b]",children:['No results for "',i,'"']}),m.map((u,f)=>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 ${f===c?"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 Op=ie.lazy(()=>ae(()=>import("./SomaView-CYukE7Fp.js"),__vite__mapDeps([0,1,2,3,4,5,6])));function ul(){const[t,e]=w.useState(null),[s,r]=w.useState(!1),[i,o]=w.useState(null),c=w.useCallback(async()=>{var p;try{const m=await me("/api/config");if(!m.ok)throw new Error(`HTTP ${m.status}`);const u=await m.json();e(!!((p=u==null?void 0:u.organism)!=null&&p.enabled)),o(null)}catch(m){o(m.message),e(!1)}},[]);w.useEffect(()=>{c()},[c]);const l=w.useRef(0),d=w.useCallback(async p=>{const m=++l.current;r(!0),o(null);try{const u=await me("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:{enabled:p}})});if(m!==l.current)return;if(!u.ok)throw new Error(`HTTP ${u.status}`);e(p),window.dispatchEvent(new CustomEvent("titan:soma:changed",{detail:{enabled:p}}))}catch(u){if(m!==l.current)return;o(u.message)}finally{m===l.current&&r(!1)}},[]);return t===null?n.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-[#52525b]",children:"Loading Soma…"}):t?n.jsxs("div",{className:"w-full h-full overflow-auto flex flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-[#27272a]/40 bg-[#18181b]/60",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-[#34d399] animate-pulse"}),n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-[#34d399]",children:"Soma active"})]}),n.jsxs("button",{onClick:()=>d(!1),disabled:s,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border border-[#27272a] text-[10px] text-[#a1a1aa] hover:text-white hover:border-[#3f3f46] disabled:opacity-60 transition-colors",title:"Disable Soma",children:[n.jsx(ai,{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 text-[#52525b]",children:"Loading Soma dashboard…"}),children:n.jsx(Op,{})})})]}):n.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-4 p-6 text-center",children:[n.jsx("div",{className:"w-14 h-14 rounded-full bg-gradient-to-br from-[#6366f1]/20 to-[#a78bfa]/20 border border-[#6366f1]/30 flex items-center justify-center",children:n.jsx(gt,{className:"w-7 h-7 text-[#a78bfa]"})}),n.jsxs("div",{className:"space-y-1 max-w-md",children:[n.jsx("h3",{className:"text-lg font-semibold text-white",children:"Soma is off"}),n.jsx("p",{className:"text-xs text-[#a1a1aa] leading-relaxed",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:()=>d(!0),disabled:s,className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-[#6366f1] hover:bg-[#4f46e5] disabled:opacity-60 disabled:cursor-not-allowed text-white text-sm font-medium transition-colors",children:[n.jsx(ai,{className:"w-4 h-4"}),s?"Enabling…":"Enable Soma"]}),i&&n.jsx("p",{className:"text-xs text-[#ef4444]",children:i}),n.jsx("p",{className:"text-[10px] text-[#52525b]",children:"You can turn this off anytime from the same button."})]})}const Pp={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)"}};function Wp(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 Up(){const[t,e]=w.useState(!1),[s,r]=w.useState({emotion:"calm",intensity:.3,activity:"Observing"}),[i,o]=w.useState(!1),[c,l]=w.useState({x:24,y:80}),[d,p]=w.useState(!1),m=w.useRef({x:0,y:0}),u=w.useRef(null);w.useEffect(()=>{let A=!1;const v=async()=>{try{const g=await me("/api/soma/state");if(!g.ok||A)return;const k=await g.json();if(A)return;r(Wp(Number((k==null?void 0:k.totalPressure)??0),Array.isArray(k==null?void 0:k.dominantDrives)?k.dominantDrives:[],!!(k!=null&&k.enabled)))}catch{}};v();const I=setInterval(v,15e3);return()=>{A=!0,clearInterval(I)}},[]),w.useEffect(()=>{const A=v=>{var I;(I=u.current)!=null&&I.contains(v.target)||o(!1)};return window.addEventListener("mousedown",A),()=>window.removeEventListener("mousedown",A)},[]);const f=A=>{A.button===0&&(m.current={x:A.clientX-c.x,y:A.clientY-c.y},p(!0))},x=A=>{d&&l({x:A.clientX-m.current.x,y:A.clientY-m.current.y})},b=()=>{p(!1)},j=Pp[s.emotion];return n.jsxs(n.Fragment,{children:[t&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/40 backdrop-blur-sm",onClick:()=>e(!1),children:n.jsxs("div",{className:"bg-[#1f1812]/95 border border-[#8b6b4a]/40 rounded-2xl shadow-2xl shadow-black/60 overflow-hidden",style:{width:"min(900px, 90vw)",height:"min(600px, 80vh)"},onClick:A=>A.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-[#8b6b4a]/30",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(mt,{className:"w-4 h-4",style:{color:j.primary}}),n.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider text-[#c8b89a]",children:"SOMA Consciousness"})]}),n.jsx("button",{onClick:()=>e(!1),className:"p-1 text-[#8b6b4a] hover:text-[#c8b89a]",children:n.jsx(_s,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"h-[calc(100%-40px)]",children:n.jsx(ul,{})})]})}),n.jsxs("div",{ref:u,className:"fixed z-50 select-none",style:{left:c.x,top:c.y},onMouseDown:f,onMouseMove:x,onMouseUp:b,onMouseLeave:b,children:[i&&n.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-[#2a2018]/95 backdrop-blur-xl border border-[#8b6b4a]/40 rounded-xl shadow-2xl shadow-black/60 overflow-hidden min-w-[160px] py-1",children:[n.jsxs("button",{onClick:()=>{e(!0),o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] text-[#c8b89a] hover:bg-[#3d3028]/50 transition-colors",children:[n.jsx(mt,{className:"w-3.5 h-3.5",style:{color:j.primary}}),"Open SOMA"]}),n.jsxs("button",{onClick:()=>{o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] text-[#c8b89a] hover:bg-[#3d3028]/50 transition-colors",children:[n.jsx(xr,{className:"w-3.5 h-3.5 text-[#f59e0b]"}),"Summarize Canvas"]}),n.jsxs("button",{onClick:()=>{o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] text-[#c8b89a] hover:bg-[#3d3028]/50 transition-colors",children:[n.jsx(xl,{className:"w-3.5 h-3.5 text-[#6366f1]"}),"Run Self-Check"]})]}),n.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>!d&&e(!0),onContextMenu:A=>{A.preventDefault(),o(!0)},children:[n.jsx("div",{className:"absolute inset-0 rounded-full animate-ping opacity-20",style:{background:j.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:j.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%, ${j.primary}, ${j.primary}88)`,boxShadow:`0 0 ${20+s.intensity*30}px ${j.glow}, inset 0 0 10px rgba(255,255,255,0.1)`},children:n.jsx(mt,{className:"w-5 h-5 text-white/90"})}),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 text-[#e8dcc8] bg-black/60 px-1.5 py-0.5 rounded border border-[#8b6b4a]/30",children:s.activity})})]})]})]})}const Bp=ie.lazy(()=>ae(()=>import("./CommandPostHub-CQqRYBjf.js"),__vite__mapDeps([7,1,2,3,4,8,9,10,11,12,5,13,14,15,16,17,18,19,20,21,22,23,24,25,26])));function Fp(){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(Bp,{})})})}const $p=ie.lazy(()=>ae(()=>import("./IntelligenceView-Dh-Wuf13.js"),__vite__mapDeps([27,1,2])));function zp(){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($p,{})})})}const Hp=ie.lazy(()=>ae(()=>import("./MemoryGraphPanel-F1P9COyY.js"),__vite__mapDeps([28,1,2,29,12,26,30])));function Vp(){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(Hp,{})})})})}function Gp(){const[t,e]=w.useState(!1);return t?n.jsx(Tl,{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(to,{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 qp=ie.lazy(()=>ae(()=>import("./InfraView-CHYaZqMK.js"),__vite__mapDeps([31,1,2])));function Yp(){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(qp,{})})})}const Kp=ie.lazy(()=>ae(()=>import("./ToolsView-CnUjq0Js.js"),__vite__mapDeps([32,1,2])));function Jp(){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(Kp,{})})})}const Xp=ie.lazy(()=>ae(()=>import("./SettingsView-Dsa7Zr4e.js"),__vite__mapDeps([33,1,2])));function Qp(){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(Xp,{})})})}function Zp(){const[t,e]=w.useState([]),[s,r]=w.useState("/"),[i,o]=w.useState(!1),c=async()=>{o(!0);try{const l=await me(`/api/files?path=${encodeURIComponent(s)}`);if(l.ok){const d=await l.json();e(d.files||[])}else e([{name:"documents",path:"/documents",type:"directory"},{name:"readme.md",path:"/readme.md",type:"file"},{name:"config.yaml",path:"/config.yaml",type:"file"}])}catch{e([{name:"documents",path:"/documents",type:"directory"},{name:"readme.md",path:"/readme.md",type:"file"},{name:"config.yaml",path:"/config.yaml",type:"file"}])}finally{o(!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(Al,{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(hn,{className:`w-3 h-3 ${i?"animate-spin":""}`})})]}),n.jsx("div",{className:"flex-1 overflow-auto",children:t.map(l=>n.jsxs("button",{onClick:()=>l.type==="directory"&&r(l.path),className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-[#27272a]/20 transition-colors",children:[l.type==="directory"?n.jsx(Rl,{className:"w-3.5 h-3.5 text-[#f59e0b]"}):n.jsx(un,{className:"w-3.5 h-3.5 text-[#6366f1]"}),n.jsx("span",{className:"text-[12px] text-[#a1a1aa]",children:l.name})]},l.path))})]})}const eg=ie.lazy(()=>ae(()=>import("./SettingsPanel-BlsRDAt7.js"),__vite__mapDeps([34,1,2,3,4,35,14,5,36,37,38,12,39,40,41,42,25,21,15,29,43,30,24,44,20,11,45,46])));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=ie.lazy(()=>ae(()=>import("./SecurityPanel-_gqMk8hJ.js"),__vite__mapDeps([47,1,2,35,14])));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=ie.lazy(()=>ae(()=>import("./AuditPanel-DrDvXZ9u.js"),__vite__mapDeps([48,1,2,12,49])));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 Fi={researcher:"#60a5fa",engineer:"#f87171",manager:"#a78bfa",ceo:"#fbbf24",general:"#9ca3af"},og={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 ag(){const[t,e]=w.useState(null),[s,r]=w.useState({}),[i,o]=w.useState({}),[c,l]=w.useState(null),[d,p]=w.useState({}),[m,u]=w.useState(!0),f=w.useCallback(async()=>{l(null);try{const[j,A]=await Promise.all([me("/api/specialists"),me("/api/models")]);if(!j.ok)throw new Error(`Specialists request failed: ${j.status}`);if(!A.ok)throw new Error(`Models request failed: ${A.status}`);const v=await j.json(),I=await A.json();e(v),r(I);const g={};await Promise.all(v.map(async k=>{try{const _=await me(`/api/specialists/${encodeURIComponent(k.id)}/recommendations`);if(_.ok){const T=await _.json();T.recommendations&&(g[k.id]=T.recommendations)}}catch{}})),o(g)}catch(j){l(j.message)}finally{u(!1)}},[]);w.useEffect(()=>{f()},[f]);const x=w.useCallback(j=>{const A=i[j];if(A&&A.length)return A.map(I=>I.id);const v=new Set;if(s&&typeof s=="object")for(const I of Object.keys(s)){const g=s[I];if(Array.isArray(g))for(const k of g)typeof k=="string"?v.add(k):k&&typeof k=="object"&&"id"in k&&typeof k.id=="string"&&v.add(k.id)}if(Array.isArray(t))for(const I of t)I!=null&&I.activeModel&&v.add(I.activeModel),I!=null&&I.defaultModel&&v.add(I.defaultModel);return Array.from(v).sort((I,g)=>I.localeCompare(g))},[i,s,t]),b=w.useCallback(async(j,A)=>{p(v=>({...v,[j]:"saving"}));try{const v=await me(`/api/specialists/${encodeURIComponent(j)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:A})});if(!v.ok){const g=await v.text().catch(()=>"");throw new Error(`PATCH failed (${v.status}): ${g||v.statusText}`)}const I=await v.json();e(g=>(g==null?void 0:g.map(k=>k.id===j?{...k,activeModel:I.activeModel??k.defaultModel,overridden:(I.activeModel??k.defaultModel)!==k.defaultModel}:k))??null),p(g=>({...g,[j]:"saved"})),setTimeout(()=>{p(g=>{if(g[j]!=="saved")return g;const k={...g};return delete k[j],k})},1500)}catch(v){p(I=>({...I,[j]:"error"})),l(`${j}: ${v.message}`)}},[]);return m&&!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(_r,{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),f()},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(hn,{className:`w-3 h-3 ${m?"animate-spin":""}`}),"Refresh"]})]}),c&&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(dn,{className:"w-3 h-3 mt-0.5 shrink-0"}),n.jsx("span",{className:"font-mono",children:c})]}),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(j=>n.jsx(lg,{row:j,models:x(j.id),recommendations:i[j.id]??[],state:d[j.id]??"idle",onChange:A=>b(j.id,A),onReset:()=>b(j.id,null)},j.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 lg({row:t,models:e,recommendations:s,state:r,onChange:i,onReset:o}){var u;const c=Fi[t.role]??Fi.general,l=s.find(f=>f.id===t.activeModel),d=s[0]??null,[p,m]=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:c},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:f=>i(f.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(f=>{const x=s.find(A=>A.id===f),b=(x==null?void 0:x.badges)??[],j=b.length?`${f} [${b.join(", ")}]`:f;return n.jsx("option",{value:f,children:j},f)})}),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(f=>n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${og[f]??"bg-[#27272a] text-[#a1a1aa] border-[#27272a]"}`,children:f},f))}),t.overridden&&n.jsxs("button",{onClick:o,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(Qi,{className:"w-3 h-3"}),"Reset"]}),n.jsx("button",{onClick:()=>m(f=>!f),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(ri,{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(hn,{className:"w-3.5 h-3.5 animate-spin text-[#6366f1]"}),r==="saved"&&n.jsx(ii,{className:"w-3.5 h-3.5 text-[#10b981]"}),r==="error"&&n.jsx(dn,{className:"w-3.5 h-3.5 text-[#ef4444]"})]})]})]}),p&&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(ri,{className:"w-3 h-3 mt-0.5 shrink-0 text-[#6366f1]"}),n.jsx("span",{children:l.rationale})]}),d&&d.id!==t.activeModel&&n.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[#10b981]",children:[n.jsx(ii,{className:"w-3 h-3 shrink-0"}),n.jsxs("span",{children:["Recommended upgrade: ",n.jsx("span",{className:"font-mono",children:d.id})," (score ",d.score,"/100)",d.badges.length>0&&n.jsxs("span",{className:"ml-1 text-[#71717a]",children:["[",d.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:c},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 cg(){const[t,e]=w.useState(null),[s,r]=w.useState(null),[i,o]=w.useState(null),[c,l]=w.useState(!1),[d,p]=w.useState(null),[m,u]=w.useState(null),f=w.useCallback(async()=>{p(null);try{const[A,v,I]=await Promise.all([me("/api/telemetry/consent").then(g=>g.ok?g.json():Promise.reject(new Error(`consent ${g.status}`))),me("/api/analytics/profile").then(g=>g.ok?g.json():null),me("/api/telemetry/status").then(g=>g.ok?g.json():null)]);e(A),r(v),I!=null&&I.remote&&o(I.remote)}catch(A){p(A.message)}},[]);w.useEffect(()=>{const A=setInterval(()=>{me("/api/telemetry/status").then(v=>v.ok?v.json():null).then(v=>{v!=null&&v.remote&&o(v.remote)}).catch(()=>{})},15e3);return()=>clearInterval(A)},[]),w.useEffect(()=>{f()},[f]);const x=w.useCallback(async A=>{l(!0),p(null);try{const v=await me("/api/telemetry/consent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!v.ok)throw new Error(`save failed: ${v.status}`);const I=await v.json();e(g=>g?{...g,...I,consentedAt:I.enabled?new Date().toISOString():void 0}:null),u(Date.now()),setTimeout(()=>u(null),2e3)}catch(v){p(v.message)}finally{l(!1)}},[]),b=!!(t!=null&&t.enabled),j=!!(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:[b?n.jsx(Il,{className:"w-5 h-5 text-[#10b981]"}):n.jsx(vr,{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 ${b?"border-[#10b981]/40 bg-[#10b981]/10 text-[#10b981]":"border-[#3f3f46] bg-[#18181b] text-[#71717a]"}`,children:b?"ENABLED":"OFF"}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[m&&n.jsxs("span",{className:"text-[11px] text-[#10b981] flex items-center gap-1",children:[n.jsx(wl,{className:"w-3 h-3"})," Saved"]}),d&&n.jsxs("span",{className:"text-[11px] text-[#ef4444] flex items-center gap-1",children:[n.jsx(vl,{className:"w-3 h-3"})," ",d]}),n.jsxs("button",{onClick:()=>{f()},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(hn,{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:b,disabled:c,onChange:A=>x({enabled:A.target.checked,crashReports:j}),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 ${b?"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:j,disabled:c||!b,onChange:A=>x({enabled:b,crashReports:A.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(dn,{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(eo,{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(ds,{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(oi,{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(oi,{className:"w-3 h-3"})," See the collector source"]})]})]})}const dg=ie.lazy(()=>ae(()=>import("./AutopilotPanel-C3yQBxAp.js"),__vite__mapDeps([50,1,2,35,14])));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=ie.lazy(()=>ae(()=>import("./WorkflowsPanel-DdY6E93C.js"),__vite__mapDeps([51,1,2,35,14,3,4,10,11,12,22,25,38,40,16,26,20,52,42,21,15,29,41,43,30,24,37,44,45,46])));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=ie.lazy(()=>ae(()=>import("./LearningPanel-CtlougkF.js"),__vite__mapDeps([53,1,2,35,14,12,15,54,55,42,25,21,29,41,43,30,24,37,38,44,20,11,45,46,4])));function gg(){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 mg=ie.lazy(()=>ae(()=>import("./SelfImprovePanel-B8o_fO30.js"),__vite__mapDeps([56,1,2,12,36,20,57,55,15,38,14,40,26,42,25,21,29,41,43,30,24,37,44,11,45,46,4])));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(mg,{})})})}const bg=ie.lazy(()=>ae(()=>import("./PersonasPanel-DIac_kZ3.js"),__vite__mapDeps([58,1,2])));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=ie.lazy(()=>ae(()=>import("./PersonaProfilesPanel-CfsQTMra.js"),__vite__mapDeps([59,1,2,35,14,12,11,16,37,38,20])));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=ie.lazy(()=>ae(()=>import("./DreamPanel-CO7iSdjn.js"),__vite__mapDeps([60,1,2,35,14,12])));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=ie.lazy(()=>ae(()=>import("./HomelabPanel-DjMUrO2B.js"),__vite__mapDeps([61,1,2,35,14,62,63,12,20,21,19,29,36,17,42,25,15,41,43,30,24,37,38,44,11,45,46,4])));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=ie.lazy(()=>ae(()=>import("./NvidiaPanel-qLJysI9M.js"),__vite__mapDeps([64,1,2,12,41,36,46,30,65,42,25,21,15,29,43,24,37,14,38,44,20,11,45,4])));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=ie.lazy(()=>ae(()=>import("./FilesPanel-dRQM0apb.js"),__vite__mapDeps([66,1,2,25,12,14,67,20,26,41,39,11,21,42,15,29,43,30,24,37,38,44,45,46,4])));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 Rg=ie.lazy(()=>ae(()=>import("./LogsPanel-Bs9IsTCH.js"),__vite__mapDeps([68,1,2,12])));function Ag(){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 Ig=ie.lazy(()=>ae(()=>import("./TelemetryPanel-DXAGuV0R.js"),__vite__mapDeps([69,1,2,62,20,18,19,42,25,21,15,29,12,41,43,30,24,37,14,38,44,11,45,46,4])));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=ie.lazy(()=>ae(()=>import("./SkillsPanel-D08WcRGp.js"),__vite__mapDeps([70,1,2,35,14,30,26,39])));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=ie.lazy(()=>ae(()=>import("./McpPanel-BobqpLsh.js"),__vite__mapDeps([71,1,2,72,12,25,26,42,21,15,29,41,43,30,24,37,14,38,44,20,11,45,46,4])));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=ie.lazy(()=>ae(()=>import("./IntegrationsPanel-CFucvr-Q.js"),__vite__mapDeps([73,1,2,72,36,65,41,38,14,42,25,21,15,29,12,43,30,24,37,44,20,11,45,46,4])));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(Wg,{})})})}const Bg=ie.lazy(()=>ae(()=>import("./ChannelsPanel-CiJs4gyw.js"),__vite__mapDeps([74,1,2,35,14,12,36,38,65,41,42,25,21,15,29,43,30,24,37,44,20,11,45,46,4])));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=ie.lazy(()=>ae(()=>import("./MeshPanel-CgIAh5ZX.js"),__vite__mapDeps([75,1,2,76,12,45])));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=ie.lazy(()=>ae(()=>import("./MemoryWikiPanel-BfYksjoI.js"),__vite__mapDeps([77,1,2,35,14,67,20,30,42,25,21,15,29,12,41,43,24,37,38,44,11,45,46,4])));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=ie.lazy(()=>ae(()=>import("./AutoresearchPanel-BgpR3EcK.js"),__vite__mapDeps([78,1,2,44,40,16,12,57,55,20,38,14])));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(Gg,{})})})}const Yg=ie.lazy(()=>ae(()=>import("./SelfProposalsPanel-DuA0zsGH.js"),__vite__mapDeps([79,1,2,35,14,20,42,25,21,15,29,12,41,43,30,24,37,38,44,11,45,46,4])));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(Yg,{})})})}const Jg=ie.lazy(()=>ae(()=>import("./OverviewPanel-Be6LukJ_.js"),__vite__mapDeps([80,1,2,62,35,14,63,20,21,81,42,25,15,29,12,41,43,30,24,37,38,44,11,45,46,4])));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 Qg=ie.lazy(()=>ae(()=>import("./SessionsPanel-DeCBkSgY.js"),__vite__mapDeps([82,1,2,35,14,3,4,76,10,11,12,30,26])));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(Qg,{})})})}const em=ie.lazy(()=>ae(()=>import("./WatchView-CaQMDEAy.js"),__vite__mapDeps([83,1,2,9])));function tm(){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(em,{})})})}const sm=ie.lazy(()=>ae(()=>import("./BackupPanel-BNxMlNIP.js"),__vite__mapDeps([84,1,2,35,14,25,12,36,42,21,15,29,41,43,30,24,37,38,44,20,11,45,46,4])));function nm(){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(sm,{})})})}const rm=ie.lazy(()=>ae(()=>import("./TrainingPanel-BLf_KMaE.js"),__vite__mapDeps([85,1,2,35,14,12,39,42,25,21,15,29,41,43,30,24,37,38,44,20,11,45,46,4])));function im(){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(rm,{})})})}const om=ie.lazy(()=>ae(()=>import("./RecipesPanel-DDYOCx3w.js"),__vite__mapDeps([86,1,2,35,14,12,40,26,42,25,21,15,29,41,43,30,24,37,38,44,20,11,45,46,4])));function am(){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(om,{})})})}const lm=ie.lazy(()=>ae(()=>import("./VramPanel-CJiic8y4.js"),__vite__mapDeps([87,1,2,35,14,12])));function cm(){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(lm,{})})})}const dm=ie.lazy(()=>ae(()=>import("./TeamsPanel-DOBe72TK.js"),__vite__mapDeps([88,1,2,35,14,12,21,26])));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(dm,{})})})}const hm=ie.lazy(()=>ae(()=>import("./CronPanel-Brmnnu8_.js"),__vite__mapDeps([89,1,2,35,14,12,20,52,26])));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(hm,{})})})}const pm=ie.lazy(()=>ae(()=>import("./CheckpointsPanel-DvKUd2VF.js"),__vite__mapDeps([90,1,2,35,14,12,41,26])));function gm(){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(pm,{})})})}const mm=ie.lazy(()=>ae(()=>import("./OrganismPanel-CNZM3eof.js"),__vite__mapDeps([91,1,2,35,14,12,36])));function ym(){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(mm,{})})})}const bm=ie.lazy(()=>ae(()=>import("./FleetPanel-Bg-f3_ip.js"),__vite__mapDeps([92,1,2,35,14,12,42,25,21,15,29,41,43,30,24,37,38,44,20,11,45,46,4])));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(bm,{})})})}const wm=ie.lazy(()=>ae(()=>import("./BrowserPanel-BNaKZOnn.js"),__vite__mapDeps([93,1,2,35,14])));function vm(){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 _m=ie.lazy(()=>ae(()=>import("./EvalPanel-CqAwhFQ5.js"),__vite__mapDeps([94,1,2,35,14,12,40])));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(_m,{})})})}function Sm(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 jm(t){const e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e>=0?t.slice(e+1):t}function Em(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(""),[c,l]=w.useState(null),[d,p]=w.useState(""),[m,u]=w.useState(!1),[f,x]=w.useState(null),[b,j]=w.useState(null),[A,v]=w.useState(null),I=w.useCallback(async()=>{r(!0),x(null);try{const C=await me("/api/time-travel/checkpoints?limit=100");if(!C.ok)throw new Error(`${C.status} ${C.statusText}`);const M=await C.json();e(M.checkpoints||[])}catch(C){x(C.message||"Failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{I()},[I]);const g=w.useCallback((C,M)=>{v({kind:C,message:M}),setTimeout(()=>v(null),4e3)},[]),k=w.useCallback(async C=>{l(C),p(""),u(!0);try{const M=await me(`/api/time-travel/diff/${encodeURIComponent(C)}`);if(!M.ok)throw new Error(`${M.status} ${M.statusText}`);const S=await M.json();p(S.diff||"(no diff returned)")}catch(M){p(`Failed to load diff: ${M.message}`)}finally{u(!1)}},[]),_=w.useCallback(C=>{j(C)},[]),T=w.useCallback(async()=>{if(!b)return;const C=b;j(null);try{const M=await me(`/api/time-travel/restore/${encodeURIComponent(C)}`,{method:"POST"});if(!M.ok)throw new Error(`${M.status} ${M.statusText}`);const S=await M.json();S.ok?(g("ok",S.message||`Restored to ${C.slice(0,8)}.`),I()):g("err",S.message||"Restore failed.")}catch(M){g("err",M.message||"Restore failed.")}},[b,I,g]),E=w.useMemo(()=>{const C=i.trim().toLowerCase();return C?t.filter(M=>M.filePath.toLowerCase().includes(C)||M.toolName.toLowerCase().includes(C)||M.id.toLowerCase().includes(C)):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:C=>o(C.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"})]})]}),A&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,background:A.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${A.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:A.kind==="ok"?"#86efac":"#fca5a5",fontSize:11},children:A.message}),f&&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:f}),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(C=>n.jsxs("div",{onClick:()=>k(C.id),style:{padding:"8px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",cursor:"pointer",background:c===C.id?"rgba(99,102,241,0.08)":"transparent",borderLeft:c===C.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:C.commitHash.slice(0,8)}),n.jsx("span",{style:{fontSize:10,color:"rgba(255,255,255,0.5)"},children:Sm(C.timestamp)})]}),n.jsx("div",{style:{fontSize:12,color:"#e2e8f5",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:C.filePath,children:jm(C.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:C.toolName})]}),n.jsx("button",{onClick:M=>{M.stopPropagation(),_(C.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"})]})]},C.id))}),n.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:c?m?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:(d||"").split(`
997
- `).map((C,M)=>{let S="rgba(255,255,255,0.7)";return C.startsWith("+")&&!C.startsWith("+++")?S="#86efac":C.startsWith("-")&&!C.startsWith("---")?S="#fca5a5":C.startsWith("@@")?S="#a5b4fc":(C.startsWith("diff")||C.startsWith("index")||C.startsWith("+++")||C.startsWith("---"))&&(S="rgba(255,255,255,0.45)"),n.jsx("div",{style:{color:S},children:C||" "},M)})}):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."})})]}),b&&n.jsx("div",{onClick:()=>j(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:C=>C.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:b.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:()=>j(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:T,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 $i=5e3,zi={planning:"#a5b4fc",delegating:"#60a5fa",observing:"#22d3ee",iterating:"#f59e0b",verifying:"#a78bfa",reporting:"#34d399",blocked:"#facc15",escalated:"#fb7185",done:"#34d399",failed:"#ef4444",cancelled:"#737373"};function Nm(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 Cm(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function Tm(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(null),[c,l]=w.useState(!1),[d,p]=w.useState(""),[m,u]=w.useState(2),[f,x]=w.useState(!1),[b,j]=w.useState(null),A=w.useCallback(async()=>{try{const _=await me("/api/missions/active");if(!_.ok)throw new Error(`${_.status} ${_.statusText}`);const T=await _.json();e(T.missions||[]),o(null)}catch(_){o(_.message||"failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{A();const _=setInterval(A,$i);return()=>clearInterval(_)},[A]);const v=w.useCallback((_,T)=>{j({kind:_,message:T}),setTimeout(()=>j(null),5e3)},[]),I=w.useCallback(async()=>{var T;const _=d.trim();if(_.length<10){v("err","Describe the mission (>=10 chars).");return}x(!0);try{const E=await me("/api/mission/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:_,budgetUsd:m})});if(!E.ok)throw new Error(`${E.status} ${E.statusText}`);const C=await E.json();v("ok",C.message||`Mission "${((T=C.goal)==null?void 0:T.title)??"?"}" launched.`),p(""),l(!1),A()}catch(E){v("err",E.message||"launch failed")}finally{x(!1)}},[d,m,A,v]),g=w.useCallback(async _=>{try{const T=await me(`/api/mission/${encodeURIComponent(_)}/cancel`,{method:"POST"});if(!T.ok)throw new Error(`${T.status} ${T.statusText}`);v("ok","Mission marked for cancellation."),A()}catch(T){v("err",T.message||"cancel failed")}},[A,v]),k=w.useMemo(()=>{const _={delegating:0,observing:1,iterating:2,verifying:3,planning:4,reporting:5,blocked:6,escalated:7};return[...t].sort((T,E)=>(_[T.phase]??99)-(_[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 ",$i/1e3,"s"]})]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("button",{onClick:()=>l(_=>!_),title:"Launch a new autonomous mission",style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid rgba(99,102,241,0.4)",background:c?"rgba(99,102,241,0.25)":"rgba(99,102,241,0.12)",color:"#c7d2fe",cursor:"pointer"},children:c?"× Close":"+ New mission"}),n.jsx("button",{onClick:A,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:"↻"})]})]}),b&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,fontSize:11,background:b.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${b.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:b.kind==="ok"?"#86efac":"#fca5a5"},children:b.message}),c&&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:d,onChange:_=>p(_.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:m,onChange:_=>u(Math.max(.05,Math.min(50,Number(_.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:f||d.trim().length<10,style:{fontSize:12,padding:"6px 14px",borderRadius:6,border:"none",background:f?"rgba(255,255,255,0.05)":"rgba(34,197,94,0.18)",color:"#86efac",cursor:f?"wait":"pointer",fontWeight:600},children:f?"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…"}):k.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.'})]}):k.map(_=>{const T=zi[_.phase]??"#94a3b8",E=_.subtasks.total>0?Math.round(_.subtasks.completed/_.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 ${_.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:_.title,children:_.title}),n.jsx("button",{onClick:()=>g(_.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:`${T}22`,border:`1px solid ${T}55`,color:T,textTransform:"uppercase",letterSpacing:.5,fontWeight:600,fontSize:9},children:_.phase}),n.jsxs("span",{children:[_.subtasks.completed,"/",_.subtasks.total," subtasks (",E,"%)"]}),n.jsx("span",{children:"·"}),n.jsx("span",{children:Cm(_.budget.costUsd)}),n.jsx("span",{children:"·"}),n.jsx("span",{children:Nm(Date.now()-new Date(_.startedAt).getTime())})]}),_.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:"})," ",_.blockedReason.question??"(no reason)"]}),_.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:_.lastHistory.slice(-3).map((C,M)=>n.jsxs("div",{style:{display:"flex",gap:6,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n.jsx("span",{style:{color:zi[C.phase]??"rgba(255,255,255,0.6)",minWidth:70,fontFamily:"ui-monospace, monospace",fontSize:9},children:C.phase}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C.note??""})]},M))})]},_.goalId)})]})]})}const Rm=6e4,Am=[{label:"6h",hours:6},{label:"24h",hours:24},{label:"7d",hours:168}];function Im(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function Lm(t){return t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(1)}k`:`${(t/1e6).toFixed(2)}M`}function Dm(){const[t,e]=w.useState(24),[s,r]=w.useState(null),[i,o]=w.useState(!0),[c,l]=w.useState(null),d=w.useCallback(async()=>{o(!0);try{const p=await me(`/api/missions/digest?hours=${t}`);if(!p.ok)throw new Error(`${p.status} ${p.statusText}`);const m=await p.json();r(m),l(null)}catch(p){l(p.message||"failed")}finally{o(!1)}},[t]);return w.useEffect(()=>{d();const p=setInterval(d,Rm);return()=>clearInterval(p)},[d]),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:Am.map(p=>n.jsx("button",{onClick:()=>e(p.hours),style:{fontSize:10,padding:"3px 8px",borderRadius:4,border:"1px solid rgba(255,255,255,0.1)",background:t===p.hours?"rgba(99,102,241,0.25)":"rgba(255,255,255,0.03)",color:t===p.hours?"#c7d2fe":"rgba(255,255,255,0.65)",cursor:"pointer"},children:p.label},p.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(Ms,{label:"Done",value:s.stats.completed,color:"#34d399"}),n.jsx(Ms,{label:"Failed",value:s.stats.failed,color:s.stats.failed>0?"#fca5a5":"rgba(255,255,255,0.5)"}),n.jsx(Ms,{label:"Active",value:s.stats.active,color:"#60a5fa"}),n.jsx(Ms,{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:Im(s.stats.totalCostUsd)})]}),n.jsxs("span",{children:["Tokens: ",n.jsx("strong",{style:{color:"#e2e8f5"},children:Lm(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…"}),c&&n.jsx("div",{style:{color:"#fca5a5",fontSize:11},children:c}),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((p,m)=>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:["• ",p]},m))]})]})]})]})}function Ms({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 Os={pending:"#737373",running:"#60a5fa",done:"#34d399",failed:"#ef4444",skipped:"#a78bfa"},Hi=6e3,vt=180,Zn=64,Vi=96,Ps=24;function Mm(t){const e=new Map,s=new Map(t.map(i=>[i.id,i])),r=(i,o)=>{if(e.has(i))return e.get(i);if(o.has(i))return 0;const c=s.get(i);if(!c)return 0;o.add(i);const l=(c.dependsOn??[]).filter(p=>s.has(p)),d=l.length===0?0:Math.max(...l.map(p=>r(p,o)))+1;return o.delete(i),e.set(i,d),d};for(const i of t)r(i.id,new Set);return e}function Om(){const[t,e]=w.useState([]),[s,r]=w.useState(null),[i,o]=w.useState(null),[c,l]=w.useState(null),[d,p]=w.useState(null),m=w.useCallback(async()=>{try{const v=await me("/api/missions/active");if(!v.ok)throw new Error(`${v.status} ${v.statusText}`);const g=(await v.json()).missions||[];e(g),!s&&g.length>0&&r(g[0].goalId)}catch(v){l(v.message||"failed")}},[s]),u=w.useCallback(async v=>{try{const I=await me(`/api/mission/${encodeURIComponent(v)}`);if(!I.ok)throw new Error(`${I.status} ${I.statusText}`);const g=await I.json();o(g),l(null)}catch(I){l(I.message||"failed to load mission"),o(null)}},[]);w.useEffect(()=>{m();const v=setInterval(m,Hi);return()=>clearInterval(v)},[m]),w.useEffect(()=>{if(!s){o(null);return}u(s);const v=setInterval(()=>u(s),Hi);return()=>clearInterval(v)},[s,u]);const{layout:f,edges:x,viewBox:b}=w.useMemo(()=>{if(!(i!=null&&i.goal.subtasks))return{layout:[],edges:[],viewBox:"0 0 600 200"};const v=i.goal.subtasks,I=Mm(v),g=new Map;for(const R of v){const O=I.get(R.id)??0;g.has(O)||g.set(O,[]),g.get(O).push(R)}const k=Array.from(g.keys()).sort((R,O)=>R-O),_=Math.max(...Array.from(g.values()).map(R=>R.length),1),T=Math.max(640,_*(vt+Ps)+Ps),E=k.length*Vi+Zn+40,C=new Map,M=[];for(const R of k){const O=g.get(R),B=O.length*vt+(O.length-1)*Ps,z=(T-B)/2,G=R*Vi+20;for(let q=0;q<O.length;q++){const W=z+q*(vt+Ps);C.set(O[q].id,{x:W,y:G}),M.push({...O[q],x:W,y:G})}}const S=[];for(const R of v){const O=C.get(R.id);if(O)for(const B of R.dependsOn??[]){const z=C.get(B);z&&S.push({from:B,to:R.id,x1:z.x+vt/2,y1:z.y+Zn,x2:O.x+vt/2,y2:O.y})}}return{layout:M,edges:S,viewBox:`0 0 ${T} ${E}`}},[i]),j=w.useMemo(()=>new Map(((i==null?void 0:i.goal.subtasks)??[]).map(v=>[v.id,v])),[i]),A=d?j.get(d):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:v=>r(v.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(v=>n.jsxs("option",{value:v.goalId,children:[v.title," [",v.phase,"]"]},v.goalId))})]}),c&&n.jsx("div",{style:{padding:10,color:"#fca5a5",fontSize:11},children:c}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[n.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:i?f.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:b,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)"})})}),x.map((v,I)=>n.jsx("line",{x1:v.x1,y1:v.y1,x2:v.x2,y2:v.y2,stroke:"rgba(255,255,255,0.25)",strokeWidth:"1.4",markerEnd:"url(#mg-arrow)"},`e-${I}`)),f.map(v=>{var _;const I=((_=i.driver)==null?void 0:_.currentSubtaskId)===v.id,g=Os[v.status],k=d===v.id;return n.jsxs("g",{transform:`translate(${v.x}, ${v.y})`,onClick:()=>p(v.id),style:{cursor:"pointer"},children:[n.jsx("rect",{width:vt,height:Zn,rx:"8",fill:I?`${g}22`:"rgba(255,255,255,0.04)",stroke:k||I?g:`${g}55`,strokeWidth:I||k?2:1}),n.jsx("circle",{cx:14,cy:14,r:"5",fill:g,children:v.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:v.title.length>22?v.title.slice(0,21)+"…":v.title}),n.jsxs("text",{x:28,y:34,fontSize:"9",fill:"rgba(255,255,255,0.55)",letterSpacing:"0.5",style:{textTransform:"uppercase"},children:[v.status,v.retries>0?` · ${v.retries} retr${v.retries===1?"y":"ies"}`:""]}),n.jsxs("text",{x:14,y:52,fontSize:"9",fill:"rgba(255,255,255,0.45)",children:[(v.description||"").slice(0,30),(v.description||"").length>30?"…":""]}),I&&n.jsx("text",{x:vt-8,y:14,fontSize:"8",fill:g,textAnchor:"end",fontWeight:"700",children:"NOW"})]},v.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."})}),A&&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:A.title}),n.jsx("button",{onClick:()=>p(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:`${Os[A.status]}22`,border:`1px solid ${Os[A.status]}55`,color:Os[A.status]},children:A.status}),A.retries>0&&n.jsxs("span",{style:{marginLeft:6,color:"rgba(255,255,255,0.5)"},children:[A.retries," retries"]})]}),n.jsx("div",{style:{color:"rgba(255,255,255,0.85)",lineHeight:1.5,marginBottom:10},children:A.description}),A.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:"})," ",A.dependsOn.map(v=>{var I;return((I=j.get(v))==null?void 0:I.title)||v}).join(", ")]}),A.completedAt&&n.jsxs("div",{style:{color:"rgba(255,255,255,0.45)",fontSize:10},children:["Completed: ",new Date(A.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 Pm(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(null),c=async()=>{try{const l=await fetch("/api/agents");if(!l.ok)throw new Error(`HTTP ${l.status}`);const d=await l.json();e(Array.isArray(d)?d:d.agents||[]),o(null)}catch(l){o(l.message)}finally{r(!1)}};return w.useEffect(()=>{c();const l=setInterval(c,1e4);return()=>clearInterval(l)},[]),s?n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(no,{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(dn,{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(Ki,{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 Wm(){const[t,e]=w.useState(null),[s,r]=w.useState(!0),i=async()=>{try{const[c,l]=await Promise.allSettled([fetch("/api/health").then(m=>m.ok?m.json():null),fetch("/ollama/api/tags").then(m=>m.ok)]),d=c.status==="fulfilled"&&c.value,p=l.status==="fulfilled"&&l.value;e({gateway:d,ollama:p,version:(d==null?void 0:d.version)||"unknown",uptime:(d==null?void 0:d.uptime)||0})}catch{e({gateway:!1,ollama:!1,version:"unknown",uptime:0})}finally{r(!1)}};if(w.useEffect(()=>{i();const c=setInterval(i,3e4);return()=>clearInterval(c)},[]),s)return n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(no,{className:"w-4 h-4 text-[#6366f1] animate-spin"})});const o=c=>{const l=Math.floor(c/3600),d=Math.floor(c%3600/60);return`${l}h ${d}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(_l,{className:"w-3.5 h-3.5 text-emerald-400"}):n.jsx(rc,{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(gt,{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:o((t==null?void 0:t.uptime)||0)})]})]})]})})}function Ws({label:t,value:e,icon:s,color:r}){const i=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.jsxs("span",{className:"text-[11px] text-[#a1a1aa] font-mono",children:[i,"%"]})]}),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}%`,backgroundColor:r}})})]})}function Um(){const[t,e]=w.useState({cpu:0,memory:0,disk:0,load:0});return w.useEffect(()=>{const s=setInterval(()=>{e({cpu:Math.random()*60+10,memory:Math.random()*50+30,disk:Math.random()*40+20,load:Math.random()*30+5})},3e3);return e({cpu:Math.random()*60+10,memory:Math.random()*50+30,disk:Math.random()*40+20,load:Math.random()*30+5}),()=>clearInterval(s)},[]),n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsxs("div",{className:"space-y-2",children:[n.jsx(Ws,{label:"CPU",value:t.cpu,icon:n.jsx(wr,{className:"w-3 h-3 text-[#6366f1]"}),color:"#6366f1"}),n.jsx(Ws,{label:"Memory",value:t.memory,icon:n.jsx(kl,{className:"w-3 h-3 text-[#a78bfa]"}),color:"#a78bfa"}),n.jsx(Ws,{label:"Disk",value:t.disk,icon:n.jsx(Sl,{className:"w-3 h-3 text-[#10b981]"}),color:"#10b981"}),n.jsx(Ws,{label:"Load",value:t.load,icon:n.jsx(gt,{className:"w-3 h-3 text-[#f59e0b]"}),color:"#f59e0b"})]})})}const Bm=[{label:"Nav",source:"system:nav",w:3,h:4,icon:n.jsx(Pl,{className:"w-3.5 h-3.5"})},{label:"Agents",source:"system:agents",w:3,h:4,icon:n.jsx(Ki,{className:"w-3.5 h-3.5"})},{label:"Health",source:"system:health",w:3,h:3,icon:n.jsx(gt,{className:"w-3.5 h-3.5"})},{label:"Stats",source:"system:stats",w:3,h:4,icon:n.jsx($l,{className:"w-3.5 h-3.5"})},{label:"Chat",source:"system:chat",w:4,h:5,icon:n.jsx(Yi,{className:"w-3.5 h-3.5"})},{label:"Files",source:"system:files",w:4,h:6,icon:n.jsx(un,{className:"w-3.5 h-3.5"})},{label:"Skills",source:"system:tools",w:5,h:4,icon:n.jsx(xr,{className:"w-3.5 h-3.5"})},{label:"Soma",source:"system:soma",w:6,h:6,icon:n.jsx(Vl,{className:"w-3.5 h-3.5"})},{label:"Intel",source:"system:intelligence",w:6,h:5,icon:n.jsx(mt,{className:"w-3.5 h-3.5"})},{label:"Infra",source:"system:infra",w:6,h:4,icon:n.jsx(Sr,{className:"w-3.5 h-3.5"})},{label:"Tools",source:"system:tools",w:5,h:4,icon:n.jsx(kr,{className:"w-3.5 h-3.5"})},{label:"Settings",source:"system:settings",w:4,h:6,icon:n.jsx(jr,{className:"w-3.5 h-3.5"})},{label:"Daemon",source:"system:daemon",w:5,h:5,icon:n.jsx(gt,{className:"w-3.5 h-3.5"})},{label:"Wiki",source:"system:memory-wiki",w:5,h:5,icon:n.jsx(us,{className:"w-3.5 h-3.5"})},{label:"Research",source:"system:autoresearch",w:5,h:5,icon:n.jsx(so,{className:"w-3.5 h-3.5"})},{label:"Proposals",source:"system:self-proposals",w:5,h:5,icon:n.jsx(oo,{className:"w-3.5 h-3.5"})},{label:"Overview",source:"system:overview",w:5,h:4,icon:n.jsx(io,{className:"w-3.5 h-3.5"})},{label:"Sessions",source:"system:sessions",w:5,h:4,icon:n.jsx(ds,{className:"w-3.5 h-3.5"})},{label:"Watch",source:"system:watch",w:6,h:5,icon:n.jsx(gt,{className:"w-3.5 h-3.5"})},{label:"Backup",source:"system:backup",w:5,h:5,icon:n.jsx(ro,{className:"w-3.5 h-3.5"})},{label:"Training",source:"system:training",w:5,h:5,icon:n.jsx(mt,{className:"w-3.5 h-3.5"})},{label:"Recipes",source:"system:recipes",w:5,h:5,icon:n.jsx(us,{className:"w-3.5 h-3.5"})},{label:"VRAM",source:"system:vram",w:5,h:5,icon:n.jsx(wr,{className:"w-3.5 h-3.5"})},{label:"Teams",source:"system:teams",w:5,h:5,icon:n.jsx(_r,{className:"w-3.5 h-3.5"})},{label:"Cron",source:"system:cron",w:5,h:5,icon:n.jsx(ds,{className:"w-3.5 h-3.5"})},{label:"Checkpoints",source:"system:checkpoints",w:5,h:5,icon:n.jsx(fn,{className:"w-3.5 h-3.5"})},{label:"Organism",source:"system:organism",w:5,h:5,icon:n.jsx(vr,{className:"w-3.5 h-3.5"})},{label:"Fleet",source:"system:fleet",w:5,h:5,icon:n.jsx(co,{className:"w-3.5 h-3.5"})},{label:"Browser",source:"system:browser",w:5,h:5,icon:n.jsx(qi,{className:"w-3.5 h-3.5"})},{label:"Paperclip",source:"system:paperclip",w:5,h:5,icon:n.jsx(lo,{className:"w-3.5 h-3.5"})},{label:"Eval",source:"system:eval",w:5,h:5,icon:n.jsx(uo,{className:"w-3.5 h-3.5"})}];function Fm(){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:Bm.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 $m extends ie.Component{componentDidCatch(e){this.props.onError(e.message)}render(){return this.props.children}}function zm({name:t,children:e}){const[s,r]=ie.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($m,{onError:r,children:e})}const Hm=ie.lazy(()=>ae(()=>import("./legacy-BVPeht6t.js"),__vite__mapDeps([95,1,2])).then(t=>({default:t.Responsive}))),Vm={"system:nav":tl,"system:chat":il,"system:cmd":dl,"system:soma":ul,"system:command-post":Fp,"system:intelligence":zp,"system:memory-graph":Vp,"system:voice":Gp,"system:infra":Yp,"system:tools":Jp,"system:settings":Qp,"system:files":Zp,"system:settings-general":tg,"system:settings-security":ng,"system:settings-audit":ig,"system:settings-specialists":ag,"system:settings-privacy":cg,"system:intelligence-autopilot":ug,"system:intelligence-workflows":fg,"system:intelligence-learning":gg,"system:intelligence-self-improve":yg,"system:intelligence-personas":xg,"system:intelligence-persona-profiles":vg,"system:intelligence-dream":kg,"system:infra-homelab":jg,"system:infra-gpu":Ng,"system:infra-files":Tg,"system:infra-logs":Ag,"system:infra-telemetry":Lg,"system:tools-skills":Mg,"system:tools-mcp":Pg,"system:tools-integrations":Ug,"system:tools-channels":Fg,"system:tools-mesh":zg,"system:agents":Pm,"system:health":Wm,"system:stats":Um,"system:quick-links":Fm,"system:memory-wiki":Vg,"system:autoresearch":qg,"system:self-proposals":Kg,"system:overview":Xg,"system:sessions":Zg,"system:watch":tm,"system:backup":nm,"system:training":im,"system:recipes":am,"system:vram":cm,"system:teams":um,"system:cron":fm,"system:checkpoints":gm,"system:organism":ym,"system:fleet":xm,"system:browser":vm,"system:eval":km,"system:time-travel":Em,"system:mission-driver":Tm,"system:daily-digest":Dm,"system:mission-graph":Om},Gm={lg:12,md:10,sm:6,xs:4,xxs:2},qm=60,Ym={lg:1200,md:996,sm:768,xs:480,xxs:0},Km=[12,12],Jm=["se","sw","ne","nw","e","w","n","s"],hl=ie.forwardRef(({widget:t,space:e,onRemove:s,style:r,className:i,onMouseDown:o,onMouseUp:c,onTouchStart:l,onTouchEnd:d,children:p},m)=>{const u=w.useCallback(()=>s(t.id),[t.id,s]);return n.jsxs("div",{ref:m,style:r,className:i,onMouseDown:o,onMouseUp:c,onTouchStart:l,onTouchEnd:d,children:[n.jsx(Zm,{widget:t,space:e,onRemove:u}),p]})});hl.displayName="MemoWidgetItem";const Xm=ie.memo(hl);function Qm({widget:t,space:e,onRemove:s}){const r=w.useRef(null),i=w.useRef(null),o=w.useRef(e),[c,l]=w.useState(null),[d,p]=w.useState(!0);if(w.useEffect(()=>{o.current=e},[e]),w.useEffect(()=>{if(t.format==="system"||!r.current)return;if(!t.source||t.source.trim()===""){l("Empty widget — no source code"),p(!1);return}p(!0),l(null),i.current=new el(r.current,{onLog:u=>console.log(`[Widget ${t.id}]`,u)}),i.current.setMessageHandler(u=>{var x,b,j,A;const f=o.current;if(u.type==="canvas"&&((x=u.payload)==null?void 0:x.action)==="createWidget"){const v=u.payload.def;if(!v)return{ok:!1,error:"createWidget requires a `def` object"};const I=Number.isFinite(v.w)?v.w:4,g=Number.isFinite(v.h)?v.h:4,k=Number.isFinite(v.x)&&Number.isFinite(v.y)?{x:v.x,y:v.y}:zs(f.widgets||[],I,g);try{const _=_e.addWidget(f.id,{name:v.name||"Agent Widget",format:v.format||"react",source:v.source||"",x:k.x,y:k.y,w:I,h:g});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0,widgetId:_.id}}catch(_){return{ok:!1,error:_.message}}}if(u.type==="canvas"&&((b=u.payload)==null?void 0:b.action)==="updateWidget"){const{id:v,patch:I}=u.payload;return v?(_e.updateWidget(f.id,v,I||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0,id:v}):{ok:!1,error:"updateWidget requires an `id`"}}if(u.type==="canvas"&&((j=u.payload)==null?void 0:j.action)==="listWidgets")return{ok:!0,widgets:f.widgets||[]};if(u.type==="canvas"&&((A=u.payload)==null?void 0:A.action)==="removeWidget"){const v=u.payload.id;return v?(_e.removeWidget(f.id,v),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}});const m=setTimeout(()=>{p(!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(m),p(!1)}).catch(u=>{clearTimeout(m),p(!1),l(String(u))}),()=>{var u;clearTimeout(m),(u=i.current)==null||u.destroy()}},[t.format,t.source,t.id]),t.format==="system"){const m=Vm[t.source];return m?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 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:"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(zm,{name:t.name,children:n.jsx(m,{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 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:"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:m=>{m.stopPropagation(),window.dispatchEvent(new CustomEvent("titan:widget:edit",{detail:{spaceId:e.id,widgetId:t.id}}))},onMouseDown:m=>m.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:c?n.jsx("div",{className:"p-3 text-xs text-red-400 font-mono whitespace-pre-wrap",children:c}):n.jsxs(n.Fragment,{children:[n.jsx("iframe",{ref:r,className:"w-full h-full border-0",sandbox:"allow-scripts",title:t.name}),d&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-xs font-serif",style:{background:"rgba(253,246,227,0.85)",color:"var(--color-desk-text-muted)"},children:n.jsx("span",{className:"animate-pulse",children:"Loading widget…"})})]})})]})}const Zm=ie.memo(Qm);function ey({children:t,position:e}){const s={"bottom-left":"left-4 bottom-4","bottom-right":"right-4 bottom-4","top-left":"left-4 top-4","top-right":"right-4 top-4"}[e];return n.jsx("div",{className:`fixed ${s} z-50`,children:t})}function ty(){const{spaceId:t}=jl(),e=Gi(),[s,r]=w.useState(null),[i]=w.useState(!0),[o,c]=w.useState(!1),[l,d]=w.useState(null),[p,m]=w.useState(!1),[u,f]=w.useState(!1),[x,b]=w.useState(!1),[j,A]=w.useState(1200),v=w.useRef(null),I=w.useRef(null),{info:g,triggerUpdate:k}=Ef(),[_,T]=w.useState(!1);w.useEffect(()=>{const W=t||"home",V=_e.get(W);V?r(V):e("/space/home",{replace:!0})},[t,e]),w.useEffect(()=>{const W=()=>{const ee=I.current;if(!ee)return null;const ne=new ResizeObserver(X=>{for(const Z of X)A(Z.contentRect.width)});return ne.observe(ee),A(ee.getBoundingClientRect().width||1200),ne};let V=W();const $=setInterval(()=>{V||(V=W()),V&&clearInterval($)},200);return()=>{V==null||V.disconnect(),clearInterval($)}},[s==null?void 0:s.id]),w.useEffect(()=>{const W=V=>{(V.metaKey||V.ctrlKey)&&V.key==="k"&&(V.preventDefault(),f($=>!$)),(V.metaKey||V.ctrlKey)&&V.key==="j"&&(V.preventDefault(),window.dispatchEvent(new CustomEvent("titan:chat:toggle")))};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[]),Nf([{key:"?",action:()=>b(!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 E=w.useCallback(()=>{},[]),C=w.useRef(null),M=w.useRef(null),S=w.useCallback(W=>{s&&(M.current=W,C.current&&clearTimeout(C.current),C.current=setTimeout(()=>{const V=M.current;!V||!s||(_e.updateLayout(s.id,V.map($=>({i:$.i,x:$.x,y:$.y,w:$.w,h:$.h}))),M.current=null,C.current=null)},50))},[s]),R=w.useCallback(W=>{var ee;if(!s)return;const V=(ee=s.widgets)==null?void 0:ee.find(ne=>ne.id===W);An("canvas_panel_removed",{widgetId:W,format:V==null?void 0:V.format,source:V==null?void 0:V.source}),_e.removeWidget(s.id,W);const $=Array.isArray(s.widgets)?s.widgets:[];r({...s,widgets:$.filter(ne=>ne.id!==W)})},[s]),O=w.useCallback(W=>{if(!s)return;const V=_e.addWidget(s.id,W),$=Array.isArray(s.widgets)?s.widgets:[];return r({...s,widgets:[...$,V]}),An(W.format==="system"?"canvas_system_panel_created":"canvas_panel_created",{source:W.source,name:W.name,format:W.format}),V},[s]),B=w.useCallback((W,V)=>{if(!s||!Array.isArray(s.widgets)||s.widgets.length===0)return{x:0,y:0};const $=12,ee=new Set;for(const ne of s.widgets)for(let X=0;X<ne.w;X++)for(let Z=0;Z<ne.h;Z++)ee.add(`${ne.x+X},${ne.y+Z}`);for(let ne=0;ne<200;ne++)for(let X=0;X<=$-W;X++){let Z=!0;for(let J=0;J<W;J++){for(let we=0;we<V;we++)if(ee.has(`${X+J},${ne+we}`)){Z=!1;break}if(!Z)break}if(Z)return{x:X,y:ne}}return{x:0,y:0}},[s]),z=w.useCallback((W,V,$=4,ee=4)=>{const ne=B($,ee);O({name:V,format:"system",source:W,x:ne.x,y:ne.y,w:$,h:ee})},[O,B]);w.useEffect(()=>{const W=V=>{const $=V.detail;if(console.log("[TitanCanvas] titan:space:refresh received:",$),!!s&&($==null?void 0:$.spaceId)===s.id){const ee=_e.get(s.id);ee&&(console.log("[TitanCanvas] Refreshing space, widget count:",ee.widgets.length),r(ee))}};return window.addEventListener("titan:space:refresh",W),()=>window.removeEventListener("titan:space:refresh",W)},[s]),w.useEffect(()=>{const W=V=>{const $=V.detail;if(s&&$!=null&&$.source){const ee=Number.isFinite($.w)?$.w:4,ne=Number.isFinite($.h)?$.h:4,X=typeof $.name=="string"&&$.name.trim()?$.name.trim():String($.source).replace("system:","").replace(/-/g," "),Z=$.format==="react"||$.format==="vanilla"||$.format==="html"||$.format==="system"?$.format:String($.source).startsWith("system:")?"system":"react",J=B(ee,ne);O({name:X,format:Z,source:String($.source),x:J.x,y:J.y,w:ee,h:ne})}};return window.addEventListener("titan:widget:add",W),()=>window.removeEventListener("titan:widget:add",W)},[s,O,B]),w.useEffect(()=>{const W=V=>{const $=V.detail;s&&($==null?void 0:$.spaceId)===s.id&&typeof($==null?void 0:$.widgetId)=="string"&&d($.widgetId)};return window.addEventListener("titan:widget:edit",W),()=>window.removeEventListener("titan:widget:edit",W)},[s]),w.useEffect(()=>s?_e.observe(s.id,V=>{console.log("[TitanCanvas] CRDT observer fired, widgets:",V.length),r($=>$&&{...$,widgets:V})}):void 0,[s==null?void 0:s.id]);const G=w.useMemo(()=>{const W=s==null?void 0:s.widgets;return Array.isArray(W)?W.filter(Boolean):[]},[s]),q=w.useMemo(()=>G.map((W,V)=>({i:W.id,x:Number.isFinite(W.x)?W.x:V%3*4,y:Number.isFinite(W.y)?W.y:Math.floor(V/3)*4,w:Number.isFinite(W.w)?W.w:4,h:Number.isFinite(W.h)?W.h:4,minW:2,minH:2,maxW:12,maxH:40})),[G]);return s?n.jsxs("div",{className:"h-full w-full flex",children:[n.jsx(kp,{}),n.jsxs("div",{ref:v,className:"flex-1 relative overflow-auto",children:[n.jsx("style",{children:`
998
- .titan-canvas-grid .react-grid-item > .react-resizable-handle {
999
- background: none;
1000
- padding: 0;
1001
- opacity: 0.35;
1002
- z-index: 10;
1003
- transition: opacity 120ms ease, background-color 120ms ease;
1004
- }
1005
- .titan-canvas-grid .react-grid-item:hover > .react-resizable-handle { opacity: 0.85; }
1006
- .titan-canvas-grid .react-grid-item > .react-resizable-handle:hover,
1007
- .titan-canvas-grid .react-grid-item > .react-resizable-handle:active { opacity: 1; }
1008
- /* Corner handles: 22x22 with a ring-coloured chevron */
1009
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se,
1010
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw,
1011
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne,
1012
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw {
1013
- width: 22px;
1014
- height: 22px;
1015
- background-image: none;
1016
- transform: none;
1017
- }
1018
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se::after,
1019
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw::after,
1020
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne::after,
1021
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw::after {
1022
- content: "";
1023
- position: absolute;
1024
- width: 12px; height: 12px;
1025
- border: 2px solid var(--color-desk-brass);
1026
- border-radius: 3px;
1027
- }
1028
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se::after { right: 3px; bottom: 3px; border-top: none; border-left: none; }
1029
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw::after { left: 3px; bottom: 3px; border-top: none; border-right: none; }
1030
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne::after { right: 3px; top: 3px; border-bottom: none; border-left: none; }
1031
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw::after { left: 3px; top: 3px; border-bottom: none; border-right: none; }
1032
- /* Edge handles: full-edge strips with a centre grip */
1033
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e,
1034
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w {
1035
- top: 8px; bottom: 8px; height: auto; margin-top: 0;
1036
- width: 8px; background-image: none; transform: none;
1037
- }
1038
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n,
1039
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s {
1040
- left: 8px; right: 8px; width: auto; margin-left: 0;
1041
- height: 8px; background-image: none; transform: none;
1042
- }
1043
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after,
1044
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after,
1045
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after,
1046
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after {
1047
- content: ""; position: absolute; background: var(--color-desk-brass); border-radius: 2px;
1048
- }
1049
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after,
1050
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after {
1051
- top: 50%; transform: translateY(-50%);
1052
- width: 3px; height: 32px;
1053
- }
1054
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after { right: 2px; }
1055
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after { left: 2px; }
1056
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after,
1057
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after {
1058
- left: 50%; transform: translateX(-50%);
1059
- height: 3px; width: 32px;
1060
- }
1061
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after { top: 2px; }
1062
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after { bottom: 2px; }
1063
- /* Allow resizing and dragging freely — placeholder turns accent blue */
1064
- .titan-canvas-grid .react-grid-placeholder {
1065
- background: rgba(99, 102, 241, 0.14) !important;
1066
- border: 1px dashed rgba(99, 102, 241, 0.55) !important;
1067
- border-radius: 12px;
1068
- opacity: 1 !important;
1069
- }
1070
- `}),n.jsx("div",{className:"fixed inset-0 opacity-[0.04] pointer-events-none",style:{backgroundImage:"radial-gradient(circle at 1px 1px, rgba(120,90,50,0.4) 1px, transparent 0)",backgroundSize:"24px 24px"}}),n.jsxs("div",{className:"absolute top-0 left-0 right-0 h-10 flex items-center justify-between px-4 z-40 border-b backdrop-blur-sm",style:{borderColor:"var(--color-desk-border)",background:"var(--color-desk-header-bg)"},children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",style:{color:s.color||"var(--color-desk-accent)"},children:s.name}),n.jsxs("button",{onClick:()=>e("/mission"),className:"group relative inline-flex items-center gap-2 px-3 py-1.5 rounded-full transition-all",title:"Open Mission Chat — a chat-style team-control surface with a real desk view",style:{background:"linear-gradient(120deg, rgba(176,138,58,0.18) 0%, rgba(99,102,241,0.16) 100%)",border:"1px solid rgba(176,138,58,0.45)",boxShadow:"0 0 0 0 rgba(176,138,58,0.4)"},children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",style:{color:"#f5d27a",flexShrink:0},children:[n.jsx("path",{d:"M3 17h18",strokeLinecap:"round"}),n.jsx("path",{d:"M5 17V9a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v8"}),n.jsx("rect",{x:"8",y:"9",width:"6",height:"6",rx:"0.5",fill:"rgba(247,245,238,0.85)",stroke:"rgba(40,30,15,0.6)",strokeWidth:"0.8"}),n.jsx("rect",{x:"13",y:"10.5",width:"4",height:"4",rx:"0.3",fill:"rgba(255,242,168,0.95)",stroke:"rgba(120,90,30,0.5)",strokeWidth:"0.7"}),n.jsx("path",{d:"M7 17v3M17 17v3",strokeLinecap:"round"})]}),n.jsx("span",{className:"text-[11px] font-semibold tracking-tight text-[#f5d27a] group-hover:text-white",children:"Mission Chat"}),n.jsx("span",{className:"text-[8px] font-bold uppercase tracking-widest text-bg-deep px-1.5 py-[1px] rounded-full",style:{background:"linear-gradient(180deg, #ffd86e 0%, #b07a1a 100%)",boxShadow:"0 1px 2px rgba(0,0,0,0.4)",animation:"missionPulse 2.4s ease-in-out infinite"},children:"NEW"}),n.jsx("style",{children:"@keyframes missionPulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.7; transform: scale(1.06); } }"})]}),n.jsxs("button",{onClick:()=>c(!0),className:"flex items-center gap-1.5 text-[10px] text-[#52525b] hover:text-[#a5b4fc] truncate max-w-md transition-colors",title:"Edit agent instructions for this space",children:[n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:n.jsx("path",{d:"m18 2 4 4-14 14H4v-4L18 2z"})}),s.agentInstructions?n.jsx("span",{className:"truncate",children:s.agentInstructions}):n.jsx("span",{className:"italic",children:"add agent instructions"})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"text-[10px]",style:{color:"var(--color-desk-text-muted)"},children:[G.length," panel",G.length!==1?"s":""]}),n.jsx("button",{onClick:()=>z("system:nav","Nav",3,4),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Navigation",children:"Nav"}),n.jsx("button",{onClick:()=>z("system:agents","Agents",3,4),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Agents",children:"Agents"}),n.jsx("button",{onClick:()=>z("system:health","Health",3,3),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Health",children:"Health"}),n.jsx("button",{onClick:()=>z("system:stats","Stats",3,4),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Stats",children:"Stats"}),n.jsx("button",{onClick:()=>z("system:quick-links","Quick Links",3,4),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Quick Links",children:"Links"}),n.jsx("button",{onClick:()=>z("system:chat","Chat",4,5),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Chat",children:"Chat"}),G.length>0&&n.jsx("button",{onClick:async()=>{An("canvas_clear_all",{panelCount:G.length}),s&&(await _e.clearSpace(s.id),r({...s,widgets:[]}))},className:"text-[10px] px-2 py-1 rounded-md bg-[#ef4444]/5 border border-[#ef4444]/10 text-[#ef4444]/70 hover:bg-[#ef4444]/10 transition-colors",children:"Clear"}),n.jsx("button",{disabled:_,className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${g!=null&&g.isNewer?"bg-[#f59e0b]/10 border-[#f59e0b]/30 text-[#f59e0b] hover:bg-[#f59e0b]/20 cursor-pointer":"border text-[#6b5a45]"}`,style:g!=null&&g.isNewer?void 0:{background:"rgba(253,246,227,0.7)",borderColor:"var(--color-desk-border)"},title:g!=null&&g.isNewer?`Update available: ${g.current} → ${g.latest}`:`TITAN ${(g==null?void 0:g.current)||""}`,onClick:async()=>{if(!(g!=null&&g.isNewer)||_||!confirm(`Update TITAN from ${g.current} → ${g.latest}?
1071
-
1072
- Your data in ~/.titan/ will be preserved. The gateway will restart after the update.`))return;T(!0);const W=await k(!0);T(!1),W.ok?alert("Update initiated. The gateway will restart shortly. Please refresh the page in 10-15 seconds."):alert(`Update failed: ${W.error||"Unknown error"}`)},children:_?"…":g!=null&&g.isNewer?`↑ ${g.latest}`:`v${(g==null?void 0:g.current)||""}`}),n.jsxs("button",{onClick:()=>m(!0),className:"text-[10px] px-2 py-1 rounded-md transition-colors flex items-center gap-1.5",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-accent)"},title:"Widget gallery",children:[n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 3l1.9 5.8L20 10l-5 3.6 1.5 6L12 16l-4.5 3.6L9 13.6 4 10l6.1-1.2L12 3z"})}),"Gallery"]}),n.jsx("button",{onClick:()=>f(!0),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},children:"⌘K"}),n.jsx("button",{onClick:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle")),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"rgba(253,246,227,0.7)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},children:"⌘J"})]})]}),n.jsx("div",{ref:I,className:"relative pt-10 min-h-[5000px]",children:G.length===0?n.jsx(sy,{space:s,onAddWidget:z,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(Hm,{className:"layout titan-canvas-grid",width:j,layouts:{lg:q},breakpoints:Ym,cols:Gm,rowHeight:qm,margin:Km,containerPadding:[12,12],isDraggable:!0,isResizable:!0,draggableHandle:".panel-drag-handle",resizeHandles:Jm,compactType:null,preventCollision:!1,allowOverlap:!0,useCSSTransforms:!0,onLayoutChange:E,onDragStop:W=>{S(W)},onResizeStop:W=>{S(W)},children:G.map(W=>n.jsx(Xm,{widget:W,space:s,onRemove:R},W.id))})})}),n.jsx(ey,{position:"bottom-left",children:n.jsx(tl,{currentSpaceId:s.id,onSpaceSelect:W=>e(`/space/${W}`)})}),n.jsx(bp,{space:s,defaultExpanded:i}),n.jsx(vp,{}),n.jsx(Ep,{space:s,open:o,onClose:()=>c(!1),onSaved:W=>{r(V=>V&&{...V,agentInstructions:W||void 0})}}),l&&(()=>{const W=G.find(V=>V.id===l);return!W||W.format==="system"?(d(null),null):n.jsx(Tp,{widget:W,spaceId:s.id,open:!0,onClose:()=>d(null),onSaved:V=>{const $=G.map(ee=>ee.id===V.id?{...ee,...V}:ee);r(ee=>ee&&{...ee,widgets:$})}})})(),n.jsx(Dp,{open:p,onClose:()=>m(!1)}),n.jsx(Up,{}),u&&n.jsx(dl,{currentSpaceId:s.id,onSpaceSelect:W=>{e(`/space/${W}`),f(!1)},onAction:W=>{W.type==="widget"&&z(W.source,W.name,W.w,W.h),f(!1)},onClose:()=>f(!1)}),n.jsx(Tf,{open:x,onClose:()=>b(!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 font-serif text-sm",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)"},children:"Loading space..."})})}function sy({space:t,onAddWidget:e,onOpenChat:s}){const r=[{label:"SOMA",source:"system:soma",w:6,h:6},{label:"Command Post",source:"system:command-post",w:8,h:6},{label:"Intelligence",source:"system:intelligence",w:6,h:5},{label:"Memory Graph",source:"system:memory-graph",w:8,h:7},{label:"Voice",source:"system:voice",w:5,h:5},{label:"Files",source:"system:files",w:4,h:6},{label:"Infra",source:"system:infra",w:6,h:4},{label:"Tools",source:"system:tools",w:5,h:4},{label:"Daemon",source:"system:daemon",w:6,h:6},{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:"Overview",source:"system:overview",w:6,h:5},{label:"Sessions",source:"system:sessions",w:6,h:5},{label:"Watch",source:"system:watch",w:8,h:7},{label:"Backup",source:"system:backup",w:6,h:6},{label:"Training",source:"system:training",w:6,h:6},{label:"Recipes",source:"system:recipes",w:6,h:6},{label:"VRAM",source:"system:vram",w:6,h:6},{label:"Teams",source:"system:teams",w:6,h:6},{label:"Cron",source:"system:cron",w:6,h:6},{label:"Checkpoints",source:"system:checkpoints",w:6,h:5},{label:"Organism",source:"system:organism",w:6,h:6},{label:"Fleet",source:"system:fleet",w:6,h:5},{label:"Browser",source:"system:browser",w:6,h:5},{label:"Eval",source:"system:eval",w:6,h:6},{label:"Time Travel",source:"system:time-travel",w:8,h:6},{label:"Mission Driver",source:"system:mission-driver",w:7,h:7},{label:"Daily Digest",source:"system:daily-digest",w:5,h:7},{label:"Mission Graph",source:"system:mission-graph",w:8,h:7}];return n.jsx("div",{className:"h-full flex items-center justify-center",children:n.jsxs("div",{className:"text-center max-w-lg rounded-2xl px-8 py-10 border",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",boxShadow:"0 4px 16px rgba(60,40,15,0.12)"},children:[n.jsx("div",{className:"w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-5",style:{background:"rgba(176,138,58,0.12)",border:"1px solid rgba(176,138,58,0.25)"},children:n.jsx("svg",{className:"w-7 h-7",style:{color:"var(--color-desk-brass)"},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(--color-desk-text)"},children:t.name}),n.jsx("p",{className:"text-sm mb-6",style:{color:"var(--color-desk-text-secondary)"},children:"This space is empty. Ask the agent to create widgets, or add system widgets below."}),n.jsx("div",{className:"flex gap-2 justify-center mb-6 flex-wrap",children:n.jsx("button",{onClick:s,className:"px-4 py-2 rounded-xl text-sm font-medium transition-all",style:{background:"rgba(176,138,58,0.15)",border:"1px solid rgba(176,138,58,0.25)",color:"var(--color-desk-accent)"},children:"Ask Agent"})}),n.jsx("div",{className:"flex gap-2 justify-center flex-wrap",children:r.map(i=>n.jsxs("button",{onClick:()=>e(i.source,i.label,i.w,i.h),className:"px-3 py-1.5 rounded-lg text-[11px] transition-all",style:{background:"rgba(58,37,24,0.06)",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},children:["+ ",i.label]},i.source))})]})})}const ky=Object.freeze(Object.defineProperty({__proto__:null,default:ty},Symbol.toStringTag,{value:"Module"}));export{ro as A,us as B,Ul as D,io as E,oo as G,Kl as H,ai as P,co as R,jr as S,uo as T,rc as W,mt as a,Sr as b,ky as c};