titan-agent 6.5.3 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (311) hide show
  1. package/README.md +179 -47
  2. package/assets/agent-skills/NOTICE-ECC.md +39 -0
  3. package/assets/agent-skills/agent-introspection-debugging/SKILL.md +153 -0
  4. package/assets/agent-skills/continuous-agent-loop/SKILL.md +45 -0
  5. package/assets/agent-skills/continuous-learning/SKILL.md +131 -0
  6. package/assets/agent-skills/continuous-learning/config.json +18 -0
  7. package/assets/agent-skills/continuous-learning/evaluate-session.sh +69 -0
  8. package/assets/agent-skills/production-audit/SKILL.md +206 -0
  9. package/assets/agent-skills/recursive-decision-ledger/SKILL.md +79 -0
  10. package/assets/agent-skills/scientific-thinking-literature-review/SKILL.md +192 -0
  11. package/assets/agent-skills/scientific-thinking-scholar-evaluation/SKILL.md +160 -0
  12. package/assets/agent-skills/verification-loop/SKILL.md +126 -0
  13. package/dist/agent/agent.js +67 -26
  14. package/dist/agent/agent.js.map +1 -1
  15. package/dist/agent/agentLoop.js +6 -2
  16. package/dist/agent/agentLoop.js.map +1 -1
  17. package/dist/agent/autoModeClassifier.js +26 -2
  18. package/dist/agent/autoModeClassifier.js.map +1 -1
  19. package/dist/agent/goalDriver.js +2 -0
  20. package/dist/agent/goalDriver.js.map +1 -1
  21. package/dist/agent/goalSpec.js +229 -0
  22. package/dist/agent/goalSpec.js.map +1 -0
  23. package/dist/agent/heartbeat.js +130 -0
  24. package/dist/agent/heartbeat.js.map +1 -0
  25. package/dist/agent/missionDecompose.js +38 -0
  26. package/dist/agent/missionDecompose.js.map +1 -0
  27. package/dist/agent/muscleMemory.js +291 -0
  28. package/dist/agent/muscleMemory.js.map +1 -0
  29. package/dist/agent/observationWriter.js +56 -0
  30. package/dist/agent/observationWriter.js.map +1 -0
  31. package/dist/agent/promptSectionCaps.js +6 -0
  32. package/dist/agent/promptSectionCaps.js.map +1 -1
  33. package/dist/agent/reminders.js +101 -0
  34. package/dist/agent/reminders.js.map +1 -0
  35. package/dist/agent/systemWidgets.js +41 -0
  36. package/dist/agent/systemWidgets.js.map +1 -0
  37. package/dist/agent/toolRunner.js +24 -0
  38. package/dist/agent/toolRunner.js.map +1 -1
  39. package/dist/agent/toolSearch.js +3 -0
  40. package/dist/agent/toolSearch.js.map +1 -1
  41. package/dist/channels/messenger.js +39 -0
  42. package/dist/channels/messenger.js.map +1 -1
  43. package/dist/config/config.js +7 -0
  44. package/dist/config/config.js.map +1 -1
  45. package/dist/config/schema.js +18 -1
  46. package/dist/config/schema.js.map +1 -1
  47. package/dist/eval/harness.js +13 -3
  48. package/dist/eval/harness.js.map +1 -1
  49. package/dist/gateway/onboarding.js +91 -0
  50. package/dist/gateway/onboarding.js.map +1 -0
  51. package/dist/gateway/routes/skills.js +2 -1
  52. package/dist/gateway/routes/skills.js.map +1 -1
  53. package/dist/gateway/routes/studioRouter.js +88 -0
  54. package/dist/gateway/routes/studioRouter.js.map +1 -0
  55. package/dist/gateway/routes/watchRouter.js +4 -4
  56. package/dist/gateway/routes/watchRouter.js.map +1 -1
  57. package/dist/gateway/server.js +251 -43
  58. package/dist/gateway/server.js.map +1 -1
  59. package/dist/memory/taxonomy.js +117 -0
  60. package/dist/memory/taxonomy.js.map +1 -0
  61. package/dist/providers/modelCapabilities.js +13 -0
  62. package/dist/providers/modelCapabilities.js.map +1 -1
  63. package/dist/providers/ollama.js +8 -2
  64. package/dist/providers/ollama.js.map +1 -1
  65. package/dist/providers/openai.js +1 -1
  66. package/dist/providers/openai.js.map +1 -1
  67. package/dist/providers/openai_compat.js +38 -2
  68. package/dist/providers/openai_compat.js.map +1 -1
  69. package/dist/providers/router.js +14 -0
  70. package/dist/providers/router.js.map +1 -1
  71. package/dist/recipes/runner.js +8 -1
  72. package/dist/recipes/runner.js.map +1 -1
  73. package/dist/recipes/store.js +2 -1
  74. package/dist/recipes/store.js.map +1 -1
  75. package/dist/skills/builtin/codebase_explore.js +214 -0
  76. package/dist/skills/builtin/codebase_explore.js.map +1 -0
  77. package/dist/skills/builtin/config_audit.js +160 -0
  78. package/dist/skills/builtin/config_audit.js.map +1 -0
  79. package/dist/skills/builtin/delegate_agent.js +107 -0
  80. package/dist/skills/builtin/delegate_agent.js.map +1 -0
  81. package/dist/skills/builtin/memory_map.js +38 -0
  82. package/dist/skills/builtin/memory_map.js.map +1 -0
  83. package/dist/skills/builtin/reminders.js +67 -0
  84. package/dist/skills/builtin/reminders.js.map +1 -0
  85. package/dist/skills/builtin/spec.js +139 -0
  86. package/dist/skills/builtin/spec.js.map +1 -0
  87. package/dist/skills/builtin/widget_gallery.js +12 -5
  88. package/dist/skills/builtin/widget_gallery.js.map +1 -1
  89. package/dist/skills/frontmatterLoader.js +7 -1
  90. package/dist/skills/frontmatterLoader.js.map +1 -1
  91. package/dist/skills/registry.js +12 -0
  92. package/dist/skills/registry.js.map +1 -1
  93. package/dist/substrate/traceBus.js.map +1 -1
  94. package/dist/telemetry/traceStore.js +127 -0
  95. package/dist/telemetry/traceStore.js.map +1 -0
  96. package/dist/utils/constants.js +1 -1
  97. package/dist/utils/constants.js.map +1 -1
  98. package/dist/utils/contrast.js +69 -0
  99. package/dist/utils/contrast.js.map +1 -0
  100. package/dist/watch/sessionContext.js +14 -0
  101. package/dist/watch/sessionContext.js.map +1 -0
  102. package/dist/watch/sessionTrace.js +51 -0
  103. package/dist/watch/sessionTrace.js.map +1 -0
  104. package/dist/watch/studioBuffer.js +53 -0
  105. package/dist/watch/studioBuffer.js.map +1 -0
  106. package/package.json +4 -3
  107. package/ui/dist/assets/AboutYouMemory-CZKEOd_O.js +11 -0
  108. package/ui/dist/assets/AuditPanel-Bu71N5Er.js +1 -0
  109. package/ui/dist/assets/{AutonomyPanel-CmaXJV8d.js → AutonomyPanel-DB-39dX4.js} +2 -2
  110. package/ui/dist/assets/{AutopilotPanel-CbohPtXW.js → AutopilotPanel-Cj8oKxWv.js} +1 -1
  111. package/ui/dist/assets/{AutoresearchPanel-DCwiQ2v2.js → AutoresearchPanel-3s8pjm6Z.js} +2 -2
  112. package/ui/dist/assets/BackupPanel-EUQJMJE7.js +1 -0
  113. package/ui/dist/assets/{BrowserPanel-D6UaSxap.js → BrowserPanel-Beo4F5Ar.js} +2 -2
  114. package/ui/dist/assets/Button-MdXmb4_n.js +1 -0
  115. package/ui/dist/assets/CPActivity-B1Se9VVc.js +1 -0
  116. package/ui/dist/assets/CPAgentDetail-BYji6tT8.js +1 -0
  117. package/ui/dist/assets/CPAgents-BSUKucTe.js +1 -0
  118. package/ui/dist/assets/CPApprovals-B4v0em6e.js +1 -0
  119. package/ui/dist/assets/CPCosts-9ikh61Kv.js +1 -0
  120. package/ui/dist/assets/CPDashboard-sOok2T5v.js +1 -0
  121. package/ui/dist/assets/{CPFiles-BO73EZwJ.js → CPFiles-DB2nY5JE.js} +1 -1
  122. package/ui/dist/assets/CPGoals-8Z1yOY8e.js +1 -0
  123. package/ui/dist/assets/CPInbox-Cq6-UY8F.js +11 -0
  124. package/ui/dist/assets/CPIssueDetail-NAGfmJg8.js +1 -0
  125. package/ui/dist/assets/CPIssues-BzX6Rckx.js +1 -0
  126. package/ui/dist/assets/CPLayout-BcRM6QSg.js +2 -0
  127. package/ui/dist/assets/CPOrg-B7DQ4UQP.js +1 -0
  128. package/ui/dist/assets/CPRuns-D-cpPw_M.js +1 -0
  129. package/ui/dist/assets/{CPSocial-Qw5rKy_4.js → CPSocial-DshtmcK0.js} +3 -3
  130. package/ui/dist/assets/CPVoice-DfXRnQVU.js +1 -0
  131. package/ui/dist/assets/{ChannelsPanel-DS21E-Iz.js → ChannelsPanel-BnaTOeyf.js} +1 -1
  132. package/ui/dist/assets/CheckpointsPanel-C62naE4U.js +1 -0
  133. package/ui/dist/assets/CommandPostHub-B_L1CAss.js +24 -0
  134. package/ui/dist/assets/ConfirmDialog-VErHWAbo.js +1 -0
  135. package/ui/dist/assets/CronPanel-BwMrrZ5d.js +1 -0
  136. package/ui/dist/assets/{DataTable-PnhPeDBG.js → DataTable-BCqSUuN7.js} +1 -1
  137. package/ui/dist/assets/{DreamPanel-DIrtlk2K.js → DreamPanel-BNAcCLBB.js} +2 -2
  138. package/ui/dist/assets/EmptyState-D9kQf1PX.js +1 -0
  139. package/ui/dist/assets/{EvalHarnessPanel-uYb_ZEQG.js → EvalHarnessPanel-BaMLdBNm.js} +2 -2
  140. package/ui/dist/assets/EvalPanel-CW-SSjtg.js +1 -0
  141. package/ui/dist/assets/{FileViewer-CVO3TRs3.js → FileViewer-BL00nsd7.js} +1 -1
  142. package/ui/dist/assets/FilesPanel-CeC6YUSd.js +16 -0
  143. package/ui/dist/assets/FleetPanel-EyWF7l3W.js +1 -0
  144. package/ui/dist/assets/{HomelabPanel-BZvN4LPM.js → HomelabPanel-BRfKRYe7.js} +2 -2
  145. package/ui/dist/assets/InfraView-Jmqhg_Yc.js +2 -0
  146. package/ui/dist/assets/{InlineEditableField-mBzpbcLB.js → InlineEditableField-DgMrLDj1.js} +1 -1
  147. package/ui/dist/assets/Input-CBTwa_Iw.js +1 -0
  148. package/ui/dist/assets/IntegrationsPanel-DQL-7Ec6.js +1 -0
  149. package/ui/dist/assets/IntelligenceView-DxD78qfP.js +2 -0
  150. package/ui/dist/assets/LearningPanel-C_JzSbJU.js +1 -0
  151. package/ui/dist/assets/LiveStudio-Db5yeaWo.js +7 -0
  152. package/ui/dist/assets/{LogsPanel-DbP3Mwnr.js → LogsPanel-CpinKwaZ.js} +1 -1
  153. package/ui/dist/assets/McpPanel-D-MqN_f-.js +1 -0
  154. package/ui/dist/assets/MemoryGraphPanel-BnD5jRqf.js +1 -0
  155. package/ui/dist/assets/MemoryTaxonomyPanel-BBI202dd.js +6 -0
  156. package/ui/dist/assets/MemoryWikiPanel-Dn3XZHL0.js +6 -0
  157. package/ui/dist/assets/{MeshPanel-Bf-4brXL.js → MeshPanel-C-mRJpr0.js} +1 -1
  158. package/ui/dist/assets/{MissionCanvas-CJyhnauG.js → MissionCanvas-CbZW83Ch.js} +1 -1
  159. package/ui/dist/assets/{MissionChat-C2Nto3zM.js → MissionChat-Bs75jPAD.js} +1 -1
  160. package/ui/dist/assets/{MissionLibrary-RXyBHsLL.js → MissionLibrary-BxQ6SxPe.js} +1 -1
  161. package/ui/dist/assets/MissionStart-CBuBPasl.js +1 -0
  162. package/ui/dist/assets/Modal-ybPGvlQs.js +9 -0
  163. package/ui/dist/assets/{NvidiaPanel-4DlcQlyl.js → NvidiaPanel-DdG13OX4.js} +1 -1
  164. package/ui/dist/assets/OrganismPanel-xZWUJKyr.js +1 -0
  165. package/ui/dist/assets/OverviewPanel-B45ZYhJV.js +1 -0
  166. package/ui/dist/assets/{PageHeader-bnc85wQN.js → PageHeader-DdrbS1aq.js} +1 -1
  167. package/ui/dist/assets/PersonaProfilesPanel-CKER-EU5.js +8 -0
  168. package/ui/dist/assets/{PersonasPanel-dR8VppcD.js → PersonasPanel-CMMQ3nh3.js} +1 -1
  169. package/ui/dist/assets/{PhoneDeskPanel-CdVOY7H9.js → PhoneDeskPanel-Bw_Y-cVE.js} +2 -2
  170. package/ui/dist/assets/RecipesPanel-DzMcxpJJ.js +1 -0
  171. package/ui/dist/assets/SecurityPanel-BCq3Fzbr.js +1 -0
  172. package/ui/dist/assets/SelfImprovePanel-YE3hT8jK.js +1 -0
  173. package/ui/dist/assets/SelfProposalsPanel-DXuqBM6p.js +1 -0
  174. package/ui/dist/assets/SessionsPanel-DORz5goR.js +1 -0
  175. package/ui/dist/assets/SessionsTab-qYHDOuC8.js +1 -0
  176. package/ui/dist/assets/SettingsPanel-BbwPu1i7.js +1 -0
  177. package/ui/dist/assets/SettingsView-zgqkDDBJ.js +2 -0
  178. package/ui/dist/assets/{SkeletonLoader-Cax7YTqW.js → SkeletonLoader-r6OGXaU9.js} +1 -1
  179. package/ui/dist/assets/SkillsPanel-BjEOBMRo.js +11 -0
  180. package/ui/dist/assets/{SomaView-eG3wI4S1.js → SomaView-DLzApZVW.js} +2 -2
  181. package/ui/dist/assets/{StatCard-Djr487DV.js → StatCard-DLq8aBps.js} +1 -1
  182. package/ui/dist/assets/{StatusBadge-JpCoA33_.js → StatusBadge-BqlvIbdj.js} +1 -1
  183. package/ui/dist/assets/{Tabs-DJHu-roP.js → Tabs-DdUThlp1.js} +1 -1
  184. package/ui/dist/assets/TeamsPanel-uIIKoU7I.js +1 -0
  185. package/ui/dist/assets/{TelemetryPanel-D4PXsd-X.js → TelemetryPanel-dVr3yQQr.js} +1 -1
  186. package/ui/dist/assets/TitanCanvas-xHAJqwG2.js +945 -0
  187. package/ui/dist/assets/ToolsView-CG1mZdiy.js +2 -0
  188. package/ui/dist/assets/{Tooltip-B1LhTXJ8.js → Tooltip-C2tXJcrN.js} +1 -1
  189. package/ui/dist/assets/TraceViewer-BIMD_Osr.js +1 -0
  190. package/ui/dist/assets/TracesPanel-nMUiyMj5.js +1 -0
  191. package/ui/dist/assets/TrainingPanel-CT5R4HWm.js +1 -0
  192. package/ui/dist/assets/{VoiceOverlay-B_ss7Zg_.js → VoiceOverlay-Br4QnCtw.js} +3 -3
  193. package/ui/dist/assets/VramPanel-CdnJYytg.js +1 -0
  194. package/ui/dist/assets/WatchView-TNU6Ns1Q.js +13 -0
  195. package/ui/dist/assets/WorkTab-wTlX_UKP.js +1 -0
  196. package/ui/dist/assets/WorkflowBuilderPanel-CDpVt5ux.js +6 -0
  197. package/ui/dist/assets/WorkflowsPanel-zsFqsLdn.js +11 -0
  198. package/ui/dist/assets/{archive-gZFnGd5A.js → archive-Bh689DNg.js} +1 -1
  199. package/ui/dist/assets/{arrow-left-qA0Qer2h.js → arrow-left-WkVYLm80.js} +1 -1
  200. package/ui/dist/assets/{book-open-DIxdPqmD.js → book-open-ohEXgUsS.js} +1 -1
  201. package/ui/dist/assets/{bot-CvIF1uHi.js → bot-DvEcyQcD.js} +1 -1
  202. package/ui/dist/assets/{chart-column-BQiM-Td4.js → chart-column-w3goFd5f.js} +1 -1
  203. package/ui/dist/assets/{check-DgyDEFtq.js → check-CuRYh4Zh.js} +1 -1
  204. package/ui/dist/assets/{chevron-right-CQ1NTOtd.js → chevron-right-DbLSHmff.js} +1 -1
  205. package/ui/dist/assets/{circle-check-big-CAFcaPPH.js → circle-check-big-Bkba568b.js} +1 -1
  206. package/ui/dist/assets/{circle-stop-C-8xGv0n.js → circle-stop-Bx2ohEg8.js} +1 -1
  207. package/ui/dist/assets/{clipboard-list-9DdqBj1F.js → clipboard-list-Dj9tORnu.js} +1 -1
  208. package/ui/dist/assets/{clock-CF9BCIpL.js → clock-JyQAYy6X.js} +1 -1
  209. package/ui/dist/assets/{dollar-sign-LDRZBae6.js → dollar-sign-XxwPAA2a.js} +1 -1
  210. package/ui/dist/assets/{download-BBNXvBO0.js → download-D1izVEOL.js} +1 -1
  211. package/ui/dist/assets/{external-link-D_ji4Bec.js → external-link-DZ_rZsIt.js} +1 -1
  212. package/ui/dist/assets/{file-text-DrdTDEYp.js → file-text-Cfawu8Bs.js} +1 -1
  213. package/ui/dist/assets/{flask-conical-BGn5PgFX.js → flask-conical-Ql8QxhgY.js} +1 -1
  214. package/ui/dist/assets/{folder-BeZZUGnK.js → folder-DAdIw-Pb.js} +1 -1
  215. package/ui/dist/assets/{funnel-CAJgGO5M.js → funnel-FycfZcXo.js} +1 -1
  216. package/ui/dist/assets/{git-branch-BcXabeOs.js → git-branch-C2qrhGGu.js} +1 -1
  217. package/ui/dist/assets/index-Cml2x9pA.js +507 -0
  218. package/ui/dist/assets/index-yWybhcfI.css +1 -0
  219. package/ui/dist/assets/{layers-DxYDmPA_.js → layers-yzjtGlHB.js} +1 -1
  220. package/ui/dist/assets/{legacy-dHWI7k8P.js → legacy-D21WSMF1.js} +1 -1
  221. package/ui/dist/assets/{lightbulb-B0Du4SM4.js → lightbulb-BZJNK69S.js} +1 -1
  222. package/ui/dist/assets/{link-CUpaumqr.js → link-CnFkBkaY.js} +1 -1
  223. package/ui/dist/assets/{list-todo-CDDhmPQB.js → list-todo-BlgfQHup.js} +1 -1
  224. package/ui/dist/assets/{message-square-D5VWlv-Q.js → message-square-CRsG9u6_.js} +1 -1
  225. package/ui/dist/assets/{mic-Ddcc6Ann.js → mic-B32RHc7Y.js} +1 -1
  226. package/ui/dist/assets/{missions-2zox16Tc.js → missions-1iw8Z2_0.js} +1 -1
  227. package/ui/dist/assets/{network-DaJ7ugwX.js → network-C9RXQGrV.js} +1 -1
  228. package/ui/dist/assets/{pause-BukaK6rs.js → pause-BT1Bc2q3.js} +1 -1
  229. package/ui/dist/assets/{pencil-D_YwQBeg.js → pencil-BK5IU6o0.js} +1 -1
  230. package/ui/dist/assets/{play-BjdwtYMk.js → play-Cl1nC_gc.js} +1 -1
  231. package/ui/dist/assets/{plug-yISDdeW2.js → plug-DvcpOalj.js} +1 -1
  232. package/ui/dist/assets/{plus-BSjTdepW.js → plus-Dpo1qfrl.js} +1 -1
  233. package/ui/dist/assets/{radio-B7kX_yWE.js → radio-C5c9IyqX.js} +1 -1
  234. package/ui/dist/assets/{refresh-cw-CwDpzXUn.js → refresh-cw-C-iZkzuS.js} +1 -1
  235. package/ui/dist/assets/{rotate-ccw-7SQDTI0_.js → rotate-ccw-qzrB3SNw.js} +1 -1
  236. package/ui/dist/assets/{save-CjTPAQM0.js → save-DwR9wQVu.js} +1 -1
  237. package/ui/dist/assets/{search-BP7VlNxX.js → search-D10l0m3-.js} +1 -1
  238. package/ui/dist/assets/{send-C2XDuRPf.js → send-DtXGsaFW.js} +1 -1
  239. package/ui/dist/assets/{server-BE8W-AT4.js → server-BzisF3LL.js} +1 -1
  240. package/ui/dist/assets/settings-Dbwd1_-c.js +6 -0
  241. package/ui/dist/assets/{shield-check-s7la2J2K.js → shield-check-CXlDJyAW.js} +1 -1
  242. package/ui/dist/assets/square-BBC-JKzY.js +11 -0
  243. package/ui/dist/assets/{terminal-B8IK4WsO.js → terminal-DaBIlWEM.js} +1 -1
  244. package/ui/dist/assets/{test-tube-Xfn9DJeg.js → test-tube-CDATRD5t.js} +1 -1
  245. package/ui/dist/assets/{toggle-right-CHpzOIlj.js → toggle-right-DTmrC5RD.js} +1 -1
  246. package/ui/dist/assets/{trash-2-B1C85ePK.js → trash-2-CTeyjxD_.js} +1 -1
  247. package/ui/dist/assets/{trending-up-DDGHQZY1.js → trending-up-CXPRjRV4.js} +1 -1
  248. package/ui/dist/assets/{trophy-D0LhJSPA.js → trophy-DbVdXRtU.js} +1 -1
  249. package/ui/dist/assets/{volume-2-DMaE91b5.js → volume-2-DYDBmm3M.js} +1 -1
  250. package/ui/dist/assets/{wifi-off-DR9h8HGA.js → wifi-off-BBuIGbiP.js} +1 -1
  251. package/ui/dist/assets/zoom-out-D47_pRAO.js +16 -0
  252. package/ui/dist/index.html +2 -2
  253. package/ui/dist/sw.js +1 -1
  254. package/ui/dist/assets/AuditPanel-BaftX5MP.js +0 -1
  255. package/ui/dist/assets/BackupPanel-DAy9G7Wt.js +0 -1
  256. package/ui/dist/assets/CPActivity-BYDsUoMn.js +0 -1
  257. package/ui/dist/assets/CPAgentDetail-Bb9-GAJY.js +0 -1
  258. package/ui/dist/assets/CPAgents-BTZuGnki.js +0 -1
  259. package/ui/dist/assets/CPApprovals-BME2ARkO.js +0 -1
  260. package/ui/dist/assets/CPCosts-mOXwWq0i.js +0 -1
  261. package/ui/dist/assets/CPDashboard-CTlKGXXQ.js +0 -1
  262. package/ui/dist/assets/CPGoals-BNWhNP14.js +0 -1
  263. package/ui/dist/assets/CPInbox-ybe4r8LW.js +0 -16
  264. package/ui/dist/assets/CPIssueDetail-DaMMGbjw.js +0 -1
  265. package/ui/dist/assets/CPIssues-BgpQOISw.js +0 -1
  266. package/ui/dist/assets/CPLayout-bgErauTx.js +0 -2
  267. package/ui/dist/assets/CPOrg-C8l5SIWJ.js +0 -8
  268. package/ui/dist/assets/CPRuns-DB8S7loF.js +0 -1
  269. package/ui/dist/assets/CPVoice-DfwHPewA.js +0 -1
  270. package/ui/dist/assets/CheckpointsPanel-9-l_8GdG.js +0 -1
  271. package/ui/dist/assets/CommandPostHub-z55Yrhj1.js +0 -24
  272. package/ui/dist/assets/CronPanel-kEZK3gpx.js +0 -1
  273. package/ui/dist/assets/EmptyState-CfvU7SdB.js +0 -1
  274. package/ui/dist/assets/EvalPanel-CDG-njyj.js +0 -1
  275. package/ui/dist/assets/FilesPanel-CaLPog2e.js +0 -16
  276. package/ui/dist/assets/FleetPanel-BtlaV6pH.js +0 -1
  277. package/ui/dist/assets/InfraView-C0zEuFrR.js +0 -2
  278. package/ui/dist/assets/Input-CbrMbLgn.js +0 -1
  279. package/ui/dist/assets/IntegrationsPanel-B4TyR6jC.js +0 -1
  280. package/ui/dist/assets/IntelligenceView-DZ4HxYZ3.js +0 -2
  281. package/ui/dist/assets/LearningPanel-B4RIm_iQ.js +0 -1
  282. package/ui/dist/assets/McpPanel-BmNUFozc.js +0 -1
  283. package/ui/dist/assets/MemoryGraphPanel-JPurHV0L.js +0 -16
  284. package/ui/dist/assets/MemoryWikiPanel-DdvCAZHa.js +0 -6
  285. package/ui/dist/assets/MissionStart-wUkcEP0T.js +0 -1
  286. package/ui/dist/assets/Modal-BmS7C6FN.js +0 -1
  287. package/ui/dist/assets/OrganismPanel-C2LYDPrn.js +0 -1
  288. package/ui/dist/assets/OverviewPanel-DK8uuq4D.js +0 -1
  289. package/ui/dist/assets/PersonaProfilesPanel-DGtokXUu.js +0 -8
  290. package/ui/dist/assets/RecipesPanel-D3Zs2wxr.js +0 -1
  291. package/ui/dist/assets/SecurityPanel-BMERf796.js +0 -1
  292. package/ui/dist/assets/SelfImprovePanel-BxqWHXCU.js +0 -1
  293. package/ui/dist/assets/SelfProposalsPanel-CuC94vdx.js +0 -2
  294. package/ui/dist/assets/SessionsPanel-CQ8qvzp7.js +0 -1
  295. package/ui/dist/assets/SessionsTab-B3eHV3jf.js +0 -1
  296. package/ui/dist/assets/SettingsPanel-Cumls7N2.js +0 -1
  297. package/ui/dist/assets/SettingsView-BtA67pol.js +0 -2
  298. package/ui/dist/assets/SkillsPanel-CA415CT8.js +0 -11
  299. package/ui/dist/assets/TeamsPanel-C_Vu6vnY.js +0 -1
  300. package/ui/dist/assets/TitanCanvas-TuYZSZO7.js +0 -1117
  301. package/ui/dist/assets/ToolsView-BvTN6vFn.js +0 -2
  302. package/ui/dist/assets/TraceViewer-Bh8Jo3Dr.js +0 -1
  303. package/ui/dist/assets/TrainingPanel-Dmbd1rJ-.js +0 -1
  304. package/ui/dist/assets/VramPanel-CPICbZ2s.js +0 -1
  305. package/ui/dist/assets/WatchView-BCgLVfiV.js +0 -13
  306. package/ui/dist/assets/WorkTab-iptofXO9.js +0 -1
  307. package/ui/dist/assets/WorkflowsPanel-3RYkFHyf.js +0 -11
  308. package/ui/dist/assets/chevron-up-UyfdjRp6.js +0 -6
  309. package/ui/dist/assets/index-CUgepw5Q.js +0 -337
  310. package/ui/dist/assets/index-Dm6zcSTS.css +0 -1
  311. package/ui/dist/assets/proxy-CWET5FFX.js +0 -9
@@ -1,1117 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SomaView-eG3wI4S1.js","assets/index-CUgepw5Q.js","assets/index-Dm6zcSTS.css","assets/Input-CbrMbLgn.js","assets/clsx-B-dksMZM.js","assets/Tooltip-B1LhTXJ8.js","assets/SomaView-BtCkeWfZ.css","assets/CommandPostHub-z55Yrhj1.js","assets/Modal-BmS7C6FN.js","assets/proxy-CWET5FFX.js","assets/InlineEditableField-mBzpbcLB.js","assets/check-DgyDEFtq.js","assets/pencil-D_YwQBeg.js","assets/approvalHeadline-DB9SgR-9.js","assets/chevron-right-CQ1NTOtd.js","assets/bot-CvIF1uHi.js","assets/pause-BukaK6rs.js","assets/dollar-sign-LDRZBae6.js","assets/git-branch-BcXabeOs.js","assets/chart-column-BQiM-Td4.js","assets/clock-CF9BCIpL.js","assets/message-square-D5VWlv-Q.js","assets/file-text-DrdTDEYp.js","assets/terminal-B8IK4WsO.js","assets/refresh-cw-CwDpzXUn.js","assets/circle-stop-C-8xGv0n.js","assets/send-C2XDuRPf.js","assets/plus-BSjTdepW.js","assets/trash-2-B1C85ePK.js","assets/IntelligenceView-DZ4HxYZ3.js","assets/MemoryGraphPanel-JPurHV0L.js","assets/network-DaJ7ugwX.js","assets/search-BP7VlNxX.js","assets/InfraView-C0zEuFrR.js","assets/ToolsView-BvTN6vFn.js","assets/SettingsView-BtA67pol.js","assets/SettingsPanel-Cumls7N2.js","assets/PageHeader-bnc85wQN.js","assets/circle-check-big-CAFcaPPH.js","assets/mic-Ddcc6Ann.js","assets/wifi-off-DR9h8HGA.js","assets/download-BBNXvBO0.js","assets/play-BjdwtYMk.js","assets/save-CjTPAQM0.js","assets/SecurityPanel-BMERf796.js","assets/AuditPanel-BaftX5MP.js","assets/funnel-CAJgGO5M.js","assets/clipboard-list-9DdqBj1F.js","assets/AutopilotPanel-CbohPtXW.js","assets/WorkflowsPanel-3RYkFHyf.js","assets/toggle-right-CHpzOIlj.js","assets/book-open-DIxdPqmD.js","assets/LearningPanel-B4RIm_iQ.js","assets/lightbulb-B0Du4SM4.js","assets/trending-up-DDGHQZY1.js","assets/chevron-up-UyfdjRp6.js","assets/server-BE8W-AT4.js","assets/rotate-ccw-7SQDTI0_.js","assets/flask-conical-BGn5PgFX.js","assets/archive-gZFnGd5A.js","assets/radio-B7kX_yWE.js","assets/test-tube-Xfn9DJeg.js","assets/VoiceOverlay-B_ss7Zg_.js","assets/volume-2-DMaE91b5.js","assets/folder-BeZZUGnK.js","assets/shield-check-s7la2J2K.js","assets/external-link-D_ji4Bec.js","assets/link-CUpaumqr.js","assets/SelfImprovePanel-BxqWHXCU.js","assets/trophy-D0LhJSPA.js","assets/PersonasPanel-dR8VppcD.js","assets/PersonaProfilesPanel-DGtokXUu.js","assets/DreamPanel-DIrtlk2K.js","assets/HomelabPanel-BZvN4LPM.js","assets/StatCard-Djr487DV.js","assets/SkeletonLoader-Cax7YTqW.js","assets/NvidiaPanel-4DlcQlyl.js","assets/FilesPanel-CaLPog2e.js","assets/arrow-left-qA0Qer2h.js","assets/LogsPanel-DbP3Mwnr.js","assets/TelemetryPanel-D4PXsd-X.js","assets/SkillsPanel-CA415CT8.js","assets/McpPanel-BmNUFozc.js","assets/plug-yISDdeW2.js","assets/IntegrationsPanel-B4TyR6jC.js","assets/ChannelsPanel-DS21E-Iz.js","assets/MeshPanel-Bf-4brXL.js","assets/DataTable-PnhPeDBG.js","assets/MemoryWikiPanel-DdvCAZHa.js","assets/AutoresearchPanel-DCwiQ2v2.js","assets/SelfProposalsPanel-CuC94vdx.js","assets/OverviewPanel-DK8uuq4D.js","assets/layers-DxYDmPA_.js","assets/SessionsPanel-CQ8qvzp7.js","assets/WatchView-BCgLVfiV.js","assets/BackupPanel-DAy9G7Wt.js","assets/TrainingPanel-Dmbd1rJ-.js","assets/RecipesPanel-D3Zs2wxr.js","assets/VramPanel-CPICbZ2s.js","assets/TeamsPanel-C_Vu6vnY.js","assets/CronPanel-kEZK3gpx.js","assets/CheckpointsPanel-9-l_8GdG.js","assets/OrganismPanel-C2LYDPrn.js","assets/FleetPanel-BtlaV6pH.js","assets/BrowserPanel-D6UaSxap.js","assets/EvalPanel-CDG-njyj.js","assets/legacy-dHWI7k8P.js"])))=>i.map(i=>d[i]);
2
- var jl=Object.defineProperty;var El=(t,e,s)=>e in t?jl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var $e=(t,e,s)=>El(t,typeof e!="symbol"?e+"":e,s);import{c as tt,a as st,g as Nl,r as w,b as ge,j as n,S as Cr,W as Tr,B as xt,H as Cl,s as Tl,u as no,d as Rl,e as Al,X as Es,f as mn,E as ro,A as Yt,C as Rr,U as Ar,h as Lr,G as io,R as oe,_ as le,Z as Ll,i as gn,I as fi,k as Il,l as Dl,L as oo,m as Ml,M as Ol,n as Pl,o as Wl,p as Bl,t as Wn}from"./index-CUgepw5Q.js";import{C as Ul}from"./chevron-up-UyfdjRp6.js";import{P as Fl}from"./plus-BSjTdepW.js";import{F as yn}from"./file-text-DrdTDEYp.js";import{S as Ir}from"./server-BE8W-AT4.js";import{N as ao}from"./network-DaJ7ugwX.js";import{T as lo}from"./terminal-B8IK4WsO.js";import{B as ps}from"./book-open-DIxdPqmD.js";import{S as bn}from"./save-CjTPAQM0.js";import{P as $l}from"./pencil-D_YwQBeg.js";import{R as co}from"./rotate-ccw-7SQDTI0_.js";import{S as uo}from"./search-BP7VlNxX.js";import{S as ho}from"./send-C2XDuRPf.js";import{M as xn}from"./message-square-D5VWlv-Q.js";import{M as fo}from"./mic-Ddcc6Ann.js";import{F as po}from"./flask-conical-BGn5PgFX.js";import{C as ms}from"./clock-CF9BCIpL.js";import{A as mo}from"./archive-gZFnGd5A.js";import{R as go}from"./radio-B7kX_yWE.js";import{T as yo,P as pi}from"./test-tube-Xfn9DJeg.js";import{VoiceOverlay as zl}from"./VoiceOverlay-B_ss7Zg_.js";import{C as Hl}from"./chevron-right-CQ1NTOtd.js";import{R as wn}from"./refresh-cw-CwDpzXUn.js";import{F as Vl}from"./folder-BeZZUGnK.js";import{C as mi}from"./check-DgyDEFtq.js";import{S as Gl}from"./shield-check-s7la2J2K.js";import{E as gi}from"./external-link-D_ji4Bec.js";import{B as Dr}from"./bot-CvIF1uHi.js";import{W as ql}from"./wifi-off-DR9h8HGA.js";import{C as Yl}from"./chart-column-BQiM-Td4.js";import{L as Kl}from"./link-CUpaumqr.js";import{T as Jl}from"./trash-2-B1C85ePK.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 Xl=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],Ql=tt("command",Xl);/**
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 Zl=[["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"}]],ec=tt("compass",Zl);/**
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 tc=[["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"}]],sc=tt("database",tc);/**
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 nc=[["path",{d:"M7 2h10",key:"nczekb"}],["path",{d:"M5 6h14",key:"u2x4p"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}]],rc=tt("gallery-vertical-end",nc);/**
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 ic=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],oc=tt("gauge",ic);/**
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 ac=[["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"}]],bo=tt("git-pull-request",ac);/**
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 lc=[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"1uw2ng"}]],cc=tt("heart-pulse",lc);/**
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 dc=[["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"}]],uc=tt("history",dc);/**
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 hc=[["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"}]],xo=tt("layout-grid",hc);/**
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 fc=[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]],pc=tt("navigation",fc);/**
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 mc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}]],gc=tt("panel-top",mc),Fe=()=>new Map,lr=t=>{const e=Fe();return t.forEach((s,r)=>{e.set(r,s)}),e},Ve=(t,e,s)=>{let r=t.get(e);return r===void 0&&t.set(e,r=s()),r},yc=(t,e)=>{const s=[];for(const[r,i]of t)s.push(e(i,r));return s},bc=(t,e)=>{for(const[s,r]of t)if(e(r,s))return!0;return!1},wt=()=>new Set,Bn=t=>t[t.length-1],xc=(t,e)=>{for(let s=0;s<e.length;s++)t.push(e[s])},ut=Array.from,Mr=(t,e)=>{for(let s=0;s<t.length;s++)if(!e(t[s],s,t))return!1;return!0},wo=(t,e)=>{for(let s=0;s<t.length;s++)if(e(t[s],s,t))return!0;return!1},wc=(t,e)=>{const s=new Array(t);for(let r=0;r<t;r++)s[r]=e(r,s);return s},vn=Array.isArray;class vo{constructor(){this._observers=Fe()}on(e,s){return Ve(this._observers,e,wt).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 ut((this._observers.get(e)||Fe()).values()).forEach(r=>r(...s))}destroy(){this._observers=Fe()}}class Or{constructor(){this._observers=Fe()}on(e,s){Ve(this._observers,e,wt).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 ut((this._observers.get(e)||Fe()).values()).forEach(r=>r(...s))}destroy(){this._observers=Fe()}}const Xe=Math.floor,Hs=Math.abs,vc=Math.log10,Pr=(t,e)=>t<e?t:e,Dt=(t,e)=>t>e?t:e,_o=t=>t!==0?t<0:1/t<0,yi=1,bi=2,Un=4,Fn=8,gs=32,ct=64,He=128,_n=31,cr=63,Et=127,_c=2147483647,Ks=Number.MAX_SAFE_INTEGER,xi=Number.MIN_SAFE_INTEGER,kc=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Xe(t)===t),ko=String.fromCharCode,Sc=t=>t.toLowerCase(),jc=/^\s*/g,Ec=t=>t.replace(jc,""),Nc=/([A-Z])/g,wi=(t,e)=>Ec(t.replace(Nc,s=>`${e}${Sc(s)}`)),Cc=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},ys=typeof TextEncoder<"u"?new TextEncoder:null,Tc=t=>ys.encode(t),dr=ys?Tc:Cc;let us=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});us&&us.decode(new Uint8Array).length===1&&(us=null);const Rc=(t,e)=>wc(e,()=>t).join("");class Ns{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const De=()=>new Ns,Ac=t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e},Se=t=>{const e=new Uint8Array(Ac(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},Lc=(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(Dt(s,e)*2),t.cpos=0)},Le=(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},bs=Le,ie=(t,e)=>{for(;e>Et;)Le(t,He|Et&e),e=Xe(e/128);Le(t,Et&e)},Wr=(t,e)=>{const s=_o(e);for(s&&(e=-e),Le(t,(e>cr?He:0)|(s?ct:0)|cr&e),e=Xe(e/64);e>0;)Le(t,(e>Et?He:0)|Et&e),e=Xe(e/128)},ur=new Uint8Array(3e4),Ic=ur.length/3,Dc=(t,e)=>{if(e.length<Ic){const s=ys.encodeInto(e,ur).written||0;ie(t,s);for(let r=0;r<s;r++)Le(t,ur[r])}else je(t,dr(e))},Mc=(t,e)=>{const s=unescape(encodeURIComponent(e)),r=s.length;ie(t,r);for(let i=0;i<r;i++)Le(t,s.codePointAt(i))},rt=ys&&ys.encodeInto?Dc:Mc,kn=(t,e)=>{const s=t.cbuf.length,r=t.cpos,i=Pr(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(Dt(s*2,o)),t.cbuf.set(e.subarray(i)),t.cpos=o)},je=(t,e)=>{ie(t,e.byteLength),kn(t,e)},Br=(t,e)=>{Lc(t,e);const s=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,s},Oc=(t,e)=>Br(t,4).setFloat32(0,e,!1),Pc=(t,e)=>Br(t,8).setFloat64(0,e,!1),Wc=(t,e)=>Br(t,8).setBigInt64(0,e,!1),vi=new DataView(new ArrayBuffer(4)),Bc=t=>(vi.setFloat32(0,t),vi.getFloat32(0)===t),Kt=(t,e)=>{switch(typeof e){case"string":Le(t,119),rt(t,e);break;case"number":kc(e)&&Hs(e)<=_c?(Le(t,125),Wr(t,e)):Bc(e)?(Le(t,124),Oc(t,e)):(Le(t,123),Pc(t,e));break;case"bigint":Le(t,122),Wc(t,e);break;case"object":if(e===null)Le(t,126);else if(vn(e)){Le(t,117),ie(t,e.length);for(let s=0;s<e.length;s++)Kt(t,e[s])}else if(e instanceof Uint8Array)Le(t,116),je(t,e);else{Le(t,118);const s=Object.keys(e);ie(t,s.length);for(let r=0;r<s.length;r++){const i=s[r];rt(t,i),Kt(t,e[i])}}break;case"boolean":Le(t,e?120:121);break;default:Le(t,127)}};class _i extends Ns{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&ie(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const ki=t=>{t.count>0&&(Wr(t.encoder,t.count===1?t.s:-t.s),t.count>1&&ie(t.encoder,t.count-2))};class Vs{constructor(){this.encoder=new Ns,this.s=0,this.count=0}write(e){this.s===e?this.count++:(ki(this),this.count=1,this.s=e)}toUint8Array(){return ki(this),Se(this.encoder)}}const Si=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Wr(t.encoder,e),t.count>1&&ie(t.encoder,t.count-2)}};class $n{constructor(){this.encoder=new Ns,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Si(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Si(this),Se(this.encoder)}}class Uc{constructor(){this.sarr=[],this.s="",this.lensE=new Vs}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 Ns;return this.sarr.push(this.s),this.s="",rt(e,this.sarr.join("")),kn(e,this.lensE.toUint8Array()),Se(e)}}const Ge=t=>new Error(t),Ze=()=>{throw Ge("Method unimplemented")},Qe=()=>{throw Ge("Unexpected case")},So=Ge("Unexpected end of array"),jo=Ge("Integer out of Range");class Sn{constructor(e){this.arr=e,this.pos=0}}const at=t=>new Sn(t),Fc=t=>t.pos!==t.arr.length,$c=(t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s},Ie=t=>$c(t,de(t)),Ct=t=>t.arr[t.pos++],de=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&Et)*s,s*=128,i<He)return e;if(e>Ks)throw jo}throw So},Ur=t=>{let e=t.arr[t.pos++],s=e&cr,r=64;const i=(e&ct)>0?-1:1;if((e&He)===0)return i*s;const o=t.arr.length;for(;t.pos<o;){if(e=t.arr[t.pos++],s=s+(e&Et)*r,r*=128,e<He)return i*s;if(s>Ks)throw jo}throw So},zc=t=>{let e=de(t);if(e===0)return"";{let s=String.fromCodePoint(Ct(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(Ct(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))}},Hc=t=>us.decode(Ie(t)),dt=us?Hc:zc,Fr=(t,e)=>{const s=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,s},Vc=t=>Fr(t,4).getFloat32(0,!1),Gc=t=>Fr(t,8).getFloat64(0,!1),qc=t=>Fr(t,8).getBigInt64(0,!1),Yc=[t=>{},t=>null,Ur,Vc,Gc,qc,t=>!1,t=>!0,dt,t=>{const e=de(t),s={};for(let r=0;r<e;r++){const i=dt(t);s[i]=Jt(t)}return s},t=>{const e=de(t),s=[];for(let r=0;r<e;r++)s.push(Jt(t));return s},Ie],Jt=t=>Yc[127-Ct(t)](t);class ji extends Sn{constructor(e,s){super(e),this.reader=s,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Fc(this)?this.count=de(this)+1:this.count=-1),this.count--,this.s}}class Gs extends Sn{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Ur(this);const e=_o(this.s);this.count=1,e&&(this.s=-this.s,this.count=de(this)+2)}return this.count--,this.s}}class zn extends Sn{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Ur(this),s=e&1;this.diff=Xe(e/2),this.count=1,s&&(this.count=de(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Kc{constructor(e){this.decoder=new Gs(e),this.str=dt(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 Jc=crypto.getRandomValues.bind(crypto),Xc=Math.random,Eo=()=>Jc(new Uint32Array(1))[0],Qc="10000000-1000-4000-8000"+-1e11,No=()=>Qc.replace(/[018]/g,t=>(t^Eo()&15>>t/4).toString(16)),ht=Date.now,Xt=t=>new Promise(t);Promise.all.bind(Promise);const Zc=t=>Promise.reject(t),$r=t=>Promise.resolve(t),Ei=t=>t===void 0?null:t;class ed{constructor(){this.map=new Map}setItem(e,s){this.map.set(e,s)}getItem(e){return this.map.get(e)}}let Co=new ed,zr=!0;try{typeof localStorage<"u"&&localStorage&&(Co=localStorage,zr=!1)}catch{}const To=Co,td=t=>zr||addEventListener("storage",t),sd=t=>zr||removeEventListener("storage",t),xs=Symbol("Equality"),Ro=(t,e)=>{var s;return t===e||!!((s=t==null?void 0:t[xs])!=null&&s.call(t,e))||!1},nd=t=>typeof t=="object",rd=Object.assign,id=Object.keys,od=(t,e)=>{for(const s in t)e(t[s],s)},Js=t=>id(t).length,ad=t=>{for(const e in t)return!1;return!0},Cs=(t,e)=>{for(const s in t)if(!e(t[s],s))return!1;return!0},Hr=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),ld=(t,e)=>t===e||Js(t)===Js(e)&&Cs(t,(s,r)=>(s!==void 0||Hr(e,r))&&Ro(e[r],s)),cd=Object.freeze,Ao=t=>{for(const e in t){const s=t[e];(typeof s=="object"||typeof s=="function")&&Ao(t[e])}return cd(t)},Vr=(t,e,s=0)=>{try{for(;s<t.length;s++)t[s](...e)}finally{s<t.length&&Vr(t,e,s+1)}},dd=()=>{},ud=t=>t,zt=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[xs]!=null)return t[xs](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;break}case Set:{if(t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;break}case Map:{if(t.size!==e.size)return!1;for(const s of t.keys())if(!e.has(s)||!zt(t.get(s),e.get(s)))return!1;break}case void 0:case Object:if(Js(t)!==Js(e))return!1;for(const s in t)if(!Hr(t,s)||!zt(t[s],e[s]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!zt(t[s],e[s]))return!1;break;default:return!1}return!0},hd=(t,e)=>e.includes(t);var Lo={};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]",Io=typeof window<"u"&&typeof document<"u"&&!Qt;let nt;const fd=()=>{if(nt===void 0)if(Qt){nt=Fe();const t=process.argv;let e=null;for(let s=0;s<t.length;s++){const r=t[s];r[0]==="-"?(e!==null&&nt.set(e,""),e=r):e!==null&&(nt.set(e,r),e=null)}e!==null&&nt.set(e,"")}else typeof location=="object"?(nt=Fe(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,s]=t.split("=");nt.set(`--${wi(e,"-")}`,s),nt.set(`-${wi(e,"-")}`,s)}})):nt=Fe();return nt},hr=t=>fd().has(t),ws=t=>Ei(Qt?Lo[t.toUpperCase().replaceAll("-","_")]:To.getItem(t)),Do=t=>hr("--"+t)||ws(t)!==null,pd=Do("production"),md=Qt&&hd(Lo.FORCE_COLOR,["true","1","2"]),gd=md||!hr("--no-colors")&&!Do("no-color")&&(!Qt||process.stdout.isTTY)&&(!Qt||hr("--color")||ws("COLORTERM")!==null||(ws("TERM")||"").includes("color")),Mo=t=>new Uint8Array(t),yd=(t,e,s)=>new Uint8Array(t,e,s),bd=t=>new Uint8Array(t),xd=t=>{let e="";for(let s=0;s<t.byteLength;s++)e+=ko(t[s]);return btoa(e)},wd=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),vd=t=>{const e=atob(t),s=Mo(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s},_d=t=>{const e=Buffer.from(t,"base64");return yd(e.buffer,e.byteOffset,e.byteLength)},Oo=Io?xd:wd,Po=Io?vd:_d,kd=t=>{const e=Mo(t.byteLength);return e.set(t),e};class Sd{constructor(e,s){this.left=e,this.right=s}}const lt=(t,e)=>new Sd(t,e),Ni=t=>t.next()>=.5,Hn=(t,e,s)=>Xe(t.next()*(s+1-e)+e),Wo=(t,e,s)=>Xe(t.next()*(s+1-e)+e),Gr=(t,e,s)=>Wo(t,e,s),jd=t=>ko(Gr(t,97,122)),Ed=(t,e=0,s=20)=>{const r=Gr(t,e,s);let i="";for(let o=0;o<r;o++)i+=jd(t);return i},Vn=(t,e)=>e[Gr(t,0,e.length-1)],Nd=Symbol("0schema");class Cd{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(Rc(" ",(this._rerrs.length-s)*2)+`${r.path!=null?`[${r.path}] `:""}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(`
58
- `)}}const fr=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[xs]?Ro(t,e):vn(t)?Mr(t,s=>wo(e,r=>fr(s,r))):nd(t)?Cs(t,(s,r)=>fr(s,e[r])):!1;class Ue{extends(e){let[s,r]=[this.shape,e.shape];return this.constructor._dilutes&&([r,s]=[s,r]),fr(s,r)}equals(e){return this.constructor===e.constructor&&zt(this.shape,e.shape)}[Nd](){return!0}[xs](e){return this.equals(e)}validate(e){return this.check(e)}check(e,s){Ze()}get nullable(){return ns(this,Tn)}get optional(){return new Fo(this)}cast(e){return Ci(e,this),e}expect(e){return Ci(e,this),e}}$e(Ue,"_dilutes",!1);class qr extends Ue{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s=void 0){const r=(e==null?void 0:e.constructor)===this.shape&&(this._c==null||this._c(e));return!r&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name,(e==null?void 0:e.constructor)!==this.shape?"Constructor match failed":"Check failed")),r}}const Ne=(t,e=null)=>new qr(t,e);Ne(qr);class Yr extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=this.shape(e);return!r&&(s==null||s.extend(null,"custom prop",e==null?void 0:e.constructor.name,"failed to check custom prop")),r}}const Oe=t=>new Yr(t);Ne(Yr);class jn extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=this.shape.some(i=>i===e);return!r&&(s==null||s.extend(null,this.shape.join(" | "),e.toString())),r}}const En=(...t)=>new jn(t),Bo=Ne(jn),Td=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Uo=t=>{if(Zt.check(t))return[Td(t)];if(Bo.check(t))return t.shape.map(e=>e+"");if(Jo.check(t))return["[+-]?\\d+.?\\d*"];if(Xo.check(t))return[".*"];if(Qs.check(t))return t.shape.map(Uo).flat(1);Qe()};class Rd extends Ue{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Uo).map(s=>`(${s.join("|")})`).join("")+"$")}check(e,s){const r=this._r.exec(e)!=null;return!r&&(s==null||s.extend(null,this._r.toString(),e.toString(),"String doesn't match string template.")),r}}Ne(Rd);const Ad=Symbol("optional");class Fo extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=e===void 0||this.shape.check(e);return!r&&(s==null||s.extend(null,"undefined (optional)","()")),r}get[Ad](){return!0}}const Ld=Ne(Fo);class Id extends Ue{check(e,s){return s==null||s.extend(null,"never",typeof e),!1}}Ne(Id);const pn=class pn extends Ue{constructor(e,s=!1){super(),this.shape=e,this._isPartial=s}get partial(){return new pn(this.shape,!0)}check(e,s){return e==null?(s==null||s.extend(null,"object","null"),!1):Cs(this.shape,(r,i)=>{const o=this._isPartial&&!Hr(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})}};$e(pn,"_dilutes",!0);let Xs=pn;const Dd=t=>new Xs(t),Md=Ne(Xs),Od=Oe(t=>t!=null&&(t.constructor===Object||t.constructor==null));class $o extends Ue{constructor(e,s){super(),this.shape={keys:e,values:s}}check(e,s){return e!=null&&Cs(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 zo=(t,e)=>new $o(t,e),Pd=Ne($o);class Ho extends Ue{constructor(e){super(),this.shape=e}check(e,s){return e!=null&&Cs(this.shape,(r,i)=>{const o=r.check(e[i],s);return!o&&(s==null||s.extend(i.toString(),"Tuple",typeof r)),o})}}const Wd=(...t)=>new Ho(t);Ne(Ho);class Vo extends Ue{constructor(e){super(),this.shape=e.length===1?e[0]:new Nn(e)}check(e,s){const r=vn(e)&&Mr(e,i=>this.shape.check(i));return!r&&(s==null||s.extend(null,"Array","")),r}}const Go=(...t)=>new Vo(t),Bd=Ne(Vo),Ud=Oe(t=>vn(t));class qo extends Ue{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s){const r=e instanceof this.shape&&(this._c==null||this._c(e));return!r&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name)),r}}const Fd=(t,e=null)=>new qo(t,e);Ne(qo);const $d=Fd(Ue);class zd extends Ue{constructor(e){super(),this.len=e.length-1,this.args=Wd(...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 Hd=Ne(zd),Vd=Oe(t=>typeof t=="function");class Gd extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=Mr(this.shape,i=>i.check(e,s));return!r&&(s==null||s.extend(null,"Intersectinon",typeof e)),r}}Ne(Gd,t=>t.shape.length>0);class Nn extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=wo(this.shape,i=>i.check(e,s));return s==null||s.extend(null,"Union",typeof e),r}}$e(Nn,"_dilutes",!0);const ns=(...t)=>t.findIndex(e=>Qs.check(e))>=0?ns(...t.map(e=>vs(e)).map(e=>Qs.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new Nn(t),Qs=Ne(Nn),Yo=()=>!0,Zs=Oe(Yo),qd=Ne(Yr,t=>t.shape===Yo),Kr=Oe(t=>typeof t=="bigint"),Yd=Oe(t=>t===Kr),Ko=Oe(t=>typeof t=="symbol");Oe(t=>t===Ko);const Ht=Oe(t=>typeof t=="number"),Jo=Oe(t=>t===Ht),Zt=Oe(t=>typeof t=="string"),Xo=Oe(t=>t===Zt),Cn=Oe(t=>typeof t=="boolean"),Kd=Oe(t=>t===Cn),Qo=En(void 0);Ne(jn,t=>t.shape.length===1&&t.shape[0]===void 0);En(void 0);const Tn=En(null),Jd=Ne(jn,t=>t.shape.length===1&&t.shape[0]===null);Ne(Uint8Array);Ne(qr,t=>t.shape===Uint8Array);const Xd=ns(Ht,Zt,Tn,Qo,Kr,Cn,Ko);(()=>{const t=Go(Zs),e=zo(Zt,Zs),s=ns(Ht,Zt,Tn,Cn,t,e);return t.shape=s,e.shape.values=s,s})();const vs=t=>{if($d.check(t))return t;if(Od.check(t)){const e={};for(const s in t)e[s]=vs(t[s]);return Dd(e)}else{if(Ud.check(t))return ns(...t.map(vs));if(Xd.check(t))return En(t);if(Vd.check(t))return Ne(t)}Qe()},Ci=pd?()=>{}:(t,e)=>{const s=new Cd;if(!e.check(t,s))throw Ge(`Expected value to be of type ${e.constructor.name}.
59
- ${s.toString()}`)};class Qd{constructor(e){this.patterns=[],this.$state=e}if(e,s){return this.patterns.push({if:vs(e),h:s}),this}else(e){return this.if(Zs,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 Ge("Unhandled pattern")}}}const Zd=t=>new Qd(t),Zo=Zd(Zs).if(Jo,(t,e)=>Hn(e,xi,Ks)).if(Xo,(t,e)=>Ed(e)).if(Kd,(t,e)=>Ni(e)).if(Yd,(t,e)=>BigInt(Hn(e,xi,Ks))).if(Qs,(t,e)=>Ut(e,Vn(e,t.shape))).if(Md,(t,e)=>{const s={};for(const r in t.shape){let i=t.shape[r];if(Ld.check(i)){if(Ni(e))continue;i=i.shape}s[r]=Zo(i,e)}return s}).if(Bd,(t,e)=>{const s=[],r=Wo(e,0,42);for(let i=0;i<r;i++)s.push(Ut(e,t.shape));return s}).if(Bo,(t,e)=>Vn(e,t.shape)).if(Jd,(t,e)=>null).if(Hd,(t,e)=>{const s=Ut(e,t.res);return()=>s}).if(qd,(t,e)=>Ut(e,Vn(e,[Ht,Zt,Tn,Qo,Kr,Cn,Go(Ht),zo(ns("a","b","c"),Ht)]))).if(Pd,(t,e)=>{const s={},r=Hn(e,0,3);for(let i=0;i<r;i++){const o=Ut(e,t.shape.keys),c=Ut(e,t.shape.values);s[o]=c}return s}).done(),Ut=(t,e)=>Zo(vs(e),t),Rn=typeof document<"u"?document:{};Oe(t=>t.nodeType===ru);typeof DOMParser<"u"&&new DOMParser;Oe(t=>t.nodeType===tu);Oe(t=>t.nodeType===su);const eu=t=>yc(t,(e,s)=>`${s}:${e};`).join(""),tu=Rn.ELEMENT_NODE,su=Rn.TEXT_NODE,nu=Rn.DOCUMENT_NODE,ru=Rn.DOCUMENT_FRAGMENT_NODE;Oe(t=>t.nodeType===nu);const iu=JSON.stringify,pt=Symbol,Je=pt(),Tt=pt(),ea=pt(),Jr=pt(),ta=pt(),sa=pt(),na=pt(),An=pt(),Ln=pt(),ou=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},Ti=[ta,na,An,ea];let Gn=0,Ri=ht();const au=(t,e)=>{const s=Ti[Gn],r=ws("log"),i=r!==null&&(r==="*"||r==="true"||new RegExp(r,"gi").test(e));return Gn=(Gn+1)%Ti.length,e+=": ",i?(...o)=>{var l;o.length===1&&((l=o[0])==null?void 0:l.constructor)===Function&&(o=o[0]());const c=ht(),d=c-Ri;Ri=c,t(s,e,Ln,...o.map(p=>{switch(p!=null&&p.constructor===Uint8Array&&(p=Array.from(p)),typeof p){case"string":case"symbol":return p;default:return iu(p)}}),s," +"+d+"ms")}:dd},lu={[Je]:lt("font-weight","bold"),[Tt]:lt("font-weight","normal"),[ea]:lt("color","blue"),[ta]:lt("color","green"),[Jr]:lt("color","grey"),[sa]:lt("color","red"),[na]:lt("color","purple"),[An]:lt("color","orange"),[Ln]:lt("color","black")},cu=t=>{var c;t.length===1&&((c=t[0])==null?void 0:c.constructor)===Function&&(t=t[0]());const e=[],s=[],r=Fe();let i=[],o=0;for(;o<t.length;o++){const d=t[o],l=lu[d];if(l!==void 0)r.set(l.left,l.right);else{if(d===void 0)break;if(d.constructor===String||d.constructor===Number){const p=eu(r);o>0||p.length>0?(e.push("%c"+d),s.push(p)):e.push(d)}else break}}for(o>0&&(i=s,i.unshift(e.join("")));o<t.length;o++){const d=t[o];d instanceof Symbol||i.push(d)}return i},ra=gd?cu:ou,ia=(...t)=>{console.log(...ra(t)),oa.forEach(e=>e.print(t))},du=(...t)=>{console.warn(...ra(t)),t.unshift(An),oa.forEach(e=>e.print(t))},oa=wt(),uu=t=>au(ia,t),aa=t=>({[Symbol.iterator](){return this},next:t}),hu=(t,e)=>aa(()=>{let s;do s=t.next();while(!s.done&&!e(s.value));return s}),qn=(t,e)=>aa(()=>{const{done:s,value:r}=t.next();return{done:s,value:s?void 0:e(r)}});class In{constructor(e,s){this.clock=e,this.len=s}}class Ts{constructor(){this.clients=new Map}}const la=(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],d=c.id.clock+c.length;for(let l=0,p=r[l];l<r.length&&p.clock<d;p=r[++l])_a(t,o,p.clock,p.len,s)}}),fu=(t,e)=>{let s=0,r=t.length-1;for(;s<=r;){const i=Xe((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},ca=(t,e)=>{const s=t.clients.get(e.client);return s!==void 0&&fu(s,e.clock)!==null},Xr=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 In(i.clock,Dt(i.len,o.clock+o.len-i.clock)):(r<s&&(e[r]=o),r++)}e.length=r})},pu=t=>{const e=new Ts;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++)xc(o,t[c].clients.get(i)||[]);e.clients.set(i,o)}});return Xr(e),e},en=(t,e,s,r)=>{Ve(t.clients,e,()=>[]).push(new In(s,r))},mu=()=>new Ts,gu=t=>{const e=mu();return t.clients.forEach((s,r)=>{const i=[];for(let o=0;o<s.length;o++){const c=s[o];if(c.deleted){const d=c.id.clock;let l=c.length;if(o+1<s.length)for(let p=s[o+1];o+1<s.length&&p.deleted;p=s[++o+1])l+=p.length;i.push(new In(d,l))}}i.length>0&&e.clients.set(r,i)}),e},rs=(t,e)=>{ie(t.restEncoder,e.clients.size),ut(e.clients.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{t.resetDsCurVal(),ie(t.restEncoder,s);const i=r.length;ie(t.restEncoder,i);for(let o=0;o<i;o++){const c=r[o];t.writeDsClock(c.clock),t.writeDsLen(c.len)}})},Qr=t=>{const e=new Ts,s=de(t.restDecoder);for(let r=0;r<s;r++){t.resetDsCurVal();const i=de(t.restDecoder),o=de(t.restDecoder);if(o>0){const c=Ve(e.clients,i,()=>[]);for(let d=0;d<o;d++)c.push(new In(t.readDsClock(),t.readDsLen()))}}return e},Ai=(t,e,s)=>{const r=new Ts,i=de(t.restDecoder);for(let o=0;o<i;o++){t.resetDsCurVal();const c=de(t.restDecoder),d=de(t.restDecoder),l=s.clients.get(c)||[],p=Me(s,c);for(let g=0;g<d;g++){const u=t.readDsClock(),f=u+t.readDsLen();if(u<p){p<f&&en(r,c,p,f-p);let x=it(l,u),y=l[x];for(!y.deleted&&y.id.clock<u&&(l.splice(x+1,0,ln(e,y,u-y.id.clock)),x++);x<l.length&&(y=l[x++],y.id.clock<f);)y.deleted||(f<y.id.clock+y.length&&l.splice(x,0,ln(e,y,f-y.id.clock)),y.delete(e))}else en(r,c,u,f-u)}}if(r.clients.size>0){const o=new Rt;return ie(o.restEncoder,0),rs(o,r),o.toUint8Array()}return null},da=Eo;class is extends vo{constructor({guid:e=No(),collectionid:s=null,gc:r=!0,gcFilter:i=()=>!0,meta:o=null,autoLoad:c=!1,shouldLoad:d=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=da(),this.guid=e,this.collectionid=s,this.share=new Map,this.store=new wa,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=d,this.autoLoad=c,this.meta=o,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Xt(p=>{this.on("load",()=>{this.isLoaded=!0,p(this)})});const l=()=>Xt(p=>{const g=u=>{(u===void 0||u===!0)&&(this.off("sync",g),p())};this.on("sync",g)});this.on("sync",p=>{p===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=p===void 0||p===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;e!==null&&!this.shouldLoad&&we(e.parent.doc,s=>{s.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(ut(this.subdocs).map(e=>e.guid))}transact(e,s=null){return we(this,e,s)}get(e,s=We){const r=Ve(this.share,e,()=>{const o=new s;return o._integrate(this,null),o}),i=r.constructor;if(s!==We&&i!==s)if(i===We){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,Gt)}getText(e=""){return this.get(e,ts)}getMap(e=""){return this.get(e,At)}getXmlElement(e=""){return this.get(e,ss)}getXmlFragment(e=""){return this.get(e,Lt)}toJSON(){const e={};return this.share.forEach((s,r)=>{e[r]=s.toJSON()}),e}destroy(){this.isDestroyed=!0,ut(this.subdocs).forEach(s=>s.destroy());const e=this._item;if(e!==null){this._item=null;const s=e.content;s.doc=new is({guid:this.guid,...s.opts,shouldLoad:!1}),s.doc._item=e,we(e.parent.doc,r=>{const i=s.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class ua{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return de(this.restDecoder)}readDsLen(){return de(this.restDecoder)}}class ha extends ua{readLeftID(){return me(de(this.restDecoder),de(this.restDecoder))}readRightID(){return me(de(this.restDecoder),de(this.restDecoder))}readClient(){return de(this.restDecoder)}readInfo(){return Ct(this.restDecoder)}readString(){return dt(this.restDecoder)}readParentInfo(){return de(this.restDecoder)===1}readTypeRef(){return de(this.restDecoder)}readLen(){return de(this.restDecoder)}readAny(){return Jt(this.restDecoder)}readBuf(){return kd(Ie(this.restDecoder))}readJSON(){return JSON.parse(dt(this.restDecoder))}readKey(){return dt(this.restDecoder)}}class yu{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=de(this.restDecoder),this.dsCurrVal}readDsLen(){const e=de(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class es extends yu{constructor(e){super(e),this.keys=[],de(e),this.keyClockDecoder=new zn(Ie(e)),this.clientDecoder=new Gs(Ie(e)),this.leftClockDecoder=new zn(Ie(e)),this.rightClockDecoder=new zn(Ie(e)),this.infoDecoder=new ji(Ie(e),Ct),this.stringDecoder=new Kc(Ie(e)),this.parentInfoDecoder=new ji(Ie(e),Ct),this.typeRefDecoder=new Gs(Ie(e)),this.lenDecoder=new Gs(Ie(e))}readLeftID(){return new Vt(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Vt(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Jt(this.restDecoder)}readBuf(){return Ie(this.restDecoder)}readJSON(){return Jt(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 fa{constructor(){this.restEncoder=De()}toUint8Array(){return Se(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ie(this.restEncoder,e)}writeDsLen(e){ie(this.restEncoder,e)}}class Rs extends fa{writeLeftID(e){ie(this.restEncoder,e.client),ie(this.restEncoder,e.clock)}writeRightID(e){ie(this.restEncoder,e.client),ie(this.restEncoder,e.clock)}writeClient(e){ie(this.restEncoder,e)}writeInfo(e){bs(this.restEncoder,e)}writeString(e){rt(this.restEncoder,e)}writeParentInfo(e){ie(this.restEncoder,e?1:0)}writeTypeRef(e){ie(this.restEncoder,e)}writeLen(e){ie(this.restEncoder,e)}writeAny(e){Kt(this.restEncoder,e)}writeBuf(e){je(this.restEncoder,e)}writeJSON(e){rt(this.restEncoder,JSON.stringify(e))}writeKey(e){rt(this.restEncoder,e)}}class pa{constructor(){this.restEncoder=De(),this.dsCurrVal=0}toUint8Array(){return Se(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const s=e-this.dsCurrVal;this.dsCurrVal=e,ie(this.restEncoder,s)}writeDsLen(e){e===0&&Qe(),ie(this.restEncoder,e-1),this.dsCurrVal+=e}}class Rt extends pa{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new $n,this.clientEncoder=new Vs,this.leftClockEncoder=new $n,this.rightClockEncoder=new $n,this.infoEncoder=new _i(bs),this.stringEncoder=new Uc,this.parentInfoEncoder=new _i(bs),this.typeRefEncoder=new Vs,this.lenEncoder=new Vs}toUint8Array(){const e=De();return ie(e,0),je(e,this.keyClockEncoder.toUint8Array()),je(e,this.clientEncoder.toUint8Array()),je(e,this.leftClockEncoder.toUint8Array()),je(e,this.rightClockEncoder.toUint8Array()),je(e,Se(this.infoEncoder)),je(e,this.stringEncoder.toUint8Array()),je(e,Se(this.parentInfoEncoder)),je(e,this.typeRefEncoder.toUint8Array()),je(e,this.lenEncoder.toUint8Array()),kn(e,Se(this.restEncoder)),Se(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){Kt(this.restEncoder,e)}writeBuf(e){je(this.restEncoder,e)}writeJSON(e){Kt(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 bu=(t,e,s,r)=>{r=Dt(r,e[0].id.clock);const i=it(e,r);ie(t.restEncoder,e.length-i),t.writeClient(s),ie(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)},Zr=(t,e,s)=>{const r=new Map;s.forEach((i,o)=>{Me(e,o)>i&&r.set(o,i)}),Dn(e).forEach((i,o)=>{s.has(o)||r.set(o,0)}),ie(t.restEncoder,r.size),ut(r.entries()).sort((i,o)=>o[0]-i[0]).forEach(([i,o])=>{bu(t,e.clients.get(i),i,o)})},xu=(t,e)=>{const s=Fe(),r=de(t.restDecoder);for(let i=0;i<r;i++){const o=de(t.restDecoder),c=new Array(o),d=t.readClient();let l=de(t.restDecoder);s.set(d,{i:0,refs:c});for(let p=0;p<o;p++){const g=t.readInfo();switch(_n&g){case 0:{const u=t.readLen();c[p]=new Ye(me(d,l),u),l+=u;break}case 10:{const u=de(t.restDecoder);c[p]=new Ke(me(d,l),u),l+=u;break}default:{const u=(g&(ct|He))===0,f=new Te(me(d,l),null,(g&He)===He?t.readLeftID():null,null,(g&ct)===ct?t.readRightID():null,u?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,u&&(g&gs)===gs?t.readString():null,Fa(t,g));c[p]=f,l+=f.length}}}}return s},wu=(t,e,s)=>{const r=[];let i=ut(s.keys()).sort((x,y)=>x-y);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 d=new wa,l=new Map,p=(x,y)=>{const E=l.get(x);(E==null||E>y)&&l.set(x,y)};let g=c.refs[c.i++];const u=new Map,f=()=>{for(const x of r){const y=x.id.client,E=s.get(y);E?(E.i--,d.clients.set(y,E.refs.slice(E.i)),s.delete(y),E.i=0,E.refs=[]):d.clients.set(y,[x]),i=i.filter(L=>L!==y)}r.length=0};for(;;){if(g.constructor!==Ke){const y=Ve(u,g.id.client,()=>Me(e,g.id.client))-g.id.clock;if(y<0)r.push(g),p(g.id.client,g.id.clock-1),f();else{const E=g.getMissing(t,e);if(E!==null){r.push(g);const L=s.get(E)||{refs:[],i:0};if(L.refs.length===L.i)p(E,Me(e,E)),f();else{g=L.refs[L.i++];continue}}else(y===0||y<g.length)&&(g.integrate(t,y),u.set(g.id.client,g.id.clock+g.length))}}if(r.length>0)g=r.pop();else if(c!==null&&c.i<c.refs.length)g=c.refs[c.i++];else{if(c=o(),c===null)break;g=c.refs[c.i++]}}if(d.clients.size>0){const x=new Rt;return Zr(x,d,new Map),ie(x.restEncoder,0),{missing:l,update:x.toUint8Array()}}return null},vu=(t,e)=>Zr(t,e.doc.store,e.beforeState),_u=(t,e,s,r=new es(t))=>we(e,i=>{i.local=!1;let o=!1;const c=i.doc,d=c.store,l=xu(r,c),p=wu(i,d,l),g=d.pendingStructs;if(g){for(const[f,x]of g.missing)if(x<Me(d,f)){o=!0;break}if(p){for(const[f,x]of p.missing){const y=g.missing.get(f);(y==null||y>x)&&g.missing.set(f,x)}g.update=tn([g.update,p.update])}}else d.pendingStructs=p;const u=Ai(r,i,d);if(d.pendingDs){const f=new es(at(d.pendingDs));de(f.restDecoder);const x=Ai(f,i,d);u&&x?d.pendingDs=tn([u,x]):d.pendingDs=u||x}else d.pendingDs=u;if(o){const f=d.pendingStructs.update;d.pendingStructs=null,ma(i.doc,f)}},s,!1),ma=(t,e,s,r=es)=>{const i=at(e);_u(i,t,s,new r(i))},ga=(t,e,s)=>ma(t,e,s,ha),ku=(t,e,s=new Map)=>{Zr(t,e.store,s),rs(t,gu(e.store))},Su=(t,e=new Uint8Array([0]),s=new Rt)=>{const r=ya(e);ku(s,t,r);const i=[s.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(Bu(t.store.pendingStructs.update,e)),i.length>1){if(s.constructor===Rs)return Pu(i.map((o,c)=>c===0?o:Fu(o)));if(s.constructor===Rt)return tn(i)}return i[0]},ei=(t,e)=>Su(t,e,new Rs),ju=t=>{const e=new Map,s=de(t.restDecoder);for(let r=0;r<s;r++){const i=de(t.restDecoder),o=de(t.restDecoder);e.set(i,o)}return e},ya=t=>ju(new ua(at(t))),ba=(t,e)=>(ie(t.restEncoder,e.size),ut(e.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{ie(t.restEncoder,s),ie(t.restEncoder,r)}),t),Eu=(t,e)=>ba(t,Dn(e.store)),Nu=(t,e=new pa)=>(t instanceof Map?ba(e,t):Eu(e,t),e.toUint8Array()),Cu=t=>Nu(t,new fa);class Tu{constructor(){this.l=[]}}const Li=()=>new Tu,Ii=(t,e)=>t.l.push(e),Di=(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.")},xa=(t,e,s)=>Vr(t.l,[e,s]);class Vt{constructor(e,s){this.client=e,this.clock=s}}const Is=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,me=(t,e)=>new Vt(t,e),Ru=t=>{for(const[e,s]of t.doc.share.entries())if(s===t)return e;throw Qe()},$t=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!ca(e.ds,t.id),pr=(t,e)=>{const s=Ve(t.meta,pr,wt),r=t.doc.store;s.has(e)||(e.sv.forEach((i,o)=>{i<Me(r,o)&&vt(t,me(o,i))}),la(t,e.ds,i=>{}),s.add(e))};class wa{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Dn=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},Me=(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},va=(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 Qe()}s.push(e)},it=(t,e)=>{let s=0,r=t.length-1,i=t[r],o=i.id.clock;if(o===e)return r;let c=Xe(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=Xe((s+r)/2)}throw Qe()},Au=(t,e)=>{const s=t.clients.get(e.client);return s[it(s,e.clock)]},Yn=Au,mr=(t,e,s)=>{const r=it(e,s),i=e[r];return i.id.clock<s&&i instanceof Te?(e.splice(r+1,0,ln(t,i,s-i.id.clock)),r+1):r},vt=(t,e)=>{const s=t.doc.store.clients.get(e.client);return s[mr(t,s,e.clock)]},Mi=(t,e,s)=>{const r=e.clients.get(s.client),i=it(r,s.clock),o=r[i];return s.clock!==o.id.clock+o.length-1&&o.constructor!==Ye&&r.splice(i+1,0,ln(t,o,s.clock-o.id.clock+1)),o},Lu=(t,e,s)=>{const r=t.clients.get(e.id.client);r[it(r,e.id.clock)]=s},_a=(t,e,s,r,i)=>{if(r===0)return;const o=s+r;let c=mr(t,e,s),d;do d=e[c++],o<d.id.clock+d.length&&mr(t,e,o),i(d);while(c<e.length&&e[c].id.clock<o)};class Iu{constructor(e,s,r){this.doc=e,this.deleteSet=new Ts,this.beforeState=Dn(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 Oi=(t,e)=>e.deleteSet.clients.size===0&&!bc(e.afterState,(s,r)=>e.beforeState.get(r)!==s)?!1:(Xr(e.deleteSet),vu(t,e),rs(t,e.deleteSet),!0),Pi=(t,e,s)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&Ve(t.changed,e,wt).add(s)},qs=(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 Te&&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},Du=(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 d=i[c],l=d.clock+d.len;for(let p=it(o,d.clock),g=o[p];p<o.length&&g.id.clock<l;g=o[++p]){const u=o[p];if(d.clock+d.len<=u.id.clock)break;u instanceof Te&&u.deleted&&!u.keep&&s(u)&&u.gc(e,!1)}}}},Mu=(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],d=Pr(i.length-1,1+it(i,c.clock+c.len-1));for(let l=d,p=i[l];l>0&&p.id.clock>=c.clock;p=i[l])l-=1+qs(i,l)}})},ka=(t,e)=>{if(e<t.length){const s=t[e],r=s.doc,i=r.store,o=s.deleteSet,c=s._mergeStructs;try{Xr(o),s.afterState=Dn(s.doc.store),r.emit("beforeObserverCalls",[s,r]);const d=[];s.changed.forEach((l,p)=>d.push(()=>{(p._item===null||!p._item.deleted)&&p._callObserver(s,l)})),d.push(()=>{s.changedParentTypes.forEach((l,p)=>{p._dEH.l.length>0&&(p._item===null||!p._item.deleted)&&(l=l.filter(g=>g.target._item===null||!g.target._item.deleted),l.forEach(g=>{g.currentTarget=p,g._path=null}),l.sort((g,u)=>g.path.length-u.path.length),d.push(()=>{xa(p._dEH,l,s)}))}),d.push(()=>r.emit("afterTransaction",[s,r])),d.push(()=>{s._needFormattingCleanup&&th(s)})}),Vr(d,[])}finally{r.gc&&Du(o,i,r.gcFilter),Mu(o,i),s.afterState.forEach((g,u)=>{const f=s.beforeState.get(u)||0;if(f!==g){const x=i.clients.get(u),y=Dt(it(x,f),1);for(let E=x.length-1;E>=y;)E-=1+qs(x,E)}});for(let g=c.length-1;g>=0;g--){const{client:u,clock:f}=c[g].id,x=i.clients.get(u),y=it(x,f);y+1<x.length&&qs(x,y+1)>1||y>0&&qs(x,y)}if(!s.local&&s.afterState.get(r.clientID)!==s.beforeState.get(r.clientID)&&(ia(An,Je,"[yjs] ",Tt,sa,"Changed the client-id because another client seems to be using it."),r.clientID=da()),r.emit("afterTransactionCleanup",[s,r]),r._observers.has("update")){const g=new Rs;Oi(g,s)&&r.emit("update",[g.toUint8Array(),s.origin,r,s])}if(r._observers.has("updateV2")){const g=new Rt;Oi(g,s)&&r.emit("updateV2",[g.toUint8Array(),s.origin,r,s])}const{subdocsAdded:d,subdocsLoaded:l,subdocsRemoved:p}=s;(d.size>0||p.size>0||l.size>0)&&(d.forEach(g=>{g.clientID=r.clientID,g.collectionid==null&&(g.collectionid=r.collectionid),r.subdocs.add(g)}),p.forEach(g=>r.subdocs.delete(g)),r.emit("subdocs",[{loaded:l,added:d,removed:p},r,s]),p.forEach(g=>g.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):ka(t,e+1)}}},we=(t,e,s=null,r=!0)=>{const i=t._transactionCleanups;let o=!1,c=null;t._transaction===null&&(o=!0,t._transaction=new Iu(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 d=t._transaction===i[0];t._transaction=null,d&&ka(i,0)}}return c};function*Ou(t){const e=de(t.restDecoder);for(let s=0;s<e;s++){const r=de(t.restDecoder),i=t.readClient();let o=de(t.restDecoder);for(let c=0;c<r;c++){const d=t.readInfo();if(d===10){const l=de(t.restDecoder);yield new Ke(me(i,o),l),o+=l}else if((_n&d)!==0){const l=(d&(ct|He))===0,p=new Te(me(i,o),null,(d&He)===He?t.readLeftID():null,null,(d&ct)===ct?t.readRightID():null,l?t.readParentInfo()?t.readString():t.readLeftID():null,l&&(d&gs)===gs?t.readString():null,Fa(t,d));yield p,o+=p.length}else{const l=t.readLen();yield new Ye(me(i,o),l),o+=l}}}}class ti{constructor(e,s){this.gen=Ou(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===Ke);return this.curr}}class si{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Pu=t=>tn(t,ha,Rs),Wu=(t,e)=>{if(t.constructor===Ye){const{client:s,clock:r}=t.id;return new Ye(me(s,r+e),t.length-e)}else if(t.constructor===Ke){const{client:s,clock:r}=t.id;return new Ke(me(s,r+e),t.length-e)}else{const s=t,{client:r,clock:i}=s.id;return new Te(me(r,i+e),null,me(r,i+e-1),null,s.rightOrigin,s.parent,s.parentSub,s.content.splice(e))}},tn=(t,e=es,s=Rt)=>{if(t.length===1)return t[0];const r=t.map(g=>new e(at(g)));let i=r.map(g=>new ti(g,!0)),o=null;const c=new s,d=new si(c);for(;i=i.filter(f=>f.curr!==null),i.sort((f,x)=>{if(f.curr.id.client===x.curr.id.client){const y=f.curr.id.clock-x.curr.id.clock;return y===0?f.curr.constructor===x.curr.constructor?0:f.curr.constructor===Ke?1:-1:y}else return x.curr.id.client-f.curr.id.client}),i.length!==0;){const g=i[0],u=g.curr.id.client;if(o!==null){let f=g.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=g.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)yt(d,o.struct,o.offset),o={struct:f,offset:0},g.next();else if(o.struct.id.clock+o.struct.length<f.id.clock)if(o.struct.constructor===Ke)o.struct.length=f.id.clock+f.length-o.struct.id.clock;else{yt(d,o.struct,o.offset);const y=f.id.clock-o.struct.id.clock-o.struct.length;o={struct:new Ke(me(u,o.struct.id.clock+o.struct.length),y),offset:0}}else{const y=o.struct.id.clock+o.struct.length-f.id.clock;y>0&&(o.struct.constructor===Ke?o.struct.length-=y:f=Wu(f,y)),o.struct.mergeWith(f)||(yt(d,o.struct,o.offset),o={struct:f,offset:0},g.next())}}else o={struct:g.curr,offset:0},g.next();for(let f=g.curr;f!==null&&f.id.client===u&&f.id.clock===o.struct.id.clock+o.struct.length&&f.constructor!==Ke;f=g.next())yt(d,o.struct,o.offset),o={struct:f,offset:0}}o!==null&&(yt(d,o.struct,o.offset),o=null),ni(d);const l=r.map(g=>Qr(g)),p=pu(l);return rs(c,p),c.toUint8Array()},Bu=(t,e,s=es,r=Rt)=>{const i=ya(e),o=new r,c=new si(o),d=new s(at(t)),l=new ti(d,!1);for(;l.curr;){const g=l.curr,u=g.id.client,f=i.get(u)||0;if(l.curr.constructor===Ke){l.next();continue}if(g.id.clock+g.length>f)for(yt(c,g,Dt(f-g.id.clock,0)),l.next();l.curr&&l.curr.id.client===u;)yt(c,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===u&&l.curr.id.clock+l.curr.length<=f;)l.next()}ni(c);const p=Qr(d);return rs(o,p),o.toUint8Array()},Sa=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Se(t.encoder.restEncoder)}),t.encoder.restEncoder=De(),t.written=0)},yt=(t,e,s)=>{t.written>0&&t.currClient!==e.id.client&&Sa(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),ie(t.encoder.restEncoder,e.id.clock+s)),e.write(t.encoder,s),t.written++},ni=t=>{Sa(t);const e=t.encoder.restEncoder;ie(e,t.clientStructs.length);for(let s=0;s<t.clientStructs.length;s++){const r=t.clientStructs[s];ie(e,r.written),kn(e,r.restEncoder)}},Uu=(t,e,s,r)=>{const i=new s(at(t)),o=new ti(i,!1),c=new r,d=new si(c);for(let p=o.curr;p!==null;p=o.next())yt(d,e(p),0);ni(d);const l=Qr(i);return rs(c,l),c.toUint8Array()},Fu=t=>Uu(t,ud,es,Rs),Wi="You must not compute changes after the event-handler fired.";class Mn{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=$u(this.currentTarget,this.target))}deletes(e){return ca(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ge(Wi);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,d;if(this.adds(o)){let l=o.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(o))if(l!==null&&this.deletes(l))c="delete",d=Bn(l.content.getContent());else return;else l!==null&&this.deletes(l)?(c="update",d=Bn(l.content.getContent())):(c="add",d=void 0)}else if(this.deletes(o))c="delete",d=Bn(o.content.getContent());else return;e.set(i,{action:c,oldValue:d})}}),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 Ge(Wi);const s=this.target,r=wt(),i=wt(),o=[];if(e={added:r,deleted:i,delta:o,keys:this.keys},this.transaction.changed.get(s).has(null)){let d=null;const l=()=>{d&&o.push(d)};for(let p=s._start;p!==null;p=p.right)p.deleted?this.deletes(p)&&!this.adds(p)&&((d===null||d.delete===void 0)&&(l(),d={delete:0}),d.delete+=p.length,i.add(p)):this.adds(p)?((d===null||d.insert===void 0)&&(l(),d={insert:[]}),d.insert=d.insert.concat(p.content.getContent()),r.add(p)):((d===null||d.retain===void 0)&&(l(),d={retain:0}),d.retain+=p.length);d!==null&&d.retain===void 0&&l()}this._changes=e}return e}}const $u=(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},Be=()=>{du("Invalid access: Add Yjs type to a document before reading data.")},ja=80;let ri=0;class zu{constructor(e,s){e.marker=!0,this.p=e,this.index=s,this.timestamp=ri++}}const Hu=t=>{t.timestamp=ri++},Ea=(t,e,s)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=s,t.timestamp=ri++},Vu=(t,e,s)=>{if(t.length>=ja){const r=t.reduce((i,o)=>i.timestamp<o.timestamp?i:o);return Ea(r,e,s),r}else{const r=new zu(e,s);return t.push(r),r}},On=(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)=>Hs(e-o.index)<Hs(e-c.index)?o:c);let r=t._start,i=0;for(s!==null&&(r=s.p,i=s.index,Hu(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&&Hs(s.index-i)<r.parent.length/ja?(Ea(s,r,i),s):Vu(t._searchMarker,r,i)},_s=(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=Dt(e,i.index+s))}},Pn=(t,e,s)=>{const r=t,i=e.changedParentTypes;for(;Ve(i,t,()=>[]).push(s),t._item!==null;)t=t._item.parent;xa(r._eH,s,e)};class We{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Li(),this._dEH=Li(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,s){this.doc=e,this._item=s}_copy(){throw Ze()}clone(){throw Ze()}_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){Ii(this._eH,e)}observeDeep(e){Ii(this._dEH,e)}unobserve(e){Di(this._eH,e)}unobserveDeep(e){Di(this._dEH,e)}toJSON(){}}const Na=(t,e,s)=>{t.doc??Be(),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 d=e;d<c.length&&r>0;d++)i.push(c[d]),r--;e=0}}o=o.right}return i},Ca=t=>{t.doc??Be();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},ks=(t,e)=>{let s=0,r=t._start;for(t.doc??Be();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}},Ta=(t,e)=>{const s=[];return ks(t,(r,i)=>{s.push(e(r,i,t))}),s},Gu=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}}}},Ra=(t,e)=>{t.doc??Be();const s=On(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}},sn=(t,e,s,r)=>{let i=s;const o=t.doc,c=o.clientID,d=o.store,l=s===null?e._start:s.right;let p=[];const g=()=>{p.length>0&&(i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new It(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(g(),u.constructor){case Uint8Array:case ArrayBuffer:i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new As(new Uint8Array(u))),i.integrate(t,0);break;case is:i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new Ls(u)),i.integrate(t,0);break;default:if(u instanceof We)i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new mt(u)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),g()},Aa=()=>Ge("Length exceeded!"),La=(t,e,s,r)=>{if(s>e._length)throw Aa();if(s===0)return e._searchMarker&&_s(e._searchMarker,s,r.length),sn(t,e,null,r);const i=s,o=On(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&&vt(t,me(c.id.client,c.id.clock+s));break}s-=c.length}return e._searchMarker&&_s(e._searchMarker,i,r.length),sn(t,e,c,r)},qu=(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 sn(t,e,i,s)},Ia=(t,e,s,r)=>{if(r===0)return;const i=s,o=r,c=On(e,s);let d=e._start;for(c!==null&&(d=c.p,s-=c.index);d!==null&&s>0;d=d.right)!d.deleted&&d.countable&&(s<d.length&&vt(t,me(d.id.client,d.id.clock+s)),s-=d.length);for(;r>0&&d!==null;)d.deleted||(r<d.length&&vt(t,me(d.id.client,d.id.clock+r)),d.delete(t),r-=d.length),d=d.right;if(r>0)throw Aa();e._searchMarker&&_s(e._searchMarker,i,-o+r)},nn=(t,e,s)=>{const r=e._map.get(s);r!==void 0&&r.delete(t)},ii=(t,e,s,r)=>{const i=e._map.get(s)||null,o=t.doc,c=o.clientID;let d;if(r==null)d=new It([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:d=new It([r]);break;case Uint8Array:d=new As(r);break;case is:d=new Ls(r);break;default:if(r instanceof We)d=new mt(r);else throw new Error("Unexpected content type")}new Te(me(c,Me(o.store,c)),i,i&&i.lastId,null,null,e,s,d).integrate(t,0)},oi=(t,e)=>{t.doc??Be();const s=t._map.get(e);return s!==void 0&&!s.deleted?s.content.getContent()[s.length-1]:void 0},Da=t=>{const e={};return t.doc??Be(),t._map.forEach((s,r)=>{s.deleted||(e[r]=s.content.getContent()[s.length-1])}),e},Ma=(t,e)=>{t.doc??Be();const s=t._map.get(e);return s!==void 0&&!s.deleted},Yu=(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&&$t(o,e)&&(s[i]=o.content.getContent()[o.length-1])}),s},Ds=t=>(t.doc??Be(),hu(t._map.entries(),e=>!e[1].deleted));class Ku extends Mn{}class Gt extends We{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const s=new Gt;return s.push(e),s}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Gt}clone(){const e=new Gt;return e.insert(0,this.toArray().map(s=>s instanceof We?s.clone():s)),e}get length(){return this.doc??Be(),this._length}_callObserver(e,s){super._callObserver(e,s),Pn(this,e,new Ku(this,e))}insert(e,s){this.doc!==null?we(this.doc,r=>{La(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}push(e){this.doc!==null?we(this.doc,s=>{qu(s,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,s=1){this.doc!==null?we(this.doc,r=>{Ia(r,this,e,s)}):this._prelimContent.splice(e,s)}get(e){return Ra(this,e)}toArray(){return Ca(this)}slice(e=0,s=this.length){return Na(this,e,s)}toJSON(){return this.map(e=>e instanceof We?e.toJSON():e)}map(e){return Ta(this,e)}forEach(e){ks(this,e)}[Symbol.iterator](){return Gu(this)}_write(e){e.writeTypeRef(wh)}}const Ju=t=>new Gt;class Xu extends Mn{constructor(e,s,r){super(e,s),this.keysChanged=r}}class At extends We{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,s){super._integrate(e,s),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new At}clone(){const e=new At;return this.forEach((s,r)=>{e.set(r,s instanceof We?s.clone():s)}),e}_callObserver(e,s){Pn(this,e,new Xu(this,e,s))}toJSON(){this.doc??Be();const e={};return this._map.forEach((s,r)=>{if(!s.deleted){const i=s.content.getContent()[s.length-1];e[r]=i instanceof We?i.toJSON():i}}),e}get size(){return[...Ds(this)].length}keys(){return qn(Ds(this),e=>e[0])}values(){return qn(Ds(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return qn(Ds(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Be(),this._map.forEach((s,r)=>{s.deleted||e(s.content.getContent()[s.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?we(this.doc,s=>{nn(s,this,e)}):this._prelimContent.delete(e)}set(e,s){return this.doc!==null?we(this.doc,r=>{ii(r,this,e,s)}):this._prelimContent.set(e,s),s}get(e){return oi(this,e)}has(e){return Ma(this,e)}clear(){this.doc!==null?we(this.doc,e=>{this.forEach(function(s,r,i){nn(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(vh)}}const Qu=t=>new At,bt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&ld(t,e);class gr{constructor(e,s,r,i){this.left=e,this.right=s,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Qe(),this.right.content.constructor){case Re:this.right.deleted||os(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const Bi=(t,e,s)=>{for(;e.right!==null&&s>0;){switch(e.right.content.constructor){case Re:e.right.deleted||os(e.currentAttributes,e.right.content);break;default:e.right.deleted||(s<e.right.length&&vt(t,me(e.right.id.client,e.right.id.clock+s)),e.index+=e.right.length,s-=e.right.length);break}e.left=e.right,e.right=e.right.right}return e},Ms=(t,e,s,r)=>{const i=new Map,o=r?On(e,s):null;if(o){const c=new gr(o.p.left,o.p,o.index,i);return Bi(t,c,s-o.index)}else{const c=new gr(null,e._start,0,i);return Bi(t,c,s)}},Oa=(t,e,s,r)=>{for(;s.right!==null&&(s.right.deleted===!0||s.right.content.constructor===Re&&bt(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,d)=>{const l=s.left,p=s.right,g=new Te(me(o,Me(i.store,o)),l,l&&l.lastId,p,p&&p.id,e,null,new Re(d,c));g.integrate(t,0),s.right=g,s.forward()})},os=(t,e)=>{const{key:s,value:r}=e;r===null?t.delete(s):t.set(s,r)},Pa=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Re&&bt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Wa=(t,e,s,r)=>{const i=t.doc,o=i.clientID,c=new Map;for(const d in r){const l=r[d],p=s.currentAttributes.get(d)??null;if(!bt(p,l)){c.set(d,p);const{left:g,right:u}=s;s.right=new Te(me(o,Me(i.store,o)),g,g&&g.lastId,u,u&&u.id,e,null,new Re(d,l)),s.right.integrate(t,0),s.forward()}}return c},Kn=(t,e,s,r,i)=>{s.currentAttributes.forEach((f,x)=>{i[x]===void 0&&(i[x]=null)});const o=t.doc,c=o.clientID;Pa(s,i);const d=Wa(t,e,s,i),l=r.constructor===String?new ot(r):r instanceof We?new mt(r):new Mt(r);let{left:p,right:g,index:u}=s;e._searchMarker&&_s(e._searchMarker,s.index,l.getLength()),g=new Te(me(c,Me(o.store,c)),p,p&&p.lastId,g,g&&g.id,e,null,l),g.integrate(t,0),s.right=g,s.index=u,s.forward(),Oa(t,e,s,d)},Ui=(t,e,s,r,i)=>{const o=t.doc,c=o.clientID;Pa(s,i);const d=Wa(t,e,s,i);e:for(;s.right!==null&&(r>0||d.size>0&&(s.right.deleted||s.right.content.constructor===Re));){if(!s.right.deleted)switch(s.right.content.constructor){case Re:{const{key:l,value:p}=s.right.content,g=i[l];if(g!==void 0){if(bt(g,p))d.delete(l);else{if(r===0)break e;d.set(l,p)}s.right.delete(t)}else s.currentAttributes.set(l,p);break}default:r<s.right.length&&vt(t,me(s.right.id.client,s.right.id.clock+r)),r-=s.right.length;break}s.forward()}if(r>0){let l="";for(;r>0;r--)l+=`
60
- `;s.right=new Te(me(c,Me(o.store,c)),s.left,s.left&&s.left.lastId,s.right,s.right&&s.right.id,e,null,new ot(l)),s.right.integrate(t,0),s.forward()}Oa(t,e,s,d)},Ba=(t,e,s,r,i)=>{let o=e;const c=Fe();for(;o&&(!o.countable||o.deleted);){if(!o.deleted&&o.content.constructor===Re){const p=o.content;c.set(p.key,p)}o=o.right}let d=0,l=!1;for(;e!==o;){if(s===e&&(l=!0),!e.deleted){const p=e.content;switch(p.constructor){case Re:{const{key:g,value:u}=p,f=r.get(g)??null;(c.get(g)!==p||f===u)&&(e.delete(t),d++,!l&&(i.get(g)??null)===u&&f!==u&&(f===null?i.delete(g):i.set(g,f))),!l&&!e.deleted&&os(i,p);break}}}e=e.right}return d},Zu=(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===Re){const r=e.content.key;s.has(r)?e.delete(t):s.add(r)}e=e.left}},eh=t=>{let e=0;return we(t.doc,s=>{let r=t._start,i=t._start,o=Fe();const c=lr(o);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Re:os(c,i.content);break;default:e+=Ba(s,r,i,o,c),o=lr(c),r=i;break}i=i.right}}),e},th=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&&_a(t,s.store.clients.get(r),o,i,c=>{!c.deleted&&c.content.constructor===Re&&c.constructor!==Ye&&e.add(c.parent)})}we(s,r=>{la(t,t.deleteSet,i=>{if(i instanceof Ye||!i.parent._hasFormatting||e.has(i.parent))return;const o=i.parent;i.content.constructor===Re?e.add(o):Zu(r,i)});for(const i of e)eh(i)})},Fi=(t,e,s)=>{const r=s,i=lr(e.currentAttributes),o=e.right;for(;s>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case mt:case Mt:case ot:s<e.right.length&&vt(t,me(e.right.id.client,e.right.id.clock+s)),s-=e.right.length,e.right.delete(t);break}e.forward()}o&&Ba(t,o,e.right,i,e.currentAttributes);const c=(e.left||e.right).parent;return c._searchMarker&&_s(c._searchMarker,e.index,-r+s),e};class sh extends Mn{constructor(e,s,r){super(e,s),this.childListChanged=!1,this.keysChanged=new Set,r.forEach(i=>{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,s=[];we(e,r=>{const i=new Map,o=new Map;let c=this.target._start,d=null;const l={};let p="",g=0,u=0;const f=()=>{if(d!==null){let x=null;switch(d){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((y,E)=>{y!==null&&(x.attributes[E]=y)}))),p="";break;case"retain":g>0&&(x={retain:g},ad(l)||(x.attributes=rd({},l))),g=0;break}x&&s.push(x),d=null}};for(;c!==null;){switch(c.content.constructor){case mt:case Mt:this.adds(c)?this.deletes(c)||(f(),d="insert",p=c.content.getContent()[0],f()):this.deletes(c)?(d!=="delete"&&(f(),d="delete"),u+=1):c.deleted||(d!=="retain"&&(f(),d="retain"),g+=1);break;case ot:this.adds(c)?this.deletes(c)||(d!=="insert"&&(f(),d="insert"),p+=c.content.str):this.deletes(c)?(d!=="delete"&&(f(),d="delete"),u+=c.length):c.deleted||(d!=="retain"&&(f(),d="retain"),g+=c.length);break;case Re:{const{key:x,value:y}=c.content;if(this.adds(c)){if(!this.deletes(c)){const E=i.get(x)??null;bt(E,y)?y!==null&&c.delete(r):(d==="retain"&&f(),bt(y,o.get(x)??null)?delete l[x]:l[x]=y)}}else if(this.deletes(c)){o.set(x,y);const E=i.get(x)??null;bt(E,y)||(d==="retain"&&f(),l[x]=E)}else if(!c.deleted){o.set(x,y);const E=l[x];E!==void 0&&(bt(E,y)?E!==null&&c.delete(r):(d==="retain"&&f(),y===null?delete l[x]:l[x]=y))}c.deleted||(d==="insert"&&f(),os(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 ts extends We{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Be(),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 ts}clone(){const e=new ts;return e.applyDelta(this.toDelta()),e}_callObserver(e,s){super._callObserver(e,s);const r=new sh(this,e,s);Pn(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Be();let e="",s=this._start;for(;s!==null;)!s.deleted&&s.countable&&s.content.constructor===ot&&(e+=s.content.str),s=s.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:s=!0}={}){this.doc!==null?we(this.doc,r=>{const i=new gr(null,this._start,0,new Map);for(let o=0;o<e.length;o++){const c=e[o];if(c.insert!==void 0){const d=!s&&typeof c.insert=="string"&&o===e.length-1&&i.right===null&&c.insert.slice(-1)===`
61
- `?c.insert.slice(0,-1):c.insert;(typeof d!="string"||d.length>0)&&Kn(r,this,i,d,c.attributes||{})}else c.retain!==void 0?Ui(r,this,i,c.retain,c.attributes||{}):c.delete!==void 0&&Fi(r,i,c.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,s,r){this.doc??Be();const i=[],o=new Map,c=this.doc;let d="",l=this._start;function p(){if(d.length>0){const u={};let f=!1;o.forEach((y,E)=>{f=!0,u[E]=y});const x={insert:d};f&&(x.attributes=u),i.push(x),d=""}}const g=()=>{for(;l!==null;){if($t(l,e)||s!==void 0&&$t(l,s))switch(l.content.constructor){case ot:{const u=o.get("ychange");e!==void 0&&!$t(l,e)?(u===void 0||u.user!==l.id.client||u.type!=="removed")&&(p(),o.set("ychange",r?r("removed",l.id):{type:"removed"})):s!==void 0&&!$t(l,s)?(u===void 0||u.user!==l.id.client||u.type!=="added")&&(p(),o.set("ychange",r?r("added",l.id):{type:"added"})):u!==void 0&&(p(),o.delete("ychange")),d+=l.content.str;break}case mt:case Mt:{p();const u={insert:l.content.getContent()[0]};if(o.size>0){const f={};u.attributes=f,o.forEach((x,y)=>{f[y]=x})}i.push(u);break}case Re:$t(l,e)&&(p(),os(o,l.content));break}l=l.right}p()};return e||s?we(c,u=>{e&&pr(u,e),s&&pr(u,s),g()},"cleanup"):g(),i}insert(e,s,r){if(s.length<=0)return;const i=this.doc;i!==null?we(i,o=>{const c=Ms(o,this,e,!r);r||(r={},c.currentAttributes.forEach((d,l)=>{r[l]=d})),Kn(o,this,c,s,r)}):this._pending.push(()=>this.insert(e,s,r))}insertEmbed(e,s,r){const i=this.doc;i!==null?we(i,o=>{const c=Ms(o,this,e,!r);Kn(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?we(r,i=>{Fi(i,Ms(i,this,e,!0),s)}):this._pending.push(()=>this.delete(e,s))}format(e,s,r){if(s===0)return;const i=this.doc;i!==null?we(i,o=>{const c=Ms(o,this,e,!1);c.right!==null&&Ui(o,this,c,s,r)}):this._pending.push(()=>this.format(e,s,r))}removeAttribute(e){this.doc!==null?we(this.doc,s=>{nn(s,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,s){this.doc!==null?we(this.doc,r=>{ii(r,this,e,s)}):this._pending.push(()=>this.setAttribute(e,s))}getAttribute(e){return oi(this,e)}getAttributes(){return Da(this)}_write(e){e.writeTypeRef(_h)}}const nh=t=>new ts;class Jn{constructor(e,s=()=>!0){this._filter=s,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Be()}[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===ss||s.constructor===Lt)&&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 Lt extends We{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 Lt}clone(){const e=new Lt;return e.insert(0,this.toArray().map(s=>s instanceof We?s.clone():s)),e}get length(){return this.doc??Be(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Jn(this,e)}querySelector(e){e=e.toUpperCase();const r=new Jn(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),ut(new Jn(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e))}_callObserver(e,s){Pn(this,e,new oh(this,s,e))}toString(){return Ta(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),ks(this,o=>{i.insertBefore(o.toDOM(e,s,r),null)}),i}insert(e,s){this.doc!==null?we(this.doc,r=>{La(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}insertAfter(e,s){if(this.doc!==null)we(this.doc,r=>{const i=e&&e instanceof We?e._item:e;sn(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 Ge("Reference item not found");r.splice(i,0,...s)}}delete(e,s=1){this.doc!==null?we(this.doc,r=>{Ia(r,this,e,s)}):this._prelimContent.splice(e,s)}toArray(){return Ca(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Ra(this,e)}slice(e=0,s=this.length){return Na(this,e,s)}forEach(e){ks(this,e)}_write(e){e.writeTypeRef(Sh)}}const rh=t=>new Lt;class ss extends Lt{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 ss(this.nodeName)}clone(){const e=new ss(this.nodeName),s=this.getAttributes();return od(s,(r,i)=>{e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof We?r.clone():r)),e}toString(){const e=this.getAttributes(),s=[],r=[];for(const d in e)r.push(d);r.sort();const i=r.length;for(let d=0;d<i;d++){const l=r[d];s.push(l+'="'+e[l]+'"')}const o=this.nodeName.toLocaleLowerCase(),c=s.length>0?" "+s.join(" "):"";return`<${o}${c}>${super.toString()}</${o}>`}removeAttribute(e){this.doc!==null?we(this.doc,s=>{nn(s,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,s){this.doc!==null?we(this.doc,r=>{ii(r,this,e,s)}):this._prelimAttrs.set(e,s)}getAttribute(e){return oi(this,e)}hasAttribute(e){return Ma(this,e)}getAttributes(e){return e?Yu(this,e):Da(this)}toDOM(e=document,s={},r){const i=e.createElement(this.nodeName),o=this.getAttributes();for(const c in o){const d=o[c];typeof d=="string"&&i.setAttribute(c,d)}return ks(this,c=>{i.appendChild(c.toDOM(e,s,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(kh),e.writeKey(this.nodeName)}}const ih=t=>new ss(t.readKey());class oh extends Mn{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 rn extends At{constructor(e){super(),this.hookName=e}_copy(){return new rn(this.hookName)}clone(){const e=new rn(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(jh),e.writeKey(this.hookName)}}const ah=t=>new rn(t.readKey());class on extends ts{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 on}clone(){const e=new on;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,d)=>c.key<d.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 d=o.attrs[c];r+=` ${d.key}="${d.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(Eh)}}const lh=t=>new on;class ai{constructor(e,s){this.id=e,this.length=s}get deleted(){throw Ze()}mergeWith(e){return!1}write(e,s,r){throw Ze()}integrate(e,s){throw Ze()}}const ch=0;class Ye extends ai{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),va(e.doc.store,this)}write(e,s){e.writeInfo(ch),e.writeLen(this.length-s)}getMissing(e,s){return null}}class As{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new As(this.content)}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeBuf(this.content)}getRef(){return 3}}const dh=t=>new As(t.readBuf());class Ss{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ss(this.len)}splice(e){const s=new Ss(this.len-e);return this.len=e,s}mergeWith(e){return this.len+=e.len,!0}integrate(e,s){en(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 uh=t=>new Ss(t.readLen()),Ua=(t,e)=>new is({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Ls{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 Ls(Ua(this.doc.guid,this.opts))}splice(e){throw Ze()}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 hh=t=>new Ls(Ua(t.readString(),t.readAny()));class Mt{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Mt(this.embed)}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeJSON(this.embed)}getRef(){return 5}}const fh=t=>new Mt(t.readJSON());class Re{constructor(e,s){this.key=e,this.value=s}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Re(this.key,this.value)}splice(e){throw Ze()}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 ph=t=>new Re(t.readKey(),t.readJSON());class an{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new an(this.arr)}splice(e){const s=new an(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 mh=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 an(s)},gh=ws("node_env")==="development";class It{constructor(e){this.arr=e,gh&&Ao(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new It(this.arr)}splice(e){const s=new It(this.arr.slice(e));return this.arr=this.arr.slice(0,e),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){const r=this.arr.length;e.writeLen(r-s);for(let i=s;i<r;i++){const o=this.arr[i];e.writeAny(o)}}getRef(){return 8}}const yh=t=>{const e=t.readLen(),s=[];for(let r=0;r<e;r++)s.push(t.readAny());return new It(s)};class ot{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new ot(this.str)}splice(e){const s=new ot(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 bh=t=>new ot(t.readString()),xh=[Ju,Qu,nh,ih,rh,ah,lh],wh=0,vh=1,_h=2,kh=3,Sh=4,jh=5,Eh=6;class mt{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new mt(this.type._copy())}splice(e){throw Ze()}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 Nh=t=>new mt(xh[t.readTypeRef()](t)),ln=(t,e,s)=>{const{client:r,clock:i}=e.id,o=new Te(me(r,i+s),e,me(r,i+s-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(s));return e.deleted&&o.markDeleted(),e.keep&&(o.keep=!0),e.redone!==null&&(o.redone=me(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 Te extends ai{constructor(e,s,r,i,o,c,d,l){super(e,l.getLength()),this.origin=r,this.left=s,this.right=i,this.rightOrigin=o,this.parent=c,this.parentSub=d,this.redone=null,this.content=l,this.info=this.content.isCountable()?bi:0}set marker(e){(this.info&Fn)>0!==e&&(this.info^=Fn)}get marker(){return(this.info&Fn)>0}get keep(){return(this.info&yi)>0}set keep(e){this.keep!==e&&(this.info^=yi)}get countable(){return(this.info&bi)>0}get deleted(){return(this.info&Un)>0}set deleted(e){this.deleted!==e&&(this.info^=Un)}markDeleted(){this.info|=Un}getMissing(e,s){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Me(s,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Me(s,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Vt&&this.id.client!==this.parent.client&&this.parent.clock>=Me(s,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Mi(e,s,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=vt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ye||this.right&&this.right.constructor===Ye)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Te?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Te&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Vt){const r=Yn(s,this.parent);r.constructor===Ye?this.parent=null:this.parent=r.content.type}return null}integrate(e,s){if(s>0&&(this.id.clock+=s,this.left=Mi(e,e.doc.store,me(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(s),this.length-=s),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const o=new Set,c=new Set;for(;i!==null&&i!==this.right;){if(c.add(i),o.add(i),Is(this.origin,i.origin)){if(i.id.client<this.id.client)r=i,o.clear();else if(Is(this.rightOrigin,i.rightOrigin))break}else if(i.origin!==null&&c.has(Yn(e.doc.store,i.origin)))o.has(Yn(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),va(e.doc.store,this),this.content.integrate(e,this),Pi(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Ye(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:me(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Is(e.origin,this.lastId)&&this.right===e&&Is(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(),en(e.deleteSet,this.id.client,this.id.clock,this.length),Pi(e,s,this.parentSub),this.content.delete(e)}}gc(e,s){if(!this.deleted)throw Qe();this.content.gc(e),s?Lu(e,this,new Ye(this.id,this.length)):this.content=new Ss(this.length)}write(e,s){const r=s>0?me(this.id.client,this.id.clock+s-1):this.origin,i=this.rightOrigin,o=this.parentSub,c=this.content.getRef()&_n|(r===null?0:He)|(i===null?0:ct)|(o===null?0:gs);if(e.writeInfo(c),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const d=this.parent;if(d._item!==void 0){const l=d._item;if(l===null){const p=Ru(d);e.writeParentInfo(!0),e.writeString(p)}else e.writeParentInfo(!1),e.writeLeftID(l.id)}else d.constructor===String?(e.writeParentInfo(!0),e.writeString(d)):d.constructor===Vt?(e.writeParentInfo(!1),e.writeLeftID(d)):Qe();o!==null&&e.writeString(o)}this.content.write(e,s)}}const Fa=(t,e)=>Ch[e&_n](t),Ch=[()=>{Qe()},uh,mh,dh,bh,fh,ph,Nh,yh,hh,()=>{Qe()}],Th=10;class Ke extends ai{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,s){Qe()}write(e,s){e.writeInfo(Th),ie(e.restEncoder,this.length-s)}getMissing(e,s){return null}}const $a=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},za="__ $YJS$ __";$a[za]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");$a[za]=!0;const Ot=t=>Xt((e,s)=>{t.onerror=r=>s(new Error(r.target.error)),t.onsuccess=r=>e(r.target.result)}),Rh=(t,e)=>Xt((s,r)=>{const i=indexedDB.open(t);i.onupgradeneeded=o=>e(o.target.result),i.onerror=o=>r(Ge(o.target.error)),i.onsuccess=o=>{const c=o.target.result;c.onversionchange=()=>{c.close()},s(c)}}),Ah=t=>Ot(indexedDB.deleteDatabase(t)),Lh=(t,e)=>e.forEach(s=>t.createObjectStore.apply(t,s)),ds=(t,e,s="readwrite")=>{const r=t.transaction(e,s);return e.map(i=>Uh(r,i))},Ha=(t,e)=>Ot(t.count(e)),Ih=(t,e)=>Ot(t.get(e)),Va=(t,e)=>Ot(t.delete(e)),Dh=(t,e,s)=>Ot(t.put(e,s)),yr=(t,e)=>Ot(t.add(e)),Mh=(t,e,s)=>Ot(t.getAll(e,s)),Oh=(t,e,s)=>{let r=null;return Bh(t,e,i=>(r=i,!1),s).then(()=>r)},Ph=(t,e=null)=>Oh(t,e,"prev"),Wh=(t,e)=>Xt((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()}}),Bh=(t,e,s,r="next")=>Wh(t.openKeyCursor(e,r),i=>s(i.key)),Uh=(t,e)=>t.objectStore(e),Fh=(t,e)=>IDBKeyRange.upperBound(t,e),$h=(t,e)=>IDBKeyRange.lowerBound(t,e),Xn="custom",Ga="updates",qa=500,Ya=(t,e=()=>{},s=()=>{})=>{const[r]=ds(t.db,[Ga]);return Mh(r,$h(t._dbref,!1)).then(i=>{t._destroyed||(e(r),we(t.doc,()=>{i.forEach(o=>ga(t.doc,o))},t,!1),s(r))}).then(()=>Ph(r).then(i=>{t._dbref=i+1})).then(()=>Ha(r).then(i=>{t._dbsize=i})).then(()=>r)},zh=(t,e=!0)=>Ya(t).then(s=>{(e||t._dbsize>=qa)&&yr(s,ei(t.doc)).then(()=>Va(s,Fh(t._dbref,!0))).then(()=>Ha(s).then(r=>{t._dbsize=r}))});class Hh extends Or{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=Rh(e,r=>Lh(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Xt(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,Ya(this,c=>yr(c,ei(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]=ds(this.db,[Ga]);yr(o,r),++this._dbsize>=qa&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{zh(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(()=>{Ah(this.name)})}get(e){return this._db.then(s=>{const[r]=ds(s,[Xn],"readonly");return Ih(r,e)})}set(e,s){return this._db.then(r=>{const[i]=ds(r,[Xn]);return Dh(i,s,e)})}del(e){return this._db.then(s=>{const[r]=ds(s,[Xn]);return Va(r,e)})}}const Vh=1200,Gh=2500,cn=3e4,br=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=ht();const d=c.data,l=typeof d=="string"?JSON.parse(d):d;l&&l.type==="pong"&&(clearTimeout(r),r=setTimeout(o,cn/2)),t.emit("message",[l,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(br,Pr(vc(t.unsuccessfulReconnects+1)*Vh,Gh),t)),clearTimeout(r)},o=()=>{t.ws===e&&t.send({type:"ping"})};e.onclose=()=>i(null),e.onerror=c=>i(c),e.onopen=()=>{t.lastMessageReceived=ht(),t.connecting=!1,t.connected=!0,t.unsuccessfulReconnects=0,t.emit("connect",[{type:"connect"},t]),r=setTimeout(o,cn/2)}}};class qh extends Or{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&&cn<ht()-this.lastMessageReceived&&this.ws.close()},cn/2),br(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&&br(this)}}const Ka=new Map;class Yh{constructor(e){this.room=e,this.onmessage=null,this._onChange=s=>s.key===e&&this.onmessage!==null&&this.onmessage({data:Po(s.newValue||"")}),td(this._onChange)}postMessage(e){To.setItem(this.room,Oo(bd(e)))}close(){sd(this._onChange)}}const Kh=typeof BroadcastChannel>"u"?Yh:BroadcastChannel,li=t=>Ve(Ka,t,()=>{const e=wt(),s=new Kh(t);return s.onmessage=r=>e.forEach(i=>i(r.data,"broadcastchannel")),{bc:s,subs:e}}),Jh=(t,e)=>(li(t).subs.add(e),e),Xh=(t,e)=>{const s=li(t),r=s.subs.delete(e);return r&&s.subs.size===0&&(s.bc.close(),Ka.delete(t)),r},Qh=(t,e,s=null)=>{const r=li(t);r.bc.postMessage(e),r.subs.forEach(i=>i(e,s))},Zh=()=>{let t=!0;return(e,s)=>{if(t){t=!1;try{e()}finally{t=!0}}else s!==void 0&&s()}};function Os(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 Qn={exports:{}},$i;function ef(){return $i||($i=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,d,l){function p(f,x){if(!d[f]){if(!c[f]){var y=typeof Os=="function"&&Os;if(!x&&y)return y(f,!0);if(g)return g(f,!0);var E=new Error("Cannot find module '"+f+"'");throw E.code="MODULE_NOT_FOUND",E}var L=d[f]={exports:{}};c[f][0].call(L.exports,function(v){var A=c[f][1][v];return p(A||v)},L,L.exports,o,c,d,l)}return d[f].exports}for(var g=typeof Os=="function"&&Os,u=0;u<l.length;u++)p(l[u]);return p}return o})()({1:[function(o,c,d){function l(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 S=T===_?0:4-T%4;return[T,S]}function p(k,_,T){return 3*(_+T)/4-T}function g(k){var _,T,S=l(k),C=S[0],D=S[1],j=new L(p(k,C,D)),R=0,P=0<D?C-4:C;for(T=0;T<P;T+=4)_=E[k.charCodeAt(T)]<<18|E[k.charCodeAt(T+1)]<<12|E[k.charCodeAt(T+2)]<<6|E[k.charCodeAt(T+3)],j[R++]=255&_>>16,j[R++]=255&_>>8,j[R++]=255&_;return D===2&&(_=E[k.charCodeAt(T)]<<2|E[k.charCodeAt(T+1)]>>4,j[R++]=255&_),D===1&&(_=E[k.charCodeAt(T)]<<10|E[k.charCodeAt(T+1)]<<4|E[k.charCodeAt(T+2)]>>2,j[R++]=255&_>>8,j[R++]=255&_),j}function u(k){return y[63&k>>18]+y[63&k>>12]+y[63&k>>6]+y[63&k]}function f(k,_,T){for(var S,C=[],D=_;D<T;D+=3)S=(16711680&k[D]<<16)+(65280&k[D+1]<<8)+(255&k[D+2]),C.push(u(S));return C.join("")}function x(k){for(var _,T=k.length,S=T%3,C=[],D=16383,j=0,R=T-S;j<R;j+=D)C.push(f(k,j,j+D>R?R:j+D));return S===1?(_=k[T-1],C.push(y[_>>2]+y[63&_<<4]+"==")):S===2&&(_=(k[T-2]<<8)+k[T-1],C.push(y[_>>10]+y[63&_>>4]+y[63&_<<2]+"=")),C.join("")}d.byteLength=function(k){var _=l(k),T=_[0],S=_[1];return 3*(T+S)/4-S},d.toByteArray=g,d.fromByteArray=x;for(var y=[],E=[],L=typeof Uint8Array>"u"?Array:Uint8Array,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",A=0,m=v.length;A<m;++A)y[A]=v[A],E[v.charCodeAt(A)]=A;E[45]=62,E[95]=63},{}],2:[function(){},{}],3:[function(o,c,d){(function(){(function(){var l=String.fromCharCode,p=Math.min;function g(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,b){if(typeof a=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return E(a)}return f(a,h,b)}function f(a,h,b){if(typeof a=="string")return L(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(M(a,ArrayBuffer)||a&&M(a.buffer,ArrayBuffer))return A(a,h,b);if(typeof a=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var I=a.valueOf&&a.valueOf();if(I!=null&&I!==a)return u.from(I,h,b);var O=m(a);if(O)return O;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof a[Symbol.toPrimitive]=="function")return u.from(a[Symbol.toPrimitive]("string"),h,b);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 y(a,h,b){return x(a),0>=a||h===void 0?g(a):typeof b=="string"?g(a).fill(h,b):g(a).fill(h)}function E(a){return x(a),g(0>a?0:0|k(a))}function L(a,h){if((typeof h!="string"||h==="")&&(h="utf8"),!u.isEncoding(h))throw new TypeError("Unknown encoding: "+h);var b=0|_(a,h),I=g(b),O=I.write(a,h);return O!==b&&(I=I.slice(0,O)),I}function v(a){for(var h=0>a.length?0:0|k(a.length),b=g(h),I=0;I<h;I+=1)b[I]=255&a[I];return b}function A(a,h,b){if(0>h||a.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(a.byteLength<h+(b||0))throw new RangeError('"length" is outside of buffer bounds');var I;return I=h===void 0&&b===void 0?new Uint8Array(a):b===void 0?new Uint8Array(a,h):new Uint8Array(a,h,b),I.__proto__=u.prototype,I}function m(a){if(u.isBuffer(a)){var h=0|k(a.length),b=g(h);return b.length===0||a.copy(b,0,0,h),b}return a.length===void 0?a.type==="Buffer"&&Array.isArray(a.data)?v(a.data):void 0:typeof a.length!="number"||W(a.length)?g(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)||M(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 b=a.length,I=2<arguments.length&&arguments[2]===!0;if(!I&&b===0)return 0;for(var O=!1;;)switch(h){case"ascii":case"latin1":case"binary":return b;case"utf8":case"utf-8":return ve(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*b;case"hex":return b>>>1;case"base64":return ee(a).length;default:if(O)return I?-1:ve(a).length;h=(""+h).toLowerCase(),O=!0}}function T(a,h,b){var I=!1;if((h===void 0||0>h)&&(h=0),h>this.length||((b===void 0||b>this.length)&&(b=this.length),0>=b)||(b>>>=0,h>>>=0,b<=h))return"";for(a||(a="utf8");;)switch(a){case"hex":return se(this,h,b);case"utf8":case"utf-8":return K(this,h,b);case"ascii":return F(this,h,b);case"latin1":case"binary":return V(this,h,b);case"base64":return H(this,h,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,h,b);default:if(I)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),I=!0}}function S(a,h,b){var I=a[h];a[h]=a[b],a[b]=I}function C(a,h,b,I,O){if(a.length===0)return-1;if(typeof b=="string"?(I=b,b=0):2147483647<b?b=2147483647:-2147483648>b&&(b=-2147483648),b=+b,W(b)&&(b=O?0:a.length-1),0>b&&(b=a.length+b),b>=a.length){if(O)return-1;b=a.length-1}else if(0>b)if(O)b=0;else return-1;if(typeof h=="string"&&(h=u.from(h,I)),u.isBuffer(h))return h.length===0?-1:D(a,h,b,I,O);if(typeof h=="number")return h&=255,typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(a,h,b):Uint8Array.prototype.lastIndexOf.call(a,h,b):D(a,[h],b,I,O);throw new TypeError("val must be string, number or Buffer")}function D(a,h,b,I,O){function U(Pt,as){return re===1?Pt[as]:Pt.readUInt16BE(as*re)}var re=1,fe=a.length,_e=h.length;if(I!==void 0&&(I=(I+"").toLowerCase(),I==="ucs2"||I==="ucs-2"||I==="utf16le"||I==="utf-16le")){if(2>a.length||2>h.length)return-1;re=2,fe/=2,_e/=2,b/=2}var pe;if(O){var ue=-1;for(pe=b;pe<fe;pe++)if(U(a,pe)!==U(h,ue===-1?0:pe-ue))ue!==-1&&(pe-=pe-ue),ue=-1;else if(ue===-1&&(ue=pe),pe-ue+1===_e)return ue*re}else for(b+_e>fe&&(b=fe-_e),pe=b;0<=pe;pe--){for(var Pe=!0,kt=0;kt<_e;kt++)if(U(a,pe+kt)!==U(h,kt)){Pe=!1;break}if(Pe)return pe}return-1}function j(a,h,b,I){b=+b||0;var O=a.length-b;I?(I=+I,I>O&&(I=O)):I=O;var U=h.length;I>U/2&&(I=U/2);for(var re,fe=0;fe<I;++fe){if(re=parseInt(h.substr(2*fe,2),16),W(re))return fe;a[b+fe]=re}return fe}function R(a,h,b,I){return ae(ve(h,a.length-b),a,b,I)}function P(a,h,b,I){return ae(X(h),a,b,I)}function B(a,h,b,I){return P(a,h,b,I)}function z(a,h,b,I){return ae(ee(h),a,b,I)}function J(a,h,b,I){return ae(Y(h,a.length-b),a,b,I)}function H(a,h,b){return h===0&&b===a.length?G.fromByteArray(a):G.fromByteArray(a.slice(h,b))}function K(a,h,b){b=p(a.length,b);for(var I=[],O=h;O<b;){var U=a[O],re=null,fe=239<U?4:223<U?3:191<U?2:1;if(O+fe<=b){var _e,pe,ue,Pe;fe===1?128>U&&(re=U):fe===2?(_e=a[O+1],(192&_e)==128&&(Pe=(31&U)<<6|63&_e,127<Pe&&(re=Pe))):fe===3?(_e=a[O+1],pe=a[O+2],(192&_e)==128&&(192&pe)==128&&(Pe=(15&U)<<12|(63&_e)<<6|63&pe,2047<Pe&&(55296>Pe||57343<Pe)&&(re=Pe))):fe===4&&(_e=a[O+1],pe=a[O+2],ue=a[O+3],(192&_e)==128&&(192&pe)==128&&(192&ue)==128&&(Pe=(15&U)<<18|(63&_e)<<12|(63&pe)<<6|63&ue,65535<Pe&&1114112>Pe&&(re=Pe)))}re===null?(re=65533,fe=1):65535<re&&(re-=65536,I.push(55296|1023&re>>>10),re=56320|1023&re),I.push(re),O+=fe}return $(I)}function $(a){var h=a.length;if(h<=4096)return l.apply(String,a);for(var b="",I=0;I<h;)b+=l.apply(String,a.slice(I,I+=4096));return b}function F(a,h,b){var I="";b=p(a.length,b);for(var O=h;O<b;++O)I+=l(127&a[O]);return I}function V(a,h,b){var I="";b=p(a.length,b);for(var O=h;O<b;++O)I+=l(a[O]);return I}function se(a,h,b){var I=a.length;(!h||0>h)&&(h=0),(!b||0>b||b>I)&&(b=I);for(var O="",U=h;U<b;++U)O+=xe(a[U]);return O}function q(a,h,b){for(var I=a.slice(h,b),O="",U=0;U<I.length;U+=2)O+=l(I[U]+256*I[U+1]);return O}function te(a,h,b){if(a%1!=0||0>a)throw new RangeError("offset is not uint");if(a+h>b)throw new RangeError("Trying to access beyond buffer length")}function Q(a,h,b,I,O,U){if(!u.isBuffer(a))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>O||h<U)throw new RangeError('"value" argument is out of bounds');if(b+I>a.length)throw new RangeError("Index out of range")}function be(a,h,b,I){if(b+I>a.length)throw new RangeError("Index out of range");if(0>b)throw new RangeError("Index out of range")}function Ce(a,h,b,I,O){return h=+h,b>>>=0,O||be(a,h,b,4),ne.write(a,h,b,I,23,4),b+4}function ce(a,h,b,I,O){return h=+h,b>>>=0,O||be(a,h,b,8),ne.write(a,h,b,I,52,8),b+8}function ye(a){if(a=a.split("=")[0],a=a.trim().replace(N,""),2>a.length)return"";for(;a.length%4!=0;)a+="=";return a}function xe(a){return 16>a?"0"+a.toString(16):a.toString(16)}function ve(a,h){h=h||1/0;for(var b,I=a.length,O=null,U=[],re=0;re<I;++re){if(b=a.charCodeAt(re),55295<b&&57344>b){if(!O){if(56319<b){-1<(h-=3)&&U.push(239,191,189);continue}else if(re+1===I){-1<(h-=3)&&U.push(239,191,189);continue}O=b;continue}if(56320>b){-1<(h-=3)&&U.push(239,191,189),O=b;continue}b=(O-55296<<10|b-56320)+65536}else O&&-1<(h-=3)&&U.push(239,191,189);if(O=null,128>b){if(0>(h-=1))break;U.push(b)}else if(2048>b){if(0>(h-=2))break;U.push(192|b>>6,128|63&b)}else if(65536>b){if(0>(h-=3))break;U.push(224|b>>12,128|63&b>>6,128|63&b)}else if(1114112>b){if(0>(h-=4))break;U.push(240|b>>18,128|63&b>>12,128|63&b>>6,128|63&b)}else throw new Error("Invalid code point")}return U}function X(a){for(var h=[],b=0;b<a.length;++b)h.push(255&a.charCodeAt(b));return h}function Y(a,h){for(var b,I,O,U=[],re=0;re<a.length&&!(0>(h-=2));++re)b=a.charCodeAt(re),I=b>>8,O=b%256,U.push(O),U.push(I);return U}function ee(a){return G.toByteArray(ye(a))}function ae(a,h,b,I){for(var O=0;O<I&&!(O+b>=h.length||O>=a.length);++O)h[O+b]=a[O];return O}function M(a,h){return a instanceof h||a!=null&&a.constructor!=null&&a.constructor.name!=null&&a.constructor.name===h.name}function W(a){return a!==a}var G=o("base64-js"),ne=o("ieee754");d.Buffer=u,d.SlowBuffer=function(a){return+a!=a&&(a=0),u.alloc(+a)},d.INSPECT_MAX_BYTES=50,d.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,b){return f(a,h,b)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(a,h,b){return y(a,h,b)},u.allocUnsafe=function(a){return E(a)},u.allocUnsafeSlow=function(a){return E(a)},u.isBuffer=function(a){return a!=null&&a._isBuffer===!0&&a!==u.prototype},u.compare=function(a,h){if(M(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),M(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 b=a.length,I=h.length,O=0,U=p(b,I);O<U;++O)if(a[O]!==h[O]){b=a[O],I=h[O];break}return b<I?-1:I<b?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 b;if(h===void 0)for(h=0,b=0;b<a.length;++b)h+=a[b].length;var I=u.allocUnsafe(h),O=0;for(b=0;b<a.length;++b){var U=a[b];if(M(U,Uint8Array)&&(U=u.from(U)),!u.isBuffer(U))throw new TypeError('"list" argument must be an Array of Buffers');U.copy(I,O),O+=U.length}return I},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)S(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)S(this,h,h+3),S(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)S(this,h,h+7),S(this,h+1,h+6),S(this,h+2,h+5),S(this,h+3,h+4);return this},u.prototype.toString=function(){var a=this.length;return a===0?"":arguments.length===0?K(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=d.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,b,I,O){if(M(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),b===void 0&&(b=a?a.length:0),I===void 0&&(I=0),O===void 0&&(O=this.length),0>h||b>a.length||0>I||O>this.length)throw new RangeError("out of range index");if(I>=O&&h>=b)return 0;if(I>=O)return-1;if(h>=b)return 1;if(h>>>=0,b>>>=0,I>>>=0,O>>>=0,this===a)return 0;for(var U=O-I,re=b-h,fe=p(U,re),_e=this.slice(I,O),pe=a.slice(h,b),ue=0;ue<fe;++ue)if(_e[ue]!==pe[ue]){U=_e[ue],re=pe[ue];break}return U<re?-1:re<U?1:0},u.prototype.includes=function(a,h,b){return this.indexOf(a,h,b)!==-1},u.prototype.indexOf=function(a,h,b){return C(this,a,h,b,!0)},u.prototype.lastIndexOf=function(a,h,b){return C(this,a,h,b,!1)},u.prototype.write=function(a,h,b,I){if(h===void 0)I="utf8",b=this.length,h=0;else if(b===void 0&&typeof h=="string")I=h,b=this.length,h=0;else if(isFinite(h))h>>>=0,isFinite(b)?(b>>>=0,I===void 0&&(I="utf8")):(I=b,b=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var O=this.length-h;if((b===void 0||b>O)&&(b=O),0<a.length&&(0>b||0>h)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");I||(I="utf8");for(var U=!1;;)switch(I){case"hex":return j(this,a,h,b);case"utf8":case"utf-8":return R(this,a,h,b);case"ascii":return P(this,a,h,b);case"latin1":case"binary":return B(this,a,h,b);case"base64":return z(this,a,h,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return J(this,a,h,b);default:if(U)throw new TypeError("Unknown encoding: "+I);I=(""+I).toLowerCase(),U=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},u.prototype.slice=function(a,h){var b=this.length;a=~~a,h=h===void 0?b:~~h,0>a?(a+=b,0>a&&(a=0)):a>b&&(a=b),0>h?(h+=b,0>h&&(h=0)):h>b&&(h=b),h<a&&(h=a);var I=this.subarray(a,h);return I.__proto__=u.prototype,I},u.prototype.readUIntLE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var I=this[a],O=1,U=0;++U<h&&(O*=256);)I+=this[a+U]*O;return I},u.prototype.readUIntBE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var I=this[a+--h],O=1;0<h&&(O*=256);)I+=this[a+--h]*O;return I},u.prototype.readUInt8=function(a,h){return a>>>=0,h||te(a,1,this.length),this[a]},u.prototype.readUInt16LE=function(a,h){return a>>>=0,h||te(a,2,this.length),this[a]|this[a+1]<<8},u.prototype.readUInt16BE=function(a,h){return a>>>=0,h||te(a,2,this.length),this[a]<<8|this[a+1]},u.prototype.readUInt32LE=function(a,h){return a>>>=0,h||te(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||te(a,4,this.length),16777216*this[a]+(this[a+1]<<16|this[a+2]<<8|this[a+3])},u.prototype.readIntLE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var I=this[a],O=1,U=0;++U<h&&(O*=256);)I+=this[a+U]*O;return O*=128,I>=O&&(I-=i(2,8*h)),I},u.prototype.readIntBE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var I=h,O=1,U=this[a+--I];0<I&&(O*=256);)U+=this[a+--I]*O;return O*=128,U>=O&&(U-=i(2,8*h)),U},u.prototype.readInt8=function(a,h){return a>>>=0,h||te(a,1,this.length),128&this[a]?-1*(255-this[a]+1):this[a]},u.prototype.readInt16LE=function(a,h){a>>>=0,h||te(a,2,this.length);var b=this[a]|this[a+1]<<8;return 32768&b?4294901760|b:b},u.prototype.readInt16BE=function(a,h){a>>>=0,h||te(a,2,this.length);var b=this[a+1]|this[a]<<8;return 32768&b?4294901760|b:b},u.prototype.readInt32LE=function(a,h){return a>>>=0,h||te(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||te(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||te(a,4,this.length),ne.read(this,a,!0,23,4)},u.prototype.readFloatBE=function(a,h){return a>>>=0,h||te(a,4,this.length),ne.read(this,a,!1,23,4)},u.prototype.readDoubleLE=function(a,h){return a>>>=0,h||te(a,8,this.length),ne.read(this,a,!0,52,8)},u.prototype.readDoubleBE=function(a,h){return a>>>=0,h||te(a,8,this.length),ne.read(this,a,!1,52,8)},u.prototype.writeUIntLE=function(a,h,b,I){if(a=+a,h>>>=0,b>>>=0,!I){var O=i(2,8*b)-1;Q(this,a,h,b,O,0)}var U=1,re=0;for(this[h]=255&a;++re<b&&(U*=256);)this[h+re]=255&a/U;return h+b},u.prototype.writeUIntBE=function(a,h,b,I){if(a=+a,h>>>=0,b>>>=0,!I){var O=i(2,8*b)-1;Q(this,a,h,b,O,0)}var U=b-1,re=1;for(this[h+U]=255&a;0<=--U&&(re*=256);)this[h+U]=255&a/re;return h+b},u.prototype.writeUInt8=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,1,255,0),this[h]=255&a,h+1},u.prototype.writeUInt16LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,65535,0),this[h]=255&a,this[h+1]=a>>>8,h+2},u.prototype.writeUInt16BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,65535,0),this[h]=a>>>8,this[h+1]=255&a,h+2},u.prototype.writeUInt32LE=function(a,h,b){return a=+a,h>>>=0,b||Q(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,b){return a=+a,h>>>=0,b||Q(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,b,I){if(a=+a,h>>>=0,!I){var O=i(2,8*b-1);Q(this,a,h,b,O-1,-O)}var U=0,re=1,fe=0;for(this[h]=255&a;++U<b&&(re*=256);)0>a&&fe===0&&this[h+U-1]!==0&&(fe=1),this[h+U]=255&(a/re>>0)-fe;return h+b},u.prototype.writeIntBE=function(a,h,b,I){if(a=+a,h>>>=0,!I){var O=i(2,8*b-1);Q(this,a,h,b,O-1,-O)}var U=b-1,re=1,fe=0;for(this[h+U]=255&a;0<=--U&&(re*=256);)0>a&&fe===0&&this[h+U+1]!==0&&(fe=1),this[h+U]=255&(a/re>>0)-fe;return h+b},u.prototype.writeInt8=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,1,127,-128),0>a&&(a=255+a+1),this[h]=255&a,h+1},u.prototype.writeInt16LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,32767,-32768),this[h]=255&a,this[h+1]=a>>>8,h+2},u.prototype.writeInt16BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,32767,-32768),this[h]=a>>>8,this[h+1]=255&a,h+2},u.prototype.writeInt32LE=function(a,h,b){return a=+a,h>>>=0,b||Q(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,b){return a=+a,h>>>=0,b||Q(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,b){return Ce(this,a,h,!0,b)},u.prototype.writeFloatBE=function(a,h,b){return Ce(this,a,h,!1,b)},u.prototype.writeDoubleLE=function(a,h,b){return ce(this,a,h,!0,b)},u.prototype.writeDoubleBE=function(a,h,b){return ce(this,a,h,!1,b)},u.prototype.copy=function(a,h,b,I){if(!u.isBuffer(a))throw new TypeError("argument should be a Buffer");if(b||(b=0),I||I===0||(I=this.length),h>=a.length&&(h=a.length),h||(h=0),0<I&&I<b&&(I=b),I===b||a.length===0||this.length===0)return 0;if(0>h)throw new RangeError("targetStart out of bounds");if(0>b||b>=this.length)throw new RangeError("Index out of range");if(0>I)throw new RangeError("sourceEnd out of bounds");I>this.length&&(I=this.length),a.length-h<I-b&&(I=a.length-h+b);var O=I-b;if(this===a&&typeof Uint8Array.prototype.copyWithin=="function")this.copyWithin(h,b,I);else if(this===a&&b<h&&h<I)for(var U=O-1;0<=U;--U)a[U+h]=this[U+b];else Uint8Array.prototype.set.call(a,this.subarray(b,I),h);return O},u.prototype.fill=function(a,h,b,I){if(typeof a=="string"){if(typeof h=="string"?(I=h,h=0,b=this.length):typeof b=="string"&&(I=b,b=this.length),I!==void 0&&typeof I!="string")throw new TypeError("encoding must be a string");if(typeof I=="string"&&!u.isEncoding(I))throw new TypeError("Unknown encoding: "+I);if(a.length===1){var O=a.charCodeAt(0);(I==="utf8"&&128>O||I==="latin1")&&(a=O)}}else typeof a=="number"&&(a&=255);if(0>h||this.length<h||this.length<b)throw new RangeError("Out of range index");if(b<=h)return this;h>>>=0,b=b===void 0?this.length:b>>>0,a||(a=0);var U;if(typeof a=="number")for(U=h;U<b;++U)this[U]=a;else{var re=u.isBuffer(a)?a:u.from(a,I),fe=re.length;if(fe===0)throw new TypeError('The value "'+a+'" is invalid for argument "value"');for(U=0;U<b-h;++U)this[U+h]=re[U%fe]}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,d){(function(l){(function(){function p(){let u;try{u=d.storage.getItem("debug")}catch{}return!u&&typeof l<"u"&&"env"in l&&(u=l.env.DEBUG),u}d.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,y=0;u[0].replace(/%[a-zA-Z%]/g,E=>{E==="%%"||(x++,E==="%c"&&(y=x))}),u.splice(y,0,f)},d.save=function(u){try{u?d.storage.setItem("debug",u):d.storage.removeItem("debug")}catch{}},d.load=p,d.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+)/))},d.storage=(function(){try{return localStorage}catch{}})(),d.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`."))}})(),d.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"],d.log=console.debug||console.log||(()=>{}),c.exports=o("./common")(d);const{formatters:g}=c.exports;g.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(d){function l(u){function f(...E){if(!f.enabled)return;const L=f,v=+new Date,A=v-(x||v);L.diff=A,L.prev=x,L.curr=v,x=v,E[0]=l.coerce(E[0]),typeof E[0]!="string"&&E.unshift("%O");let m=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(_,T)=>{if(_==="%%")return"%";m++;const S=l.formatters[T];if(typeof S=="function"){const C=E[m];_=S.call(L,C),E.splice(m,1),m--}return _}),l.formatArgs.call(L,E),(L.log||l.log).apply(L,E)}let x,y=null;return f.namespace=u,f.useColors=l.useColors(),f.color=l.selectColor(u),f.extend=p,f.destroy=l.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>y===null?l.enabled(u):y,set:E=>{y=E}}),typeof l.init=="function"&&l.init(f),f}function p(u,f){const x=l(this.namespace+(typeof f>"u"?":":f)+u);return x.log=this.log,x}function g(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}return l.debug=l,l.default=l,l.coerce=function(u){return u instanceof Error?u.stack||u.message:u},l.disable=function(){const u=[...l.names.map(g),...l.skips.map(g).map(f=>"-"+f)].join(",");return l.enable(""),u},l.enable=function(u){l.save(u),l.names=[],l.skips=[];let f;const x=(typeof u=="string"?u:"").split(/[\s,]+/),y=x.length;for(f=0;f<y;f++)x[f]&&(u=x[f].replace(/\*/g,".*?"),u[0]==="-"?l.skips.push(new RegExp("^"+u.substr(1)+"$")):l.names.push(new RegExp("^"+u+"$")))},l.enabled=function(u){if(u[u.length-1]==="*")return!0;let f,x;for(f=0,x=l.skips.length;f<x;f++)if(l.skips[f].test(u))return!1;for(f=0,x=l.names.length;f<x;f++)if(l.names[f].test(u))return!0;return!1},l.humanize=o("ms"),l.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(d).forEach(u=>{l[u]=d[u]}),l.names=[],l.skips=[],l.formatters={},l.selectColor=function(u){let f=0;for(let x=0;x<u.length;x++)f=(f<<5)-f+u.charCodeAt(x),f|=0;return l.colors[r(f)%l.colors.length]},l.enable(l.load()),l}},{ms:11}],6:[function(o,c){function d(l,p){for(const g in p)Object.defineProperty(l,g,{value:p[g],enumerable:!0,configurable:!0});return l}c.exports=function(l,p,g){if(!l||typeof l=="string")throw new TypeError("Please pass an Error to err-code");g||(g={}),typeof p=="object"&&(g=p,p=""),p&&(g.code=p);try{return d(l,g)}catch{g.message=l.message,g.stack=l.stack;const f=function(){};return f.prototype=Object.create(Object.getPrototypeOf(l)),d(new f,g)}}},{}],7:[function(o,c){function d(j){console&&console.warn&&console.warn(j)}function l(){l.init.call(this)}function p(j){if(typeof j!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof j)}function g(j){return j._maxListeners===void 0?l.defaultMaxListeners:j._maxListeners}function u(j,R,P,B){var z,J,H;if(p(P),J=j._events,J===void 0?(J=j._events=Object.create(null),j._eventsCount=0):(J.newListener!==void 0&&(j.emit("newListener",R,P.listener?P.listener:P),J=j._events),H=J[R]),H===void 0)H=J[R]=P,++j._eventsCount;else if(typeof H=="function"?H=J[R]=B?[P,H]:[H,P]:B?H.unshift(P):H.push(P),z=g(j),0<z&&H.length>z&&!H.warned){H.warned=!0;var K=new Error("Possible EventEmitter memory leak detected. "+H.length+" "+(R+" listeners added. Use emitter.setMaxListeners() to increase limit"));K.name="MaxListenersExceededWarning",K.emitter=j,K.type=R,K.count=H.length,d(K)}return j}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(j,R,P){var B={fired:!1,wrapFn:void 0,target:j,type:R,listener:P},z=f.bind(B);return z.listener=P,B.wrapFn=z,z}function y(j,R,P){var B=j._events;if(B===void 0)return[];var z=B[R];return z===void 0?[]:typeof z=="function"?P?[z.listener||z]:[z]:P?A(z):L(z,z.length)}function E(j){var R=this._events;if(R!==void 0){var P=R[j];if(typeof P=="function")return 1;if(P!==void 0)return P.length}return 0}function L(j,R){for(var P=Array(R),B=0;B<R;++B)P[B]=j[B];return P}function v(j,R){for(;R+1<j.length;R++)j[R]=j[R+1];j.pop()}function A(j){for(var R=Array(j.length),P=0;P<R.length;++P)R[P]=j[P].listener||j[P];return R}function m(j,R,P){typeof j.on=="function"&&k(j,"error",R,P)}function k(j,R,P,B){if(typeof j.on=="function")B.once?j.once(R,P):j.on(R,P);else if(typeof j.addEventListener=="function")j.addEventListener(R,function z(J){B.once&&j.removeEventListener(R,z),P(J)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof j)}var _,T=typeof Reflect=="object"?Reflect:null,S=T&&typeof T.apply=="function"?T.apply:function(j,R,P){return Function.prototype.apply.call(j,R,P)};_=T&&typeof T.ownKeys=="function"?T.ownKeys:Object.getOwnPropertySymbols?function(j){return Object.getOwnPropertyNames(j).concat(Object.getOwnPropertySymbols(j))}:function(j){return Object.getOwnPropertyNames(j)};var C=Number.isNaN||function(j){return j!==j};c.exports=l,c.exports.once=function(j,R){return new Promise(function(P,B){function z(H){j.removeListener(R,J),B(H)}function J(){typeof j.removeListener=="function"&&j.removeListener("error",z),P([].slice.call(arguments))}k(j,R,J,{once:!0}),R!=="error"&&m(j,z,{once:!0})})},l.EventEmitter=l,l.prototype._events=void 0,l.prototype._eventsCount=0,l.prototype._maxListeners=void 0;var D=10;Object.defineProperty(l,"defaultMaxListeners",{enumerable:!0,get:function(){return D},set:function(j){if(typeof j!="number"||0>j||C(j))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+j+".");D=j}}),l.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},l.prototype.setMaxListeners=function(j){if(typeof j!="number"||0>j||C(j))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+j+".");return this._maxListeners=j,this},l.prototype.getMaxListeners=function(){return g(this)},l.prototype.emit=function(j){for(var R=[],P=1;P<arguments.length;P++)R.push(arguments[P]);var B=j==="error",z=this._events;if(z!==void 0)B=B&&z.error===void 0;else if(!B)return!1;if(B){var J;if(0<R.length&&(J=R[0]),J instanceof Error)throw J;var H=new Error("Unhandled error."+(J?" ("+J.message+")":""));throw H.context=J,H}var K=z[j];if(K===void 0)return!1;if(typeof K=="function")S(K,this,R);else for(var $=K.length,F=L(K,$),P=0;P<$;++P)S(F[P],this,R);return!0},l.prototype.addListener=function(j,R){return u(this,j,R,!1)},l.prototype.on=l.prototype.addListener,l.prototype.prependListener=function(j,R){return u(this,j,R,!0)},l.prototype.once=function(j,R){return p(R),this.on(j,x(this,j,R)),this},l.prototype.prependOnceListener=function(j,R){return p(R),this.prependListener(j,x(this,j,R)),this},l.prototype.removeListener=function(j,R){var P,B,z,J,H;if(p(R),B=this._events,B===void 0)return this;if(P=B[j],P===void 0)return this;if(P===R||P.listener===R)--this._eventsCount==0?this._events=Object.create(null):(delete B[j],B.removeListener&&this.emit("removeListener",j,P.listener||R));else if(typeof P!="function"){for(z=-1,J=P.length-1;0<=J;J--)if(P[J]===R||P[J].listener===R){H=P[J].listener,z=J;break}if(0>z)return this;z===0?P.shift():v(P,z),P.length===1&&(B[j]=P[0]),B.removeListener!==void 0&&this.emit("removeListener",j,H||R)}return this},l.prototype.off=l.prototype.removeListener,l.prototype.removeAllListeners=function(j){var R,P,B;if(P=this._events,P===void 0)return this;if(P.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):P[j]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete P[j]),this;if(arguments.length===0){var z,J=Object.keys(P);for(B=0;B<J.length;++B)z=J[B],z!=="removeListener"&&this.removeAllListeners(z);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(R=P[j],typeof R=="function")this.removeListener(j,R);else if(R!==void 0)for(B=R.length-1;0<=B;B--)this.removeListener(j,R[B]);return this},l.prototype.listeners=function(j){return y(this,j,!0)},l.prototype.rawListeners=function(j){return y(this,j,!1)},l.listenerCount=function(j,R){return typeof j.listenerCount=="function"?j.listenerCount(R):E.call(j,R)},l.prototype.listenerCount=E,l.prototype.eventNames=function(){return 0<this._eventsCount?_(this._events):[]}},{}],8:[function(o,c){c.exports=function(){if(typeof globalThis>"u")return null;var d={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return d.RTCPeerConnection?d:null}},{}],9:[function(o,c,d){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */d.read=function(l,p,g,u,f){var x,y,E=8*f-u-1,L=(1<<E)-1,v=L>>1,A=-7,m=g?f-1:0,k=g?-1:1,_=l[p+m];for(m+=k,x=_&(1<<-A)-1,_>>=-A,A+=E;0<A;x=256*x+l[p+m],m+=k,A-=8);for(y=x&(1<<-A)-1,x>>=-A,A+=u;0<A;y=256*y+l[p+m],m+=k,A-=8);if(x===0)x=1-v;else{if(x===L)return y?NaN:(_?-1:1)*(1/0);y+=i(2,u),x-=v}return(_?-1:1)*y*i(2,x-u)},d.write=function(l,p,g,u,f,x){var y,E,L,v=Math.LN2,A=Math.log,m=8*x-f-1,k=(1<<m)-1,_=k>>1,T=f===23?i(2,-24)-i(2,-77):0,S=u?0:x-1,C=u?1:-1,D=0>p||p===0&&0>1/p?1:0;for(p=r(p),isNaN(p)||p===1/0?(E=isNaN(p)?1:0,y=k):(y=s(A(p)/v),1>p*(L=i(2,-y))&&(y--,L*=2),p+=1<=y+_?T/L:T*i(2,1-_),2<=p*L&&(y++,L/=2),y+_>=k?(E=0,y=k):1<=y+_?(E=(p*L-1)*i(2,f),y+=_):(E=p*i(2,_-1)*i(2,f),y=0));8<=f;l[g+S]=255&E,S+=C,E/=256,f-=8);for(y=y<<f|E,m+=f;0<m;l[g+S]=255&y,S+=C,y/=256,m-=8);l[g+S-C]|=128*D}},{}],10:[function(o,c){c.exports=typeof Object.create=="function"?function(d,l){l&&(d.super_=l,d.prototype=Object.create(l.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}))}:function(d,l){if(l){d.super_=l;var p=function(){};p.prototype=l.prototype,d.prototype=new p,d.prototype.constructor=d}}},{}],11:[function(o,c){var d=Math.round;function l(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 y=parseFloat(x[1]),E=(x[2]||"ms").toLowerCase();return E==="years"||E==="year"||E==="yrs"||E==="yr"||E==="y"?315576e5*y:E==="weeks"||E==="week"||E==="w"?6048e5*y:E==="days"||E==="day"||E==="d"?864e5*y:E==="hours"||E==="hour"||E==="hrs"||E==="hr"||E==="h"?36e5*y:E==="minutes"||E==="minute"||E==="mins"||E==="min"||E==="m"?6e4*y:E==="seconds"||E==="second"||E==="secs"||E==="sec"||E==="s"?1e3*y:E==="milliseconds"||E==="millisecond"||E==="msecs"||E==="msec"||E==="ms"?y:void 0}}}function p(f){var x=r(f);return 864e5<=x?d(f/864e5)+"d":36e5<=x?d(f/36e5)+"h":6e4<=x?d(f/6e4)+"m":1e3<=x?d(f/1e3)+"s":f+"ms"}function g(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,y,E){return d(f/y)+" "+E+(x>=1.5*y?"s":"")}c.exports=function(f,x){x=x||{};var y=typeof f;if(y=="string"&&0<f.length)return l(f);if(y==="number"&&isFinite(f))return x.long?g(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 d(){throw new Error("setTimeout has not been defined")}function l(){throw new Error("clearTimeout has not been defined")}function p(T){if(E===setTimeout)return setTimeout(T,0);if((E===d||!E)&&setTimeout)return E=setTimeout,setTimeout(T,0);try{return E(T,0)}catch{try{return E.call(null,T,0)}catch{return E.call(this,T,0)}}}function g(T){if(L===clearTimeout)return clearTimeout(T);if((L===l||!L)&&clearTimeout)return L=clearTimeout,clearTimeout(T);try{return L(T)}catch{try{return L.call(null,T)}catch{return L.call(this,T)}}}function u(){k&&A&&(k=!1,A.length?m=A.concat(m):_=-1,m.length&&f())}function f(){if(!k){var T=p(u);k=!0;for(var S=m.length;S;){for(A=m,m=[];++_<S;)A&&A[_].run();_=-1,S=m.length}A=null,k=!1,g(T)}}function x(T,S){this.fun=T,this.array=S}function y(){}var E,L,v=c.exports={};(function(){try{E=typeof setTimeout=="function"?setTimeout:d}catch{E=d}try{L=typeof clearTimeout=="function"?clearTimeout:l}catch{L=l}})();var A,m=[],k=!1,_=-1;v.nextTick=function(T){var S=Array(arguments.length-1);if(1<arguments.length)for(var C=1;C<arguments.length;C++)S[C-1]=arguments[C];m.push(new x(T,S)),m.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=y,v.addListener=y,v.once=y,v.off=y,v.removeListener=y,v.removeAllListeners=y,v.emit=y,v.prependListener=y,v.prependOnceListener=y,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(d){(function(){/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let l;c.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window>"u"?d:window):p=>(l||(l=Promise.resolve())).then(p).catch(g=>setTimeout(()=>{throw g},0))}).call(this)}).call(this,typeof st>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:st)},{}],14:[function(o,c){(function(d,l){(function(){var p=o("safe-buffer").Buffer,g=l.crypto||l.msCrypto;c.exports=g&&g.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 y=0;y<u;y+=65536)g.getRandomValues(x.slice(y,y+65536));else g.getRandomValues(x);return typeof f=="function"?d.nextTick(function(){f(null,x)}):x}:function(){throw new Error(`Secure random number generation is not supported by this browser.
62
- Use Chrome, Firefox or Internet Explorer 11`)}}).call(this)}).call(this,o("_process"),typeof st>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:st)},{_process:12,"safe-buffer":30}],15:[function(o,c){function d(y,E){y.prototype=Object.create(E.prototype),y.prototype.constructor=y,y.__proto__=E}function l(y,E,L){function v(m,k,_){return typeof E=="string"?E:E(m,k,_)}L||(L=Error);var A=(function(m){function k(_,T,S){return m.call(this,v(_,T,S))||this}return d(k,m),k})(L);A.prototype.name=L.name,A.prototype.code=y,x[y]=A}function p(y,E){if(Array.isArray(y)){var L=y.length;return y=y.map(function(v){return v+""}),2<L?"one of ".concat(E," ").concat(y.slice(0,L-1).join(", "),", or ")+y[L-1]:L===2?"one of ".concat(E," ").concat(y[0]," or ").concat(y[1]):"of ".concat(E," ").concat(y[0])}return"of ".concat(E," ").concat(y+"")}function g(y,E,L){return y.substr(0,E.length)===E}function u(y,E,L){return(L===void 0||L>y.length)&&(L=y.length),y.substring(L-E.length,L)===E}function f(y,E,L){return typeof L!="number"&&(L=0),!(L+E.length>y.length)&&y.indexOf(E,L)!==-1}var x={};l("ERR_INVALID_OPT_VALUE",function(y,E){return'The value "'+E+'" is invalid for option "'+y+'"'},TypeError),l("ERR_INVALID_ARG_TYPE",function(y,E,L){var v;typeof E=="string"&&g(E,"not ")?(v="must not be",E=E.replace(/^not /,"")):v="must be";var A;if(u(y," argument"))A="The ".concat(y," ").concat(v," ").concat(p(E,"type"));else{var m=f(y,".")?"property":"argument";A='The "'.concat(y,'" ').concat(m," ").concat(v," ").concat(p(E,"type"))}return A+=". Received type ".concat(typeof L),A},TypeError),l("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),l("ERR_METHOD_NOT_IMPLEMENTED",function(y){return"The "+y+" method is not implemented"}),l("ERR_STREAM_PREMATURE_CLOSE","Premature close"),l("ERR_STREAM_DESTROYED",function(y){return"Cannot call "+y+" after a stream was destroyed"}),l("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),l("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),l("ERR_STREAM_WRITE_AFTER_END","write after end"),l("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),l("ERR_UNKNOWN_ENCODING",function(y){return"Unknown encoding: "+y},TypeError),l("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),c.exports.codes=x},{}],16:[function(o,c){(function(d){(function(){function l(v){return this instanceof l?(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 l(v)}function p(){this._writableState.ended||d.nextTick(g,this)}function g(v){v.end()}var u=Object.keys||function(v){var A=[];for(var m in v)A.push(m);return A};c.exports=l;var f=o("./_stream_readable"),x=o("./_stream_writable");o("inherits")(l,f);for(var y,E=u(x.prototype),L=0;L<E.length;L++)y=E[L],l.prototype[y]||(l.prototype[y]=x.prototype[y]);Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.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 d(p){return this instanceof d?void l.call(this,p):new d(p)}c.exports=d;var l=o("./_stream_transform");o("inherits")(d,l),d.prototype._transform=function(p,g,u){u(null,p)}},{"./_stream_transform":19,inherits:10}],18:[function(o,c){(function(d,l){(function(){function p(N){return q.from(N)}function g(N){return q.isBuffer(N)||N instanceof te}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){$=$||o("./_stream_duplex"),N=N||{},typeof h!="boolean"&&(h=a instanceof $),this.objectMode=!!N.objectMode,h&&(this.objectMode=this.objectMode||!!N.readableObjectMode),this.highWaterMark=X(this,N,"readableHighWaterMark",h),this.buffer=new ye,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&&(!be&&(be=o("string_decoder/").StringDecoder),this.decoder=new be(N.encoding),this.encoding=N.encoding)}function x(N){if($=$||o("./_stream_duplex"),!(this instanceof x))return new x(N);var a=this instanceof $;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)),se.call(this)}function y(N,a,h,b,I){F("readableAddChunk",a);var O=N._readableState;if(a===null)O.reading=!1,m(N,O);else{var U;if(I||(U=L(O,a)),U)G(N,U);else if(!(O.objectMode||a&&0<a.length))b||(O.reading=!1,T(N,O));else if(typeof a=="string"||O.objectMode||Object.getPrototypeOf(a)===q.prototype||(a=p(a)),b)O.endEmitted?G(N,new W):E(N,O,a,!0);else if(O.ended)G(N,new ae);else{if(O.destroyed)return!1;O.reading=!1,O.decoder&&!h?(a=O.decoder.write(a),O.objectMode||a.length!==0?E(N,O,a,!1):T(N,O)):E(N,O,a,!1)}}return!O.ended&&(O.length<O.highWaterMark||O.length===0)}function E(N,a,h,b){a.flowing&&a.length===0&&!a.sync?(a.awaitDrain=0,N.emit("data",h)):(a.length+=a.objectMode?1:h.length,b?a.buffer.unshift(h):a.buffer.push(h),a.needReadable&&k(N)),T(N,a)}function L(N,a){var h;return g(a)||typeof a=="string"||a===void 0||N.objectMode||(h=new ee("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 A(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 m(N,a){if(F("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;F("emitReadable",a.needReadable,a.emittedReadable),a.needReadable=!1,a.emittedReadable||(F("emitReadable",a.flowing),a.emittedReadable=!0,d.nextTick(_,N))}function _(N){var a=N._readableState;F("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,d.nextTick(S,N,a))}function S(N,a){for(;!a.reading&&!a.ended&&(a.length<a.highWaterMark||a.flowing&&a.length===0);){var h=a.length;if(F("maybeReadMore read 0"),N.read(0),h===a.length)break}a.readingMore=!1}function C(N){return function(){var a=N._readableState;F("pipeOnDrain",a.awaitDrain),a.awaitDrain&&a.awaitDrain--,a.awaitDrain===0&&V(N,"data")&&(a.flowing=!0,B(N))}}function D(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 j(N){F("readable nexttick read 0"),N.read(0)}function R(N,a){a.resumeScheduled||(a.resumeScheduled=!0,d.nextTick(P,N,a))}function P(N,a){F("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(F("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 J(N){var a=N._readableState;F("endReadable",a.endEmitted),a.endEmitted||(a.ended=!0,d.nextTick(H,a,N))}function H(N,a){if(F("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 K(N,a){for(var h=0,b=N.length;h<b;h++)if(N[h]===a)return h;return-1}c.exports=x;var $;x.ReadableState=f;var F;o("events").EventEmitter;var V=function(N,a){return N.listeners(a).length},se=o("./internal/streams/stream"),q=o("buffer").Buffer,te=l.Uint8Array||function(){},Q=o("util");F=Q&&Q.debuglog?Q.debuglog("stream"):function(){};var be,Ce,ce,ye=o("./internal/streams/buffer_list"),xe=o("./internal/streams/destroy"),ve=o("./internal/streams/state"),X=ve.getHighWaterMark,Y=o("../errors").codes,ee=Y.ERR_INVALID_ARG_TYPE,ae=Y.ERR_STREAM_PUSH_AFTER_EOF,M=Y.ERR_METHOD_NOT_IMPLEMENTED,W=Y.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;o("inherits")(x,se);var G=xe.errorOrDestroy,ne=["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=xe.destroy,x.prototype._undestroy=xe.undestroy,x.prototype._destroy=function(N,a){a(N)},x.prototype.push=function(N,a){var h,b=this._readableState;return b.objectMode?h=!0:typeof N=="string"&&(a=a||b.defaultEncoding,a!==b.encoding&&(N=q.from(N,a),a=""),h=!0),y(this,N,a,!1,h)},x.prototype.unshift=function(N){return y(this,N,null,!0,!1)},x.prototype.isPaused=function(){return this._readableState.flowing===!1},x.prototype.setEncoding=function(N){be||(be=o("string_decoder/").StringDecoder);var a=new be(N);this._readableState.decoder=a,this._readableState.encoding=this._readableState.decoder.encoding;for(var h=this._readableState.buffer.head,b="";h!==null;)b+=a.write(h.data),h=h.next;return this._readableState.buffer.clear(),b!==""&&this._readableState.buffer.push(b),this._readableState.length=b.length,this},x.prototype.read=function(N){F("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 F("read: emitReadable",a.length,a.ended),a.length===0&&a.ended?J(this):k(this),null;if(N=A(N,a),N===0&&a.ended)return a.length===0&&J(this),null;var b=a.needReadable;F("need readable",b),(a.length===0||a.length-N<a.highWaterMark)&&(b=!0,F("length less than watermark",b)),a.ended||a.reading?(b=!1,F("reading or ended",b)):b&&(F("do read"),a.reading=!0,a.sync=!0,a.length===0&&(a.needReadable=!0),this._read(a.highWaterMark),a.sync=!1,!a.reading&&(N=A(h,a)));var I;return I=0<N?z(N,a):null,I===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&&J(this)),I!==null&&this.emit("data",I),I},x.prototype._read=function(){G(this,new M("_read()"))},x.prototype.pipe=function(N,a){function h(Wt,Bt){F("onunpipe"),Wt===pe&&Bt&&Bt.hasUnpiped===!1&&(Bt.hasUnpiped=!0,I())}function b(){F("onend"),N.end()}function I(){F("cleanup"),N.removeListener("close",re),N.removeListener("finish",fe),N.removeListener("drain",Pt),N.removeListener("error",U),N.removeListener("unpipe",h),pe.removeListener("end",b),pe.removeListener("end",_e),pe.removeListener("data",O),as=!0,ue.awaitDrain&&(!N._writableState||N._writableState.needDrain)&&Pt()}function O(Wt){F("ondata");var Bt=N.write(Wt);F("dest.write",Bt),Bt===!1&&((ue.pipesCount===1&&ue.pipes===N||1<ue.pipesCount&&K(ue.pipes,N)!==-1)&&!as&&(F("false write response, pause",ue.awaitDrain),ue.awaitDrain++),pe.pause())}function U(Wt){F("onerror",Wt),_e(),N.removeListener("error",U),V(N,"error")===0&&G(N,Wt)}function re(){N.removeListener("finish",fe),_e()}function fe(){F("onfinish"),N.removeListener("close",re),_e()}function _e(){F("unpipe"),pe.unpipe(N)}var pe=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,F("pipe count=%d opts=%j",ue.pipesCount,a);var Pe=(!a||a.end!==!1)&&N!==d.stdout&&N!==d.stderr,kt=Pe?b:_e;ue.endEmitted?d.nextTick(kt):pe.once("end",kt),N.on("unpipe",h);var Pt=C(pe);N.on("drain",Pt);var as=!1;return pe.on("data",O),u(N,"error",U),N.once("close",re),N.once("finish",fe),N.emit("pipe",pe),ue.flowing||(F("pipe resume"),pe.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 b=a.pipes,I=a.pipesCount;a.pipes=null,a.pipesCount=0,a.flowing=!1;for(var O=0;O<I;O++)b[O].emit("unpipe",this,{hasUnpiped:!1});return this}var U=K(a.pipes,N);return U===-1?this:(a.pipes.splice(U,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=se.prototype.on.call(this,N,a),b=this._readableState;return N==="data"?(b.readableListening=0<this.listenerCount("readable"),b.flowing!==!1&&this.resume()):N=="readable"&&!b.endEmitted&&!b.readableListening&&(b.readableListening=b.needReadable=!0,b.flowing=!1,b.emittedReadable=!1,F("on readable",b.length,b.reading),b.length?k(this):!b.reading&&d.nextTick(j,this)),h},x.prototype.addListener=x.prototype.on,x.prototype.removeListener=function(N,a){var h=se.prototype.removeListener.call(this,N,a);return N==="readable"&&d.nextTick(D,this),h},x.prototype.removeAllListeners=function(N){var a=se.prototype.removeAllListeners.apply(this,arguments);return(N==="readable"||N===void 0)&&d.nextTick(D,this),a},x.prototype.resume=function(){var N=this._readableState;return N.flowing||(F("resume"),N.flowing=!N.readableListening,R(this,N)),N.paused=!1,this},x.prototype.pause=function(){return F("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(F("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},x.prototype.wrap=function(N){var a=this,h=this._readableState,b=!1;for(var I in N.on("end",function(){if(F("wrapped end"),h.decoder&&!h.ended){var U=h.decoder.end();U&&U.length&&a.push(U)}a.push(null)}),N.on("data",function(U){if(F("wrapped data"),h.decoder&&(U=h.decoder.write(U)),!(h.objectMode&&U==null)&&(h.objectMode||U&&U.length)){var re=a.push(U);re||(b=!0,N.pause())}}),N)this[I]===void 0&&typeof N[I]=="function"&&(this[I]=(function(U){return function(){return N[U].apply(N,arguments)}})(I));for(var O=0;O<ne.length;O++)N.on(ne[O],this.emit.bind(this,ne[O]));return this._read=function(U){F("wrapped _read",U),b&&(b=!1,N.resume())},this},typeof Symbol=="function"&&(x.prototype[Symbol.asyncIterator]=function(){return Ce===void 0&&(Ce=o("./internal/streams/async_iterator")),Ce(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 ce===void 0&&(ce=o("./internal/streams/from")),ce(x,N,a)})}).call(this)}).call(this,o("_process"),typeof st>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:st)},{"../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 d(v,A){var m=this._transformState;m.transforming=!1;var k=m.writecb;if(k===null)return this.emit("error",new x);m.writechunk=null,m.writecb=null,A!=null&&this.push(A),k(v);var _=this._readableState;_.reading=!1,(_.needReadable||_.length<_.highWaterMark)&&this._read(_.highWaterMark)}function l(v){return this instanceof l?(L.call(this,v),this._transformState={afterTransform:d.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 l(v)}function p(){var v=this;typeof this._flush!="function"||this._readableState.destroyed?g(this,null,null):this._flush(function(A,m){g(v,A,m)})}function g(v,A,m){if(A)return v.emit("error",A);if(m!=null&&v.push(m),v._writableState.length)throw new E;if(v._transformState.transforming)throw new y;return v.push(null)}c.exports=l;var u=o("../errors").codes,f=u.ERR_METHOD_NOT_IMPLEMENTED,x=u.ERR_MULTIPLE_CALLBACK,y=u.ERR_TRANSFORM_ALREADY_TRANSFORMING,E=u.ERR_TRANSFORM_WITH_LENGTH_0,L=o("./_stream_duplex");o("inherits")(l,L),l.prototype.push=function(v,A){return this._transformState.needTransform=!1,L.prototype.push.call(this,v,A)},l.prototype._transform=function(v,A,m){m(new f("_transform()"))},l.prototype._write=function(v,A,m){var k=this._transformState;if(k.writecb=m,k.writechunk=v,k.writeencoding=A,!k.transforming){var _=this._readableState;(k.needTransform||_.needReadable||_.length<_.highWaterMark)&&this._read(_.highWaterMark)}},l.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))},l.prototype._destroy=function(v,A){L.prototype._destroy.call(this,v,function(m){A(m)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(o,c){(function(d,l){(function(){function p(M){var W=this;this.next=null,this.entry=null,this.finish=function(){J(W,M)}}function g(M){return F.from(M)}function u(M){return F.isBuffer(M)||M instanceof V}function f(){}function x(M,W,G){H=H||o("./_stream_duplex"),M=M||{},typeof G!="boolean"&&(G=W instanceof H),this.objectMode=!!M.objectMode,G&&(this.objectMode=this.objectMode||!!M.writableObjectMode),this.highWaterMark=te(this,M,"writableHighWaterMark",G),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var ne=M.decodeStrings===!1;this.decodeStrings=!ne,this.defaultEncoding=M.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(N){T(W,N)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=M.emitClose!==!1,this.autoDestroy=!!M.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new p(this)}function y(M){H=H||o("./_stream_duplex");var W=this instanceof H;return W||ae.call(y,this)?(this._writableState=new x(M,this,W),this.writable=!0,M&&(typeof M.write=="function"&&(this._write=M.write),typeof M.writev=="function"&&(this._writev=M.writev),typeof M.destroy=="function"&&(this._destroy=M.destroy),typeof M.final=="function"&&(this._final=M.final)),void $.call(this)):new y(M)}function E(M,W){var G=new X;ee(M,G),d.nextTick(W,G)}function L(M,W,G,ne){var N;return G===null?N=new ve:typeof G!="string"&&!W.objectMode&&(N=new be("chunk",["string","Buffer"],G)),!N||(ee(M,N),d.nextTick(ne,N),!1)}function v(M,W,G){return M.objectMode||M.decodeStrings===!1||typeof W!="string"||(W=F.from(W,G)),W}function A(M,W,G,ne,N,a){if(!G){var h=v(W,ne,N);ne!==h&&(G=!0,N="buffer",ne=h)}var b=W.objectMode?1:ne.length;W.length+=b;var I=W.length<W.highWaterMark;if(I||(W.needDrain=!0),W.writing||W.corked){var O=W.lastBufferedRequest;W.lastBufferedRequest={chunk:ne,encoding:N,isBuf:G,callback:a,next:null},O?O.next=W.lastBufferedRequest:W.bufferedRequest=W.lastBufferedRequest,W.bufferedRequestCount+=1}else m(M,W,!1,b,ne,N,a);return I}function m(M,W,G,ne,N,a,h){W.writelen=ne,W.writecb=h,W.writing=!0,W.sync=!0,W.destroyed?W.onwrite(new xe("write")):G?M._writev(N,W.onwrite):M._write(N,a,W.onwrite),W.sync=!1}function k(M,W,G,ne,N){--W.pendingcb,G?(d.nextTick(N,ne),d.nextTick(B,M,W),M._writableState.errorEmitted=!0,ee(M,ne)):(N(ne),M._writableState.errorEmitted=!0,ee(M,ne),B(M,W))}function _(M){M.writing=!1,M.writecb=null,M.length-=M.writelen,M.writelen=0}function T(M,W){var G=M._writableState,ne=G.sync,N=G.writecb;if(typeof N!="function")throw new ce;if(_(G),W)k(M,G,ne,W,N);else{var a=j(G)||M.destroyed;a||G.corked||G.bufferProcessing||!G.bufferedRequest||D(M,G),ne?d.nextTick(S,M,G,a,N):S(M,G,a,N)}}function S(M,W,G,ne){G||C(M,W),W.pendingcb--,ne(),B(M,W)}function C(M,W){W.length===0&&W.needDrain&&(W.needDrain=!1,M.emit("drain"))}function D(M,W){W.bufferProcessing=!0;var G=W.bufferedRequest;if(M._writev&&G&&G.next){var ne=W.bufferedRequestCount,N=Array(ne),a=W.corkedRequestsFree;a.entry=G;for(var h=0,b=!0;G;)N[h]=G,G.isBuf||(b=!1),G=G.next,h+=1;N.allBuffers=b,m(M,W,!0,W.length,N,"",a.finish),W.pendingcb++,W.lastBufferedRequest=null,a.next?(W.corkedRequestsFree=a.next,a.next=null):W.corkedRequestsFree=new p(W),W.bufferedRequestCount=0}else{for(;G;){var I=G.chunk,O=G.encoding,U=G.callback,re=W.objectMode?1:I.length;if(m(M,W,!1,re,I,O,U),G=G.next,W.bufferedRequestCount--,W.writing)break}G===null&&(W.lastBufferedRequest=null)}W.bufferedRequest=G,W.bufferProcessing=!1}function j(M){return M.ending&&M.length===0&&M.bufferedRequest===null&&!M.finished&&!M.writing}function R(M,W){M._final(function(G){W.pendingcb--,G&&ee(M,G),W.prefinished=!0,M.emit("prefinish"),B(M,W)})}function P(M,W){W.prefinished||W.finalCalled||(typeof M._final!="function"||W.destroyed?(W.prefinished=!0,M.emit("prefinish")):(W.pendingcb++,W.finalCalled=!0,d.nextTick(R,M,W)))}function B(M,W){var G=j(W);if(G&&(P(M,W),W.pendingcb===0&&(W.finished=!0,M.emit("finish"),W.autoDestroy))){var ne=M._readableState;(!ne||ne.autoDestroy&&ne.endEmitted)&&M.destroy()}return G}function z(M,W,G){W.ending=!0,B(M,W),G&&(W.finished?d.nextTick(G):M.once("finish",G)),W.ended=!0,M.writable=!1}function J(M,W,G){var ne=M.entry;for(M.entry=null;ne;){var N=ne.callback;W.pendingcb--,N(G),ne=ne.next}W.corkedRequestsFree.next=M}c.exports=y;var H;y.WritableState=x;var K={deprecate:o("util-deprecate")},$=o("./internal/streams/stream"),F=o("buffer").Buffer,V=l.Uint8Array||function(){},se=o("./internal/streams/destroy"),q=o("./internal/streams/state"),te=q.getHighWaterMark,Q=o("../errors").codes,be=Q.ERR_INVALID_ARG_TYPE,Ce=Q.ERR_METHOD_NOT_IMPLEMENTED,ce=Q.ERR_MULTIPLE_CALLBACK,ye=Q.ERR_STREAM_CANNOT_PIPE,xe=Q.ERR_STREAM_DESTROYED,ve=Q.ERR_STREAM_NULL_VALUES,X=Q.ERR_STREAM_WRITE_AFTER_END,Y=Q.ERR_UNKNOWN_ENCODING,ee=se.errorOrDestroy;o("inherits")(y,$),x.prototype.getBuffer=function(){for(var M=this.bufferedRequest,W=[];M;)W.push(M),M=M.next;return W},(function(){try{Object.defineProperty(x.prototype,"buffer",{get:K.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var ae;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(ae=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(M){return!!ae.call(this,M)||this===y&&M&&M._writableState instanceof x}})):ae=function(M){return M instanceof this},y.prototype.pipe=function(){ee(this,new ye)},y.prototype.write=function(M,W,G){var ne=this._writableState,N=!1,a=!ne.objectMode&&u(M);return a&&!F.isBuffer(M)&&(M=g(M)),typeof W=="function"&&(G=W,W=null),a?W="buffer":!W&&(W=ne.defaultEncoding),typeof G!="function"&&(G=f),ne.ending?E(this,G):(a||L(this,ne,M,G))&&(ne.pendingcb++,N=A(this,ne,a,M,W,G)),N},y.prototype.cork=function(){this._writableState.corked++},y.prototype.uncork=function(){var M=this._writableState;M.corked&&(M.corked--,!M.writing&&!M.corked&&!M.bufferProcessing&&M.bufferedRequest&&D(this,M))},y.prototype.setDefaultEncoding=function(M){if(typeof M=="string"&&(M=M.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((M+"").toLowerCase())))throw new Y(M);return this._writableState.defaultEncoding=M,this},Object.defineProperty(y.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(M,W,G){G(new Ce("_write()"))},y.prototype._writev=null,y.prototype.end=function(M,W,G){var ne=this._writableState;return typeof M=="function"?(G=M,M=null,W=null):typeof W=="function"&&(G=W,W=null),M!=null&&this.write(M,W),ne.corked&&(ne.corked=1,this.uncork()),ne.ending||z(this,ne,G),this},Object.defineProperty(y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(y.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(M){this._writableState&&(this._writableState.destroyed=M)}}),y.prototype.destroy=se.destroy,y.prototype._undestroy=se.undestroy,y.prototype._destroy=function(M,W){W(M)}}).call(this)}).call(this,o("_process"),typeof st>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:st)},{"../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(d){(function(){function l(C,D,j){return D in C?Object.defineProperty(C,D,{value:j,enumerable:!0,configurable:!0,writable:!0}):C[D]=j,C}function p(C,D){return{value:C,done:D}}function g(C){var D=C[E];if(D!==null){var j=C[_].read();j!==null&&(C[m]=null,C[E]=null,C[L]=null,D(p(j,!1)))}}function u(C){d.nextTick(g,C)}function f(C,D){return function(j,R){C.then(function(){return D[A]?void j(p(void 0,!0)):void D[k](j,R)},R)}}var x,y=o("./end-of-stream"),E=Symbol("lastResolve"),L=Symbol("lastReject"),v=Symbol("error"),A=Symbol("ended"),m=Symbol("lastPromise"),k=Symbol("handlePromise"),_=Symbol("stream"),T=Object.getPrototypeOf(function(){}),S=Object.setPrototypeOf((x={get stream(){return this[_]},next:function(){var C=this,D=this[v];if(D!==null)return Promise.reject(D);if(this[A])return Promise.resolve(p(void 0,!0));if(this[_].destroyed)return new Promise(function(B,z){d.nextTick(function(){C[v]?z(C[v]):B(p(void 0,!0))})});var j,R=this[m];if(R)j=new Promise(f(R,this));else{var P=this[_].read();if(P!==null)return Promise.resolve(p(P,!1));j=new Promise(this[k])}return this[m]=j,j}},l(x,Symbol.asyncIterator,function(){return this}),l(x,"return",function(){var C=this;return new Promise(function(D,j){C[_].destroy(null,function(R){return R?void j(R):void D(p(void 0,!0))})})}),x),T);c.exports=function(C){var D,j=Object.create(S,(D={},l(D,_,{value:C,writable:!0}),l(D,E,{value:null,writable:!0}),l(D,L,{value:null,writable:!0}),l(D,v,{value:null,writable:!0}),l(D,A,{value:C._readableState.endEmitted,writable:!0}),l(D,k,{value:function(R,P){var B=j[_].read();B?(j[m]=null,j[E]=null,j[L]=null,R(p(B,!1))):(j[E]=R,j[L]=P)},writable:!0}),D));return j[m]=null,y(C,function(R){if(R&&R.code!=="ERR_STREAM_PREMATURE_CLOSE"){var P=j[L];return P!==null&&(j[m]=null,j[E]=null,j[L]=null,P(R)),void(j[v]=R)}var B=j[E];B!==null&&(j[m]=null,j[E]=null,j[L]=null,B(p(void 0,!0))),j[A]=!0}),C.on("readable",u.bind(null,j)),j}}).call(this)}).call(this,o("_process"))},{"./end-of-stream":24,_process:12}],22:[function(o,c){function d(m,k){var _=Object.keys(m);if(Object.getOwnPropertySymbols){var T=Object.getOwnPropertySymbols(m);k&&(T=T.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),_.push.apply(_,T)}return _}function l(m){for(var k,_=1;_<arguments.length;_++)k=arguments[_]==null?{}:arguments[_],_%2?d(Object(k),!0).forEach(function(T){p(m,T,k[T])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(k)):d(Object(k)).forEach(function(T){Object.defineProperty(m,T,Object.getOwnPropertyDescriptor(k,T))});return m}function p(m,k,_){return k in m?Object.defineProperty(m,k,{value:_,enumerable:!0,configurable:!0,writable:!0}):m[k]=_,m}function g(m,k){if(!(m instanceof k))throw new TypeError("Cannot call a class as a function")}function u(m,k){for(var _,T=0;T<k.length;T++)_=k[T],_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(m,_.key,_)}function f(m,k,_){return k&&u(m.prototype,k),m}function x(m,k,_){E.prototype.copy.call(m,k,_)}var y=o("buffer"),E=y.Buffer,L=o("util"),v=L.inspect,A=v&&v.custom||"inspect";c.exports=(function(){function m(){g(this,m),this.head=null,this.tail=null,this.length=0}return f(m,[{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 E.alloc(0);for(var _=E.allocUnsafe(k>>>0),T=this.head,S=0;T;)x(T.data,_,S),S+=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,S=_.data;for(k-=S.length;_=_.next;){var C=_.data,D=k>C.length?C.length:k;if(S+=D===C.length?C:C.slice(0,k),k-=D,k===0){D===C.length?(++T,this.head=_.next?_.next:this.tail=null):(this.head=_,_.data=C.slice(D));break}++T}return this.length-=T,S}},{key:"_getBuffer",value:function(k){var _=E.allocUnsafe(k),T=this.head,S=1;for(T.data.copy(_),k-=T.data.length;T=T.next;){var C=T.data,D=k>C.length?C.length:k;if(C.copy(_,_.length-k,0,D),k-=D,k===0){D===C.length?(++S,this.head=T.next?T.next:this.tail=null):(this.head=T,T.data=C.slice(D));break}++S}return this.length-=S,_}},{key:A,value:function(k,_){return v(this,l({},_,{depth:0,customInspect:!1}))}}]),m})()},{buffer:3,util:2}],23:[function(o,c){(function(d){(function(){function l(u,f){g(u,f),p(u)}function p(u){u._writableState&&!u._writableState.emitClose||u._readableState&&!u._readableState.emitClose||u.emit("close")}function g(u,f){u.emit("error",f)}c.exports={destroy:function(u,f){var x=this,y=this._readableState&&this._readableState.destroyed,E=this._writableState&&this._writableState.destroyed;return y||E?(f?f(u):u&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,d.nextTick(g,this,u)):d.nextTick(g,this,u)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(u||null,function(L){!f&&L?x._writableState?x._writableState.errorEmitted?d.nextTick(p,x):(x._writableState.errorEmitted=!0,d.nextTick(l,x,L)):d.nextTick(l,x,L):f?(d.nextTick(p,x),f(L)):d.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,y=u._writableState;x&&x.autoDestroy||y&&y.autoDestroy?u.destroy(f):u.emit("error",f)}}}).call(this)}).call(this,o("_process"))},{_process:12}],24:[function(o,c){function d(f){var x=!1;return function(){if(!x){x=!0;for(var y=arguments.length,E=Array(y),L=0;L<y;L++)E[L]=arguments[L];f.apply(this,E)}}}function l(){}function p(f){return f.setHeader&&typeof f.abort=="function"}function g(f,x,y){if(typeof x=="function")return g(f,null,x);x||(x={}),y=d(y||l);var E=x.readable||x.readable!==!1&&f.readable,L=x.writable||x.writable!==!1&&f.writable,v=function(){f.writable||m()},A=f._writableState&&f._writableState.finished,m=function(){L=!1,A=!0,E||y.call(f)},k=f._readableState&&f._readableState.endEmitted,_=function(){E=!1,k=!0,L||y.call(f)},T=function(D){y.call(f,D)},S=function(){var D;return E&&!k?(f._readableState&&f._readableState.ended||(D=new u),y.call(f,D)):L&&!A?(f._writableState&&f._writableState.ended||(D=new u),y.call(f,D)):void 0},C=function(){f.req.on("finish",m)};return p(f)?(f.on("complete",m),f.on("abort",S),f.req?C():f.on("request",C)):L&&!f._writableState&&(f.on("end",v),f.on("close",v)),f.on("end",_),f.on("finish",m),x.error!==!1&&f.on("error",T),f.on("close",S),function(){f.removeListener("complete",m),f.removeListener("abort",S),f.removeListener("request",C),f.req&&f.req.removeListener("finish",m),f.removeListener("end",v),f.removeListener("close",v),f.removeListener("finish",m),f.removeListener("end",_),f.removeListener("error",T),f.removeListener("close",S)}}var u=o("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;c.exports=g},{"../../../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 d(A){var m=!1;return function(){m||(m=!0,A.apply(void 0,arguments))}}function l(A){if(A)throw A}function p(A){return A.setHeader&&typeof A.abort=="function"}function g(A,m,k,_){_=d(_);var T=!1;A.on("close",function(){T=!0}),y===void 0&&(y=o("./end-of-stream")),y(A,{readable:m,writable:k},function(C){return C?_(C):(T=!0,void _())});var S=!1;return function(C){if(!T)return S?void 0:(S=!0,p(A)?A.abort():typeof A.destroy=="function"?A.destroy():void _(C||new v("pipe")))}}function u(A){A()}function f(A,m){return A.pipe(m)}function x(A){return A.length&&typeof A[A.length-1]=="function"?A.pop():l}var y,E=o("../../../errors").codes,L=E.ERR_MISSING_ARGS,v=E.ERR_STREAM_DESTROYED;c.exports=function(){for(var A=arguments.length,m=Array(A),k=0;k<A;k++)m[k]=arguments[k];var _=x(m);if(Array.isArray(m[0])&&(m=m[0]),2>m.length)throw new L("streams");var T,S=m.map(function(C,D){var j=D<m.length-1;return g(C,j,0<D,function(R){T||(T=R),R&&S.forEach(u),j||(S.forEach(u),_(T))})});return m.reduce(f)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(o,c){function d(p,g,u){return p.highWaterMark==null?g?p[u]:null:p.highWaterMark}var l=o("../../../errors").codes.ERR_INVALID_OPT_VALUE;c.exports={getHighWaterMark:function(p,g,u,f){var x=d(g,f,u);if(x!=null){if(!(isFinite(x)&&s(x)===x)||0>x){var y=f?u:"highWaterMark";throw new l(y,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,d){d=c.exports=o("./lib/_stream_readable.js"),d.Stream=d,d.Readable=d,d.Writable=o("./lib/_stream_writable.js"),d.Duplex=o("./lib/_stream_duplex.js"),d.Transform=o("./lib/_stream_transform.js"),d.PassThrough=o("./lib/_stream_passthrough.js"),d.finished=o("./lib/internal/streams/end-of-stream.js"),d.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,d){function l(f,x){for(var y in f)x[y]=f[y]}function p(f,x,y){return u(f,x,y)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var g=o("buffer"),u=g.Buffer;u.from&&u.alloc&&u.allocUnsafe&&u.allocUnsafeSlow?c.exports=g:(l(g,d),d.Buffer=p),p.prototype=Object.create(u.prototype),l(u,p),p.from=function(f,x,y){if(typeof f=="number")throw new TypeError("Argument must not be a number");return u(f,x,y)},p.alloc=function(f,x,y){if(typeof f!="number")throw new TypeError("Argument must be a number");var E=u(f);return x===void 0?E.fill(0):typeof y=="string"?E.fill(x,y):E.fill(x),E},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 g.SlowBuffer(f)}},{buffer:3}],31:[function(o,c,d){function l(S){if(!S)return"utf8";for(var C;;)switch(S){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 S;default:if(C)return;S=(""+S).toLowerCase(),C=!0}}function p(S){var C=l(S);if(typeof C!="string"&&(_.isEncoding===T||!T(S)))throw new Error("Unknown encoding: "+S);return C||S}function g(S){this.encoding=p(S);var C;switch(this.encoding){case"utf16le":this.text=E,this.end=L,C=4;break;case"utf8":this.fillLast=y,C=4;break;case"base64":this.text=v,this.end=A,C=3;break;default:return this.write=m,void(this.end=k)}this.lastNeed=0,this.lastTotal=0,this.lastChar=_.allocUnsafe(C)}function u(S){return 127>=S?0:S>>5==6?2:S>>4==14?3:S>>3==30?4:S>>6==2?-1:-2}function f(S,C,D){var j=C.length-1;if(j<D)return 0;var R=u(C[j]);return 0<=R?(0<R&&(S.lastNeed=R-1),R):--j<D||R===-2?0:(R=u(C[j]),0<=R?(0<R&&(S.lastNeed=R-2),R):--j<D||R===-2?0:(R=u(C[j]),0<=R?(0<R&&(R===2?R=0:S.lastNeed=R-3),R):0))}function x(S,C){if((192&C[0])!=128)return S.lastNeed=0,"�";if(1<S.lastNeed&&1<C.length){if((192&C[1])!=128)return S.lastNeed=1,"�";if(2<S.lastNeed&&2<C.length&&(192&C[2])!=128)return S.lastNeed=2,"�"}}function y(S){var C=this.lastTotal-this.lastNeed,D=x(this,S);return D===void 0?this.lastNeed<=S.length?(S.copy(this.lastChar,C,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(S.copy(this.lastChar,C,0,S.length),void(this.lastNeed-=S.length)):D}function E(S,C){if((S.length-C)%2==0){var D=S.toString("utf16le",C);if(D){var j=D.charCodeAt(D.length-1);if(55296<=j&&56319>=j)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=S[S.length-2],this.lastChar[1]=S[S.length-1],D.slice(0,-1)}return D}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=S[S.length-1],S.toString("utf16le",C,S.length-1)}function L(S){var C=S&&S.length?this.write(S):"";if(this.lastNeed){var D=this.lastTotal-this.lastNeed;return C+this.lastChar.toString("utf16le",0,D)}return C}function v(S,C){var D=(S.length-C)%3;return D==0?S.toString("base64",C):(this.lastNeed=3-D,this.lastTotal=3,D==1?this.lastChar[0]=S[S.length-1]:(this.lastChar[0]=S[S.length-2],this.lastChar[1]=S[S.length-1]),S.toString("base64",C,S.length-D))}function A(S){var C=S&&S.length?this.write(S):"";return this.lastNeed?C+this.lastChar.toString("base64",0,3-this.lastNeed):C}function m(S){return S.toString(this.encoding)}function k(S){return S&&S.length?this.write(S):""}var _=o("safe-buffer").Buffer,T=_.isEncoding||function(S){switch(S=""+S,S&&S.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}};d.StringDecoder=g,g.prototype.write=function(S){if(S.length===0)return"";var C,D;if(this.lastNeed){if(C=this.fillLast(S),C===void 0)return"";D=this.lastNeed,this.lastNeed=0}else D=0;return D<S.length?C?C+this.text(S,D):this.text(S,D):C||""},g.prototype.end=function(S){var C=S&&S.length?this.write(S):"";return this.lastNeed?C+"�":C},g.prototype.text=function(S,C){var D=f(this,S,C);if(!this.lastNeed)return S.toString("utf8",C);this.lastTotal=D;var j=S.length-(D-this.lastNeed);return S.copy(this.lastChar,0,j),S.toString("utf8",C,j)},g.prototype.fillLast=function(S){return this.lastNeed<=S.length?(S.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(S.copy(this.lastChar,this.lastTotal-this.lastNeed,0,S.length),void(this.lastNeed-=S.length))}},{"safe-buffer":30}],32:[function(o,c){(function(d){(function(){function l(p){try{if(!d.localStorage)return!1}catch{return!1}var g=d.localStorage[p];return g!=null&&(g+"").toLowerCase()==="true"}c.exports=function(p,g){function u(){if(!f){if(l("throwDeprecation"))throw new Error(g);l("traceDeprecation")?console.trace(g):console.warn(g),f=!0}return p.apply(this,arguments)}if(l("noDeprecation"))return p;var f=!1;return u}}).call(this)}).call(this,typeof st>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:st)},{}],"/":[function(o,c){function d(A){return A.replace(/a=ice-options:trickle\s\n/g,"")}function l(A){console.warn(A)}/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const p=o("debug")("simple-peer"),g=o("get-browser-rtc"),u=o("randombytes"),f=o("readable-stream"),x=o("queue-microtask"),y=o("err-code"),{Buffer:E}=o("buffer"),L=65536;class v extends f.Duplex{constructor(m){if(m=Object.assign({allowHalfOpen:!1},m),super(m),this._id=u(4).toString("hex").slice(0,7),this._debug("new peer %o",m),this.channelName=m.initiator?m.channelName||u(20).toString("hex"):null,this.initiator=m.initiator||!1,this.channelConfig=m.channelConfig||v.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},v.config,m.config),this.offerOptions=m.offerOptions||{},this.answerOptions=m.answerOptions||{},this.sdpTransform=m.sdpTransform||(k=>k),this.streams=m.streams||(m.stream?[m.stream]:[]),this.trickle=m.trickle===void 0||m.trickle,this.allowHalfTrickle=m.allowHalfTrickle!==void 0&&m.allowHalfTrickle,this.iceCompleteTimeout=m.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=m.wrtc&&typeof m.wrtc=="object"?m.wrtc:g(),!this._wrtc)throw y(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(k){return void this.destroy(y(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(y(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(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof m=="string")try{m=JSON.parse(m)}catch{m={}}this._debug("signal()"),m.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),m.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(m.transceiverRequest.kind,m.transceiverRequest.init)),m.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(m.candidate):this._pendingCandidates.push(m.candidate)),m.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(m)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(k=>{this._addIceCandidate(k)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(k=>{this.destroy(y(k,"ERR_SET_REMOTE_DESCRIPTION"))}),m.sdp||m.candidate||m.renegotiate||m.transceiverRequest||this.destroy(y(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(m){const k=new this._wrtc.RTCIceCandidate(m);this._pc.addIceCandidate(k).catch(_=>{!k.address||k.address.endsWith(".local")?l("Ignoring unsupported ICE candidate."):this.destroy(y(_,"ERR_ADD_ICE_CANDIDATE"))})}send(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(m)}}addTransceiver(m,k){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(m,k),this._needsNegotiation()}catch(_){this.destroy(y(_,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:m,init:k}})}}addStream(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),m.getTracks().forEach(k=>{this.addTrack(k,m)})}}addTrack(m,k){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const _=this._senderMap.get(m)||new Map;let T=_.get(k);if(!T)T=this._pc.addTrack(m,k),_.set(k,T),this._senderMap.set(m,_),this._needsNegotiation();else throw T.removed?y(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):y(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(m,k,_){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const T=this._senderMap.get(m),S=T?T.get(_):null;if(!S)throw y(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");k&&this._senderMap.set(k,T),S.replaceTrack==null?this.destroy(y(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):S.replaceTrack(k)}removeTrack(m,k){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const _=this._senderMap.get(m),T=_?_.get(k):null;if(!T)throw y(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{T.removed=!0,this._pc.removeTrack(T)}catch(S){S.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(T):this.destroy(y(S,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),m.getTracks().forEach(k=>{this.removeTrack(k,m)})}}_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 y(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(m){this._destroy(m,()=>{})}_destroy(m,k){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",m&&(m.message||m)),x(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",m&&(m.message||m)),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,m&&this.emit("error",m),this.emit("close"),k()}))}_setupData(m){if(!m.channel)return this.destroy(y(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=m.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=L),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(y(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(m,k,_){if(this.destroyed)return _(y(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(m)}catch(T){return this.destroy(y(T,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>L?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=_):_(null)}else this._debug("write before connect"),this._chunk=m,this._cb=_}_onFinish(){if(!this.destroyed){const m=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?m():this.once("connect",m)}}_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(m=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(m.sdp=d(m.sdp)),m.sdp=this.sdpTransform(m.sdp);const k=()=>{if(!this.destroyed){const _=this._pc.localDescription||m;this._debug("signal"),this.emit("signal",{type:_.type,sdp:_.sdp})}};this._pc.setLocalDescription(m).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?k():this.once("_iceComplete",k))}).catch(_=>{this.destroy(y(_,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(m=>{this.destroy(y(m,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(m=>{m.mid||!m.sender.track||m.requested||(m.requested=!0,this.addTransceiver(m.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(m=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(m.sdp=d(m.sdp)),m.sdp=this.sdpTransform(m.sdp);const k=()=>{if(!this.destroyed){const _=this._pc.localDescription||m;this._debug("signal"),this.emit("signal",{type:_.type,sdp:_.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(m).then(()=>{this.destroyed||(this.trickle||this._iceComplete?k():this.once("_iceComplete",k))}).catch(_=>{this.destroy(y(_,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(m=>{this.destroy(y(m,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(y(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const m=this._pc.iceConnectionState,k=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",m,k),this.emit("iceStateChange",m,k),(m==="connected"||m==="completed")&&(this._pcReady=!0,this._maybeReady()),m==="failed"&&this.destroy(y(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),m==="closed"&&this.destroy(y(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(m){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(S=>{T.push(k(S))}),m(null,T)},_=>m(_)):0<this._pc.getStats.length?this._pc.getStats(_=>{if(this.destroyed)return;const T=[];_.result().forEach(S=>{const C={};S.names().forEach(D=>{C[D]=S.stat(D)}),C.id=S.id,C.type=S.type,C.timestamp=S.timestamp,T.push(k(C))}),m(null,T)},_=>m(_)):m(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 m=()=>{this.destroyed||this.getStats((k,_)=>{if(this.destroyed)return;k&&(_=[]);const T={},S={},C={};let D=!1;_.forEach(R=>{(R.type==="remotecandidate"||R.type==="remote-candidate")&&(T[R.id]=R),(R.type==="localcandidate"||R.type==="local-candidate")&&(S[R.id]=R),(R.type==="candidatepair"||R.type==="candidate-pair")&&(C[R.id]=R)});const j=R=>{D=!0;let P=S[R.localCandidateId];P&&(P.ip||P.address)?(this.localAddress=P.ip||P.address,this.localPort=+P.port):P&&P.ipAddress?(this.localAddress=P.ipAddress,this.localPort=+P.portNumber):typeof R.googLocalAddress=="string"&&(P=R.googLocalAddress.split(":"),this.localAddress=P[0],this.localPort=+P[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&&j(C[R.selectedCandidatePairId]),(R.type==="googCandidatePair"&&R.googActiveConnection==="true"||(R.type==="candidatepair"||R.type==="candidate-pair")&&R.selected)&&j(R)}),!D&&(!Object.keys(C).length||Object.keys(S).length))return void setTimeout(m,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(P){return this.destroy(y(P,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const 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")})};m()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>L)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(m=>{this._pc.removeTrack(m),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(m){this.destroyed||(m.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:m.candidate.candidate,sdpMLineIndex:m.candidate.sdpMLineIndex,sdpMid:m.candidate.sdpMid}}):!m.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),m.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(m){if(this.destroyed)return;let k=m.data;k instanceof ArrayBuffer&&(k=E.from(k)),this.push(k)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const m=this._cb;this._cb=null,m(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(m){this.destroyed||m.streams.forEach(k=>{this._debug("on track"),this.emit("track",m.track,k),this._remoteTracks.push({track:m.track,stream:k}),this._remoteStreams.some(_=>_.id===k.id)||(this._remoteStreams.push(k),x(()=>{this._debug("on stream"),this.emit("stream",k)}))})}_debug(){const m=[].slice.call(arguments);m[0]="["+this._id+"] "+m[0],p.apply(null,m)}}v.WEBRTC_SUPPORT=!!g(),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}]},{},[])("/")})})(Qn)),Qn.exports}var tf=ef();const sf=Nl(tf),ci=0,di=1,Ja=2,Xa=(t,e)=>{ie(t,ci);const s=Cu(e);je(t,s)},Qa=(t,e,s)=>{ie(t,di),je(t,ei(e,s))},nf=(t,e,s)=>Qa(e,s,Ie(t)),Za=(t,e,s,r)=>{try{ga(e,Ie(t),s)}catch(i){r!=null&&r(i),console.error("Caught error while handling a Yjs update",i)}},rf=(t,e)=>{ie(t,Ja),je(t,e)},of=Za,af=(t,e,s,r,i)=>{const o=de(t);switch(o){case ci:nf(t,e,s);break;case di:Za(t,s,r,i);break;case Ja:of(t,s,r,i);break;default:throw new Error("Unknown message type")}return o},Zn=3e4;class lf extends Or{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const s=ht();this.getLocalState()!==null&&Zn/2<=s-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((i,o)=>{o!==this.clientID&&Zn<=s-i.lastUpdated&&this.states.has(o)&&r.push(o)}),r.length>0&&xr(this,r,"timeout")},Xe(Zn/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:ht()});const c=[],d=[],l=[],p=[];e===null?p.push(s):o==null?e!=null&&c.push(s):(d.push(s),zt(o,e)||l.push(s)),(c.length>0||l.length>0||p.length>0)&&this.emit("change",[{added:c,updated:l,removed:p},"local"]),this.emit("update",[{added:c,updated:d,removed:p},"local"])}setLocalStateField(e,s){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:s})}getStates(){return this.states}}const xr=(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:ht()})}r.push(o)}}r.length>0&&(t.emit("change",[{added:[],updated:[],removed:r},s]),t.emit("update",[{added:[],updated:[],removed:r},s]))},dn=(t,e,s=t.states)=>{const r=e.length,i=De();ie(i,r);for(let o=0;o<r;o++){const c=e[o],d=s.get(c)||null,l=t.meta.get(c).clock;ie(i,c),ie(i,l),rt(i,JSON.stringify(d))}return Se(i)},cf=(t,e,s)=>{const r=at(e),i=ht(),o=[],c=[],d=[],l=[],p=de(r);for(let g=0;g<p;g++){const u=de(r);let f=de(r);const x=JSON.parse(dt(r)),y=t.meta.get(u),E=t.states.get(u),L=y===void 0?0:y.clock;(L<f||L===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}),y===void 0&&x!==null?o.push(u):y!==void 0&&x===null?l.push(u):x!==null&&(zt(x,E)||d.push(u),c.push(u)))}(o.length>0||d.length>0||l.length>0)&&t.emit("change",[{added:o,updated:d,removed:l},s]),(o.length>0||c.length>0||l.length>0)&&t.emit("update",[{added:o,updated:c,removed:l},s])},df=(t,e)=>{const s=dr(t).buffer,r=dr(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"]))},el=(t,e)=>{if(!e)return $r(t);const s=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,t).then(r=>{const i=De();return rt(i,"AES-GCM"),je(i,s),je(i,new Uint8Array(r)),Se(i)})},uf=(t,e)=>{const s=De();return Kt(s,t),el(Se(s),e)},tl=(t,e)=>{if(!e)return $r(t);const s=at(t);dt(s)!=="AES-GCM"&&Zc(Ge("Unknown encryption algorithm"));const i=Ie(s),o=Ie(s);return crypto.subtle.decrypt({name:"AES-GCM",iv:i},e,o).then(c=>new Uint8Array(c))},hf=(t,e)=>tl(t,e).then(s=>Jt(at(new Uint8Array(s)))),ze=uu("y-webrtc"),qt=0,sl=3,js=1,ui=4,un=new Map,Nt=new Map,nl=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}]),ze("synced ",Je,t.name,Tt," with all peers"))},rl=(t,e,s)=>{const r=at(e),i=De(),o=de(r);if(t===void 0)return null;const c=t.awareness,d=t.doc;let l=!1;switch(o){case qt:{ie(i,qt);const p=af(r,i,d,t);p===di&&!t.synced&&s(),p===ci&&(l=!0);break}case sl:ie(i,js),je(i,dn(c,Array.from(c.getStates().keys()))),l=!0;break;case js:cf(c,Ie(r),t);break;case ui:{const p=Ct(r)===1,g=dt(r);if(g!==t.peerId&&(t.bcConns.has(g)&&!p||!t.bcConns.has(g)&&p)){const u=[],f=[];p?(t.bcConns.add(g),f.push(g)):(t.bcConns.delete(g),u.push(g)),t.provider.emit("peers",[{added:f,removed:u,webrtcPeers:Array.from(t.webrtcConns.keys()),bcPeers:Array.from(t.bcConns)}]),il(t)}break}default:return console.error("Unable to compute message"),i}return l?i:null},ff=(t,e)=>{const s=t.room;return ze("received message from ",Je,t.remotePeerId,Jr," (",s.name,")",Tt,Ln),rl(s,e,()=>{t.synced=!0,ze("synced ",Je,s.name,Tt," with ",Je,t.remotePeerId),nl(s)})},er=(t,e)=>{ze("send message to ",Je,t.remotePeerId,Tt,Jr," (",t.room.name,")",Ln);try{t.peer.send(Se(e))}catch{}},pf=(t,e)=>{ze("broadcast message in ",Je,t.name,Tt),t.webrtcConns.forEach(s=>{try{s.peer.send(e)}catch{}})};class zi{constructor(e,s,r,i){ze("establishing connection to ",Je,r),this.room=i,this.remotePeerId=r,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new sf({initiator:s,...i.provider.peerOpts}),this.peer.on("signal",o=>{this.glareToken===void 0&&(this.glareToken=Date.now()+Math.random()),hi(e,i,{to:r,from:i.peerId,type:"signal",token:this.glareToken,signal:o})}),this.peer.on("connect",()=>{ze("connected to ",Je,r),this.connected=!0;const c=i.provider.doc,d=i.awareness,l=De();ie(l,qt),Xa(l,c),er(this,l);const p=d.getStates();if(p.size>0){const g=De();ie(g,js),je(g,dn(d,Array.from(p.keys()))),er(this,g)}}),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)}])),nl(i),this.peer.destroy(),ze("closed connection to ",Je,r),wr(i)}),this.peer.on("error",o=>{ze("Error in connection to ",Je,r,": ",o),wr(i)}),this.peer.on("data",o=>{const c=ff(this,o);c!==null&&er(this,c)})}destroy(){this.peer.destroy()}}const gt=(t,e)=>el(e,t.key).then(s=>t.mux(()=>Qh(t.name,s))),Hi=(t,e)=>{t.bcconnected&&gt(t,e),pf(t,e)},wr=t=>{un.forEach(e=>{e.connected&&(e.send({type:"subscribe",topics:[t.name]}),t.webrtcConns.size<t.provider.maxConns&&hi(e,t,{type:"announce",from:t.peerId}))})},il=t=>{if(t.provider.filterBcConns){const e=De();ie(e,ui),bs(e,1),rt(e,t.peerId),gt(t,Se(e))}};class mf{constructor(e,s,r,i){this.peerId=No(),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=Zh(),this.bcconnected=!1,this._bcSubscriber=o=>tl(new Uint8Array(o),i).then(c=>this.mux(()=>{const d=rl(this,c,()=>{});d&&gt(this,Se(d))})),this._docUpdateHandler=(o,c)=>{const d=De();ie(d,qt),rf(d,o),Hi(this,Se(d))},this._awarenessUpdateHandler=({added:o,updated:c,removed:d},l)=>{const p=o.concat(c).concat(d),g=De();ie(g,js),je(g,dn(this.awareness,p)),Hi(this,Se(g))},this._beforeUnloadHandler=()=>{xr(this.awareness,[e.clientID],"window unload"),Nt.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),wr(this);const e=this.name;Jh(e,this._bcSubscriber),this.bcconnected=!0,il(this);const s=De();ie(s,qt),Xa(s,this.doc),gt(this,Se(s));const r=De();ie(r,qt),Qa(r,this.doc),gt(this,Se(r));const i=De();ie(i,sl),gt(this,Se(i));const o=De();ie(o,js),je(o,dn(this.awareness,[this.doc.clientID])),gt(this,Se(o))}disconnect(){un.forEach(s=>{s.connected&&s.send({type:"unsubscribe",topics:[this.name]})}),xr(this.awareness,[this.doc.clientID],"disconnect");const e=De();ie(e,ui),bs(e,0),rt(e,this.peerId),gt(this,Se(e)),Xh(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 gf=(t,e,s,r)=>{if(Nt.has(s))throw Ge(`A Yjs Doc connected to room "${s}" already exists!`);const i=new mf(t,e,s,r);return Nt.set(s,i),i},hi=(t,e,s)=>{e.key?uf(s,e.key).then(r=>{t.send({type:"publish",topic:e.name,data:Oo(r)})}):t.send({type:"publish",topic:e.name,data:s})};class yf extends qh{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{ze(`connected (${e})`);const s=Array.from(Nt.keys());this.send({type:"subscribe",topics:s}),Nt.forEach(r=>hi(this,r,{type:"announce",from:r.peerId}))}),this.on("message",s=>{switch(s.type){case"publish":{const r=s.topic,i=Nt.get(r);if(i==null||typeof r!="string")return;const o=c=>{const d=i.webrtcConns,l=i.peerId;if(c==null||c.from===l||c.to!==void 0&&c.to!==l||i.bcConns.has(c.from))return;const p=d.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":d.size<i.provider.maxConns&&(Ve(d,c.from,()=>new zi(this,!0,c.from,i)),p());break;case"signal":if(c.signal.type==="offer"){const g=d.get(c.from);if(g){const u=c.token,f=g.glareToken;if(f&&f>u){ze("offer rejected: ",c.from);return}g.glareToken=void 0}}if(c.signal.type==="answer"){ze("offer answered by: ",c.from);const g=d.get(c.from);g.glareToken=void 0}c.to===l&&(Ve(d,c.from,()=>new zi(this,!1,c.from,i)).peer.signal(c.signal),p());break}};i.key?typeof s.data=="string"&&hf(Po(s.data),i.key).then(o):o(s.data)}}}),this.on("disconnect",()=>ze(`disconnect (${e})`))}}const tr=t=>{t.emit("status",[{connected:t.connected}])};class bf extends vo{constructor(e,s,{signaling:r=["wss://y-webrtc-eu.fly.dev"],password:i=null,awareness:o=new lf(s),maxConns:c=20+Xe(Xc()*15),filterBcConns:d=!0,peerOpts:l={}}={}){super(),this.roomName=e,this.doc=s,this.filterBcConns=d,this.awareness=o,this.shouldConnect=!1,this.signalingUrls=r,this.signalingConns=[],this.maxConns=c,this.peerOpts=l,this.key=i?df(i,e):$r(null),this.room=null,this.key.then(p=>{this.room=gf(s,this,e,p),this.shouldConnect?this.room.connect():this.room.disconnect(),tr(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=Ve(un,e,()=>new yf(e));this.signalingConns.push(s),s.providers.add(this)}),this.room&&(this.room.connect(),tr(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),e.providers.size===0&&(e.destroy(),un.delete(e.url))}),this.room&&(this.room.disconnect(),tr(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),Nt.delete(this.roomName)}),super.destroy()}}const hs=new Map,hn=new Map,vr=new Map;function xf(){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem("titan2:webrtc"))==="1"}catch{return!1}}function wf(t){if(!hs.has(t)){const e=new is({guid:`titan-space-${t}`});hs.set(t,e);const s=new Hh(`titan-space-${t}`,e);if(hn.set(t,s),xf())try{const r=new bf(`titan-space-${t}`,e,{signaling:["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com"]});vr.set(t,r)}catch{}}return hs.get(t)}function vf(t){const{widgets:e}=_t(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 _t(t){const e=wf(t),s=e.getArray("widgets"),r=e.getMap("meta"),i=hn.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 _f(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 ol(t){const e=new At;return e.set("id",t.id),e.set("name",t.name),e.set("format",t.format),e.set("source",t.source),e.set("x",t.x),e.set("y",t.y),e.set("w",t.w),e.set("h",t.h),e.set("metadata",t.metadata),e.set("createdAt",t.createdAt),e.set("updatedAt",t.updatedAt),e}function kf(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 fn=new Map;function Sf(t,e){let s=fn.get(t);s||(s=new Set,fn.set(t,s)),s.add(e)}function jf(t,e){var s;return((s=fn.get(t))==null?void 0:s.has(e))??!1}function al(t){fn.delete(t)}function Ef(t,e){const{widgets:s}=_t(t),r=new Map,i=()=>{const c=new Set,d=kf(t),l=[];s.forEach(p=>{const g=_f(p);if(!g.id||c.has(g.id))return;const u=g.format==="system",f=typeof g.source=="string"&&g.source.trim()!=="";!u&&!f||d&&!d.has(g.id)&&!jf(t,g.id)||(c.add(g.id),l.push(g))}),e(l)},o=()=>{const c=new Set;s.forEach(d=>c.add(d));for(const[d,l]of r)c.has(d)||(d.unobserve(l),r.delete(d));for(const d of c)if(!r.has(d)){const l=()=>i();d.observe(l),r.set(d,l)}i()};return s.observe(o),o(),()=>{s.unobserve(o);for(const[c,d]of r)c.unobserve(d);r.clear()}}function Nf(t,e){const{widgets:s}=_t(t),r={...e,id:`widget_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,createdAt:Date.now(),updatedAt:Date.now()};return Sf(t,r.id),s.push([ol(r)]),r}function Cf(t,e){const{widgets:s}=_t(t);let r=-1;s.forEach((i,o)=>{i.get("id")===e&&(r=o)}),r>=0&&s.delete(r,1)}function Vi(t,e,s){const{widgets:r}=_t(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 Tf(t){const{widgets:e}=_t(t);e.delete(0,e.length),al(t)}function Rf(t){var e,s,r;(e=hn.get(t))==null||e.destroy(),(s=vr.get(t))==null||s.destroy(),(r=hs.get(t))==null||r.destroy(),hn.delete(t),vr.delete(t),hs.delete(t),al(t)}const fs="titan2-spaces",Af=!0;function he(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 Ps=[{id:"home",name:"Home",icon:"Home",color:"#6366f1",widgets:[he("home-welcome","Welcome","system:soma",0,0,6,5),he("home-voice","Voice","system:voice",6,0,6,5),he("home-overview","Overview","system:overview",0,5,6,5),he("home-sessions","Sessions","system:sessions",6,5,6,5),he("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:[he("soma-main","SOMA","system:soma",0,0,8,8),he("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:[he("cp-hub","Command Post","system:command-post",0,0,12,10),he("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:[he("intel-autopilot","Autopilot","system:intelligence-autopilot",0,0,6,5),he("intel-workflows","Workflows","system:intelligence-workflows",6,0,6,5),he("intel-learning","Learning","system:intelligence-learning",0,5,6,5),he("intel-memory","Memory Graph","system:memory-graph",6,5,6,5),he("intel-selfimprove","Self-Improve","system:intelligence-self-improve",0,10,6,5),he("intel-personas","Personas","system:intelligence-personas",6,10,6,5),he("intel-wiki","Memory Wiki","system:memory-wiki",0,15,6,6),he("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:[he("infra-homelab","Homelab","system:infra-homelab",0,0,6,6),he("infra-gpu","GPU / NVIDIA","system:infra-gpu",6,0,6,6),he("infra-files","Files","system:infra-files",0,6,4,5),he("infra-logs","Logs","system:infra-logs",4,6,4,5),he("infra-telemetry","Telemetry","system:infra-telemetry",8,6,4,5),he("infra-vram","VRAM","system:vram",0,11,6,5),he("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:[he("tools-skills","Skills","system:tools-skills",0,0,6,6),he("tools-mcp","MCP Servers","system:tools-mcp",6,0,6,6),he("tools-integrations","Integrations","system:tools-integrations",0,6,4,5),he("tools-channels","Channels","system:tools-channels",4,6,4,5),he("tools-mesh","Mesh Network","system:tools-mesh",8,6,4,5),he("tools-recipes","Recipes","system:recipes",0,11,6,5),he("tools-browser","Browser","system:browser",6,11,6,5),he("tools-cron","Cron","system:cron",0,16,6,5)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"settings",name:"Settings",icon:"Settings",color:"#6b7280",widgets:[he("settings-specialists","Specialist Models","system:settings-specialists",0,0,6,8),he("settings-privacy","Privacy & Telemetry","system:settings-privacy",6,0,6,8),he("settings-general","General","system:settings-general",0,8,6,8),he("settings-security","Security","system:settings-security",6,8,6,8),he("settings-audit","Audit Log","system:settings-audit",0,16,12,6)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}],_r=11,ll={home:new Set(["home-chat"]),tools:new Set(["tools-paperclip"])},kr=new Set(["system:paperclip","system:daemon"]);function Lf(t,e){const{widgets:s,meta:r,whenSynced:i}=_t(t.id);i.then(()=>{try{const o=vf(t.id);o>0&&console.info(`[SpaceEngine] healed ${o} duplicate widget(s) in "${t.id}"`);const c=ll[t.id]??new Set;if(c.size>0||kr.size>0)for(let d=s.length-1;d>=0;d--){const l=s.get(d),p=l==null?void 0:l.get("id"),g=l==null?void 0:l.get("source"),u=typeof p=="string"&&c.has(p),f=typeof g=="string"&&kr.has(g);(u||f)&&s.delete(d,1)}if(e){for(let p=s.length-1;p>=0;p--){const g=s.get(p),u=g==null?void 0:g.get("source");(typeof u!="string"||u.trim()==="")&&s.delete(p,1)}const d=new Map;for(const p of t.widgets)d.set(p.id,p);const l=new Set;s.forEach(p=>{const g=p.get("id");if(typeof g=="string"&&d.has(g)){l.add(g);const u=d.get(g);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)l.has(p.id)||s.push([ol(p)]);r.set("seedVersion",_r)}}catch(o){console.warn(`[SpaceEngine] healYSpaceOnSync failed for "${t.id}":`,o)}})}function If(){try{const t=localStorage.getItem(fs),s=parseInt(localStorage.getItem(`${fs}-version`)||"0",10)<_r;if(Af)for(const o of Ps)Lf(o,s);if(!t||s){localStorage.setItem(`${fs}-version`,String(_r));const o=Ps.map(c=>({...c,widgets:[...c.widgets]}));return jt(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").filter(c=>{var d;return!(((d=ll[o.id])==null?void 0:d.has(c.id))??!1)}).filter(c=>!(typeof c.source=="string"&&kr.has(c.source))).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(d=>c.has(d.id)?!1:(c.add(d.id),!0))}const i=new Map(r.map(o=>[o.id,o]));return Ps.forEach(o=>{i.get(o.id)||i.set(o.id,{...o,widgets:[...o.widgets]})}),Array.from(i.values())}catch{return Ps.map(t=>({...t,widgets:[...t.widgets]}))}}let sr=null;function jt(t){sr&&clearTimeout(sr),sr=setTimeout(()=>{localStorage.setItem(fs,JSON.stringify(t))},250)}let qe=null;const ke={list(){return qe||(qe=If()),qe},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 qe=[...this.list(),e],jt(qe),e},save(t){t.updatedAt=new Date().toISOString(),qe=this.list().map(e=>e.id===t.id?t:e),jt(qe)},remove(t){qe=this.list().filter(e=>e.id!==t),jt(qe)},addWidget(t,e){if(!e.source||e.source.trim()==="")throw new Error("Widget source cannot be empty");{const s=Nf(t,e);try{const r=localStorage.getItem(fs),i=r?JSON.parse(r):[],o=i.find(c=>c.id===t);if(o)new Set((o.widgets||[]).map(d=>d.id)).has(s.id)||(o.widgets=[...o.widgets||[],s]),o.updatedAt=new Date().toISOString(),qe=i,jt(i);else{const c={id:t,name:t,widgets:[s],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};qe=[...i,c],jt(qe)}}catch{}return s}},updateWidget(t,e,s){Vi(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){Cf(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)Vi(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 Ef(t,e)},async clearSpace(t){{const{whenSynced:r}=_t(t);await r,Tf(t),Rf(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=[],jt(e))}};let ls=null;function Df(){if(ls)return ls;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 ls=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 ls=null,e}),ls}function Mf(t){const e=Of;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 Of=`
63
- <script>
64
- (function() {
65
- 'use strict';
66
-
67
- // NOTE: Prototype freezing is intentionally disabled.
68
- // Babel standalone mutates Function.prototype.toString during JSX transform.
69
- // Freezing causes "Cannot assign to read only property" errors.
70
-
71
- // Prevent eval and Function constructor abuse
72
- window.eval = function() { throw new Error('eval is disabled in sandbox'); };
73
- const OriginalFunction = window.Function;
74
- window.Function = function(...args) {
75
- const body = args.pop() || '';
76
- if (body.includes('import') && body.includes('http')) {
77
- throw new Error('Dynamic imports with URLs are disabled in sandbox');
78
- }
79
- return OriginalFunction.apply(this, [...args, body]);
80
- };
81
-
82
- const pending = new Map();
83
- let msgId = 0;
84
- let reactRoot = null;
85
-
86
- function send(type, payload) {
87
- const id = ++msgId;
88
- return new Promise((resolve, reject) => {
89
- pending.set(id, { resolve, reject });
90
- window.parent.postMessage({ type, id, payload }, '*');
91
- });
92
- }
93
-
94
- window.addEventListener('message', (e) => {
95
- // Resolve pending iframe promises (parent responses to titan.* calls)
96
- if (typeof e.data?.id === 'number' && pending.has(e.data.id)) {
97
- const p = pending.get(e.data.id);
98
- pending.delete(e.data.id);
99
- if (e.data.error) p.reject(new Error(e.data.error));
100
- else p.resolve(e.data.payload);
101
- return;
102
- }
103
-
104
- // Handle parent commands
105
- if (e.data?.type === 'render') {
106
- handleRender(e.data.id, e.data.payload);
107
- }
108
- if (e.data?.type === 'execute') {
109
- handleExecute(e.data.id, e.data.payload);
110
- }
111
- });
112
-
113
- const titan = {
114
- fetch: (url, opts) => {
115
- try { new URL(url, 'https://example.com'); } catch {
116
- throw new Error('Invalid URL: ' + url);
117
- }
118
- return send('fetch', { url, options: opts });
119
- },
120
- api: { call: (endpoint, body) => send('api', { endpoint, body }) },
121
- state: {
122
- get: (key) => send('state', { action: 'get', key }),
123
- set: (key, value) => send('state', { action: 'set', key, value }),
124
- },
125
- canvas: {
126
- createWidget: (def) => send('canvas', { action: 'createWidget', def }),
127
- updateWidget: (id, patch) => send('canvas', { action: 'updateWidget', id, patch }),
128
- removeWidget: (id) => send('canvas', { action: 'removeWidget', id }),
129
- listWidgets: () => send('canvas', { action: 'listWidgets' }),
130
- },
131
- // v6.0 Step 8 — Widget-runtime API surface.
132
- // titan.tools.run / titan.tools.list — invoke or enumerate any
133
- // TITAN tool from inside a widget. Widgets become first-class
134
- // agent surfaces (not just dumb UI).
135
- tools: {
136
- list: () => send('api', { endpoint: '/api/tools', body: { method: 'GET' } }),
137
- run: (name, args) => send('api', { endpoint: '/api/tools/run', body: { name, args: args || {} } }),
138
- },
139
- // titan.agent.ask — sub-question to TITAN itself. Widgets can
140
- // delegate parts of their work back to the agent loop.
141
- agent: {
142
- ask: (prompt) => send('api', { endpoint: '/api/message', body: { content: String(prompt) } }),
143
- },
144
- // titan.memory.get / .set — typed access to widget-scoped memory.
145
- memory: {
146
- get: (key) => send('api', { endpoint: '/api/memory/' + encodeURIComponent(key), body: { method: 'GET' } }),
147
- set: (key, value) => send('api', { endpoint: '/api/memory', body: { key, value } }),
148
- },
149
- // titan.persona — read-only handle to the active persona content.
150
- persona: {
151
- get: () => send('api', { endpoint: '/api/persona/current', body: { method: 'GET' } }),
152
- },
153
- // titan.space — read-only handle to the active Space (id, name,
154
- // intent, widget count).
155
- space: {
156
- active: () => send('api', { endpoint: '/api/spaces', body: { method: 'GET' } }),
157
- },
158
- log: (...args) => send('log', { args: args.map(a => String(a)) }),
159
- };
160
-
161
- window.titan = titan;
162
-
163
- function handleRender(msgId, payload) {
164
- const { format, source } = payload;
165
- const root = document.getElementById('root');
166
- root.innerHTML = '';
167
- const loadingEl = document.getElementById('sandbox-loading');
168
- if (loadingEl) loadingEl.style.display = 'none';
169
-
170
- // Unmount previous React root to prevent memory leaks
171
- if (reactRoot) {
172
- try { reactRoot.unmount(); } catch (e) {}
173
- reactRoot = null;
174
- }
175
-
176
- function showError(title, detail) {
177
- root.innerHTML = '';
178
- const wrap = document.createElement('div');
179
- wrap.style.cssText = 'padding:16px;font-family:monospace;font-size:12px;line-height:1.5;';
180
- const h = document.createElement('div');
181
- h.style.cssText = 'color:#ef4444;font-weight:bold;margin-bottom:8px;';
182
- h.textContent = title;
183
- const d = document.createElement('pre');
184
- d.style.cssText = 'color:#a1a1aa;white-space:pre-wrap;word-break:break-word;margin:0;';
185
- d.textContent = detail;
186
- wrap.appendChild(h);
187
- wrap.appendChild(d);
188
- root.appendChild(wrap);
189
- }
190
-
191
- try {
192
- if (format === 'react') {
193
- console.log('[sandbox] render react, source length:', source.length);
194
- if (!source || source.trim() === '') {
195
- throw new Error('Source is empty');
196
- }
197
- if (typeof React === 'undefined') {
198
- throw new Error('React not loaded — the inlined React bundle failed to evaluate inside the sandbox.');
199
- }
200
- if (typeof ReactDOM === 'undefined') {
201
- throw new Error('ReactDOM not loaded — the inlined ReactDOM bundle failed to evaluate inside the sandbox.');
202
- }
203
- if (typeof Babel === 'undefined') {
204
- throw new Error('Babel not loaded — the inlined Babel bundle failed to evaluate inside the sandbox.');
205
- }
206
-
207
- // ── 1. Strip export-default variations so Babel doesn't choke ──
208
- // Using simple string operations (no regex backslashes) to avoid Vite stripping
209
- let src = source;
210
- const lines = src.split('\\n');
211
- const outLines = [];
212
- for (let i = 0; i < lines.length; i++) {
213
- let line = lines[i];
214
- const trimmed = line.trim();
215
- if (trimmed.startsWith('export default function ')) {
216
- const rest = trimmed.slice('export default function '.length);
217
- const name = rest.split('(')[0].trim();
218
- line = '/* export default function ' + name + ' */ function ' + rest;
219
- } else if (trimmed.startsWith('export default class ')) {
220
- const rest = trimmed.slice('export default class '.length);
221
- const name = rest.split(' ')[0].trim().split('{')[0].trim();
222
- line = '/* export default class ' + name + ' */ class ' + rest;
223
- } else if (trimmed.startsWith('export default ')) {
224
- line = '/* export default */';
225
- }
226
- outLines.push(line);
227
- }
228
- src = outLines.join('\\n');
229
-
230
- // ── 2. Detect candidate component names ──
231
- const detected = new Set();
232
- const srcLines = src.split('\\n');
233
- const keywords = ['function ', 'const ', 'let ', 'var ', 'class '];
234
- for (let i = 0; i < srcLines.length; i++) {
235
- const trimmed = srcLines[i].trimStart();
236
- for (let k = 0; k < keywords.length; k++) {
237
- const kw = keywords[k];
238
- if (trimmed.startsWith(kw)) {
239
- const after = trimmed.slice(kw.length);
240
- const endIdx = after.search(/[\\s\\(=]/);
241
- const name = endIdx > 0 ? after.slice(0, endIdx) : after;
242
- if (name.length > 0 && name[0] >= 'A' && name[0] <= 'Z') {
243
- detected.add(name);
244
- }
245
- }
246
- }
247
- }
248
-
249
- const names = ['Widget', ...Array.from(detected)];
250
- console.log('[sandbox] detected names:', names.join(', '));
251
-
252
- // ── 3. Babel transform (JSX only, classic runtime → React.createElement) ──
253
- let code;
254
- try {
255
- const babelResult = Babel.transform(src, { presets: [['react', { runtime: 'classic' }]], filename: 'widget.tsx' });
256
- code = babelResult.code;
257
- console.log('[sandbox] babel ok, code length:', code.length);
258
- } catch (babelErr) {
259
- throw new Error('Babel transform failed: ' + babelErr.message);
260
- }
261
-
262
- // ── 3.5 Auto-inject React hooks and the legacy gallery render()
263
- // helper. Older templates end with render(<MyWidget/>); while newer
264
- // generated code is component-only and gets auto-detected below.
265
- const hookDecl = 'const { useState, useEffect, useRef, useCallback, useMemo, useContext, useReducer, useLayoutEffect, useId, useTransition, useDeferredValue, useImperativeHandle, useDebugValue, useSyncExternalStore } = React;';
266
- const renderDecl = 'window.__titanRenderedElement = null; const render = (node) => { window.__titanRenderedElement = node; };';
267
- code = hookDecl + '\\n' + renderDecl + '\\n' + code;
268
-
269
- // ── 4. Eval the code and find the component ──
270
- const returnChecks = names.map(n =>
271
- 'if (typeof ' + n + ' !== "undefined" && ' + n + ' != null) return ' + n + ';'
272
- ).join('\\n') + '\\nreturn undefined;';
273
-
274
- let Widget;
275
- try {
276
- const fn = new Function('React', 'ReactDOM', 'titan', code + '\\n' + returnChecks);
277
- Widget = fn(React, ReactDOM, titan);
278
- console.log('[sandbox] eval ok, Widget type:', typeof Widget, 'name:', Widget?.name || Widget?.displayName || 'n/a');
279
- } catch (evalErr) {
280
- throw new Error('Eval failed: ' + evalErr.message + '\\nDetected names: ' + names.join(', '));
281
- }
282
-
283
- const renderedElement = window.__titanRenderedElement;
284
- if (!Widget && !renderedElement) {
285
- throw new Error('No React component found. Detected names: ' + names.join(', ') + '. The code must define a capitalized component (e.g., function Widget() {}).');
286
- }
287
-
288
- // ── 5. Render ──
289
- try {
290
- reactRoot = ReactDOM.createRoot(root);
291
- reactRoot.render(renderedElement || React.createElement(Widget, { titan }));
292
- console.log('[sandbox] react render dispatched');
293
- } catch (renderErr) {
294
- throw new Error('React render failed: ' + renderErr.message);
295
- }
296
- } else if (format === 'vanilla') {
297
- const fn = new Function('container', 'titan', 'return (' + source + ')(container, titan)');
298
- const cleanup = fn(root, titan);
299
- window.__widgetCleanup = cleanup;
300
- } else if (format === 'html') {
301
- root.innerHTML = source;
302
- }
303
- window.parent.postMessage({ type: 'rendered', id: msgId }, '*');
304
- } catch (err) {
305
- console.error('[sandbox] render error:', err.name, err.message);
306
- showError(err.name + ': ' + err.message, err.stack || '');
307
- window.parent.postMessage({ type: 'error', id: msgId, error: err.message }, '*');
308
- }
309
- }
310
-
311
- function handleExecute(msgId, payload) {
312
- const { code } = payload;
313
- const logs = [];
314
- const originals = {};
315
- ['log','info','warn','error','debug'].forEach(m => {
316
- originals[m] = console[m];
317
- console[m] = (...args) => {
318
- logs.push({ level: m, text: args.map(a => String(a)).join(' ') });
319
- originals[m](...args);
320
- };
321
- });
322
-
323
- const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
324
-
325
- // Shadow dangerous globals so sandboxed code cannot access them directly.
326
- const forbiddenGlobals = [
327
- 'window','globalThis','self','top','parent','document','location',
328
- 'fetch','XMLHttpRequest','WebSocket','EventSource',
329
- 'localStorage','sessionStorage','indexedDB','navigator','history',
330
- ];
331
-
332
- const runner = new AsyncFunction(
333
- ...forbiddenGlobals,
334
- '__titan',
335
- '"use strict";\\n' +
336
- forbiddenGlobals.map(g => 'const ' + g + ' = undefined;').join('\\n') + '\\n' +
337
- code
338
- );
339
-
340
- (async () => {
341
- try {
342
- const result = await runner(...forbiddenGlobals.map(() => undefined), titan);
343
- Object.keys(originals).forEach(m => console[m] = originals[m]);
344
- window.parent.postMessage({ type: 'result', id: msgId, payload: { status: 'success', logs, result: formatValue(result), resultText: formatValue(result) } }, '*');
345
- } catch (err) {
346
- Object.keys(originals).forEach(m => console[m] = originals[m]);
347
- window.parent.postMessage({ type: 'result', id: msgId, payload: { status: 'error', logs, error: { message: err.message, name: err.name, stack: err.stack } } }, '*');
348
- }
349
- })();
350
- }
351
-
352
- function formatValue(v) {
353
- if (v === undefined) return 'undefined';
354
- if (v === null) return 'null';
355
- if (typeof v === 'string') return v;
356
- if (typeof v === 'number' || typeof v === 'boolean') return String(v);
357
- if (typeof v === 'function') return '[Function]';
358
- if (v instanceof Error) return v.stack || v.message;
359
- if (v instanceof Node) return '<' + v.tagName?.toLowerCase() + '>';
360
- try { return JSON.stringify(v); } catch { return String(v); }
361
- }
362
-
363
- window.parent.postMessage({ type: 'ready' }, '*');
364
- })();
365
- <\/script>
366
- </body>
367
- </html>`;class cl{constructor(e,s){$e(this,"iframe",null);$e(this,"pending",new Map);$e(this,"msgId",0);$e(this,"ready",!1);$e(this,"readyQueue",[]);$e(this,"onLog");$e(this,"messageHandler");$e(this,"messageListener");$e(this,"observer");this.iframe=e,this.onLog=s==null?void 0:s.onLog,this.init()}init(){const e=this.iframe;Df().then(i=>{!this.iframe||!document.contains(e)||(e.srcdoc=Mf(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(d=>d()),this.readyQueue=[];return}if(typeof(o==null?void 0:o.id)=="number"&&this.pending.has(o.id)){const d=this.pending.get(o.id);this.pending.delete(o.id),o.type==="error"?d.reject(new Error(o.error||"Sandbox error")):d.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:d,options:l}=r||{},p=localStorage.getItem("titan-token"),g={...(l==null?void 0:l.headers)||{}};let u=!1;try{typeof d=="string"&&(d.startsWith("/")?u=!0:u=new URL(d,window.location.href).origin===window.location.origin)}catch{}p&&u&&(g.Authorization=`Bearer ${p}`);const f=await fetch(d,{...l,headers:g}),x=await f.text();let y;try{y=JSON.parse(x)}catch{}c={ok:f.ok,status:f.status,text:x,json:y}}else if(e==="api"){const{endpoint:d,body:l}=r||{},p=localStorage.getItem("titan-token"),g={"Content-Type":"application/json"};let u="POST",f=l;if(l&&typeof l=="object"&&("method"in l||"headers"in l)&&!("content"in l)&&!("message"in l)&&!("action"in l)){const m=l;typeof m.method=="string"&&(u=m.method.toUpperCase()),m.headers&&Object.assign(g,m.headers),f=m.body}p&&(g.Authorization=`Bearer ${p}`);let x=typeof d=="string"?d:"";x.startsWith("/api/")||(x.startsWith("/")?x="/api"+x:x="/api/"+x);const y={method:u,headers:g};u!=="GET"&&u!=="HEAD"&&f!==void 0&&(y.body=typeof f=="string"?f:JSON.stringify(f));const E=await fetch(x,y),L=await E.text();let v;try{v=JSON.parse(L)}catch{}c={...v&&typeof v=="object"&&!Array.isArray(v)?v:{},status:E.status,body:v??L,ok:E.ok}}else if(e==="state"){const{action:d,key:l,value:p}=r||{};if(d==="get"){const g=localStorage.getItem("titan:sandbox:"+l);c=g?JSON.parse(g):void 0}else d==="set"&&(localStorage.setItem("titan:sandbox:"+l,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,d;(d=(c=this.iframe)==null?void 0:c.contentWindow)==null||d.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 Pf(t=3e5){const[e,s]=w.useState(null),[r,i]=w.useState(!1),o=w.useCallback(async()=>{i(!0);try{const l=await ge("/api/update");if(l.ok){const p=await l.json();s(p)}}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 ge("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restart:l})})).json()}catch(p){return{ok:!1,error:p.message}}},[]),d=w.useCallback(async(l,p=3e4)=>{const g=Date.now(),u=1500;for(;Date.now()-g<p;){await new Promise(f=>setTimeout(f,u));try{const f=await ge("/api/update");if(f.ok){const x=await f.json();if(x.current&&x.current!==l)return s(x),x.current}}catch{}}return null},[]);return{info:e,checking:r,triggerUpdate:c,waitForReload:d}}function Wf(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),d=!!i.shift===s.shiftKey,l=!!i.alt===s.altKey;if(o&&c&&d&&l){s.preventDefault(),i.action();return}}},[t]);w.useEffect(()=>(window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)),[e])}const Bf=[{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 Uf({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:Bf.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 Ff={Home:n.jsx(Cl,{className:"w-3.5 h-3.5"}),Brain:n.jsx(xt,{className:"w-3.5 h-3.5"}),Terminal:n.jsx(lo,{className:"w-3.5 h-3.5"}),Network:n.jsx(ao,{className:"w-3.5 h-3.5"}),Server:n.jsx(Ir,{className:"w-3.5 h-3.5"}),Wrench:n.jsx(Tr,{className:"w-3.5 h-3.5"}),Settings:n.jsx(Cr,{className:"w-3.5 h-3.5"}),FileText:n.jsx(yn,{className:"w-3.5 h-3.5"})};function $f({currentSpaceId:t,onSpaceSelect:e}){const[s,r]=w.useState(!1),[i,o]=w.useState(""),c=ke.list(),d=()=>{if(!i.trim())return;const l=ke.create(i.trim());o(""),e(l.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(l=>!l),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(Ul,{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(l=>n.jsxs("button",{onClick:()=>e(l.id),className:`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-left text-[11px] transition-colors ${l.id===t?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#71717a] hover:bg-[#27272a]/40 hover:text-[#a1a1aa]"}`,children:[n.jsx("span",{style:{color:l.color||"#52525b"},children:Ff[l.icon||""]||n.jsx("div",{className:"w-3.5 h-3.5 rounded-full",style:{background:l.color||"#52525b"}})}),n.jsx("span",{className:"truncate",children:l.name})]},l.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:l=>o(l.target.value),onKeyDown:l=>l.key==="Enter"&&d(),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:d,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(Fl,{className:"w-3.5 h-3.5"})})]})]})]})}const Sr=["_____javascript","_____react","_____tool","_____widget","_____canvas","_____framework","_____transient"];function dl(t,e){let s=e;for(;s>0&&t[s-1]!==`
368
- `&&t[s-1]!=="\r";)s--;return s}function ul(t,e){let s=e;for(;s<t.length&&t[s]!==`
369
- `&&t[s]!=="\r";)s++;return s}function jr(t,e,s){const r=dl(t,e),i=ul(t,e+s.length);return!t.slice(r,e).trim()&&!t.slice(e+s.length,i).trim()}function zf(t){return t.replace(/\n_+\s*$/g,"").trimEnd()}function Hf(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 hl(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=Hf(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 Vf(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 Gf(t){const e=[];let s=0;for(;s<t.length;){let r=null,i=-1;for(const u of Sr){const f=t.indexOf(u,s);f!==-1&&(i===-1||f<i)&&jr(t,f,u)&&(i=f,r=u)}if(!r||i===-1)break;if(r==="_____framework"||r==="_____transient"){s=i+r.length;continue}const o=dl(t,i);let d=ul(t,i+r.length);t.startsWith(`\r
370
- `,d)?d+=2:(t[d]===`
371
- `||t[d]==="\r")&&(d+=1);let l=t.length;for(const u of Sr){const f=t.indexOf(u,d);f!==-1&&f<l&&jr(t,f,u)&&(l=f)}let p=t.slice(d,l).trimEnd();p=zf(p);const g={gate:r,code:p,leadingText:t.slice(s,o).trim()};g.action=hl(g),e.push(g),s=l}return e.length===0&&t.trim()&&e.push({gate:"_____transient",code:"",leadingText:t.trim()}),e}function qf(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(`
372
- `)}).join(`
373
-
374
- `)}function Yf(t){return{role:"framework",content:qf(t),timestamp:Date.now(),executions:t}}function Kf(t,e){let s=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)jr(t,r,e)&&s++,r+=e.length;return s}function Jf(t){const s=Sr.filter(r=>r!=="_____framework"&&r!=="_____transient").map(r=>({gate:r,count:Kf(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 Ys(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(l=>c<l.x+l.w&&c+e>l.x&&o<l.y+l.h&&o+s>l.y))return{x:c,y:o};return{x:0,y:i+s}}function Xf(t){const e=t.widgets||[],s=e.length>0?e.map(l=>{const p=l.source?l.source.slice(0,150).replace(/\n/g," ").replace(/\s+/g," ").trim():"(no source)";return`- ${l.name} (id: ${l.id}, format: ${l.format}, ${l.w}x${l.h}) — "${p}…"`}).join(`
375
- `):"(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:"",d=e.length>0?`${e.length} widget${e.length===1?"":"s"} on canvas (system: ${e.filter(l=>l.format==="system").length}, generated: ${e.filter(l=>l.format!=="system").length})`:"canvas is empty";return`BASE LAW — These rules override all other instructions:
376
- 1. The user is NOT technical. They do NOT know about React, widgets, gates, or code. NEVER use technical jargon in responses.
377
- 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.
378
- 3. USE AN EXECUTION GATE for all browser work. Never describe what you would do instead of doing it.
379
- 4. One short staging sentence, then the gate on its own line. No narrated step-by-step plans.
380
- 5. Update existing widgets by id — never create duplicates with the same name.
381
- 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.
382
- 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.
383
- 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.
384
- 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.
385
- 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.
386
-
387
- 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.
388
-
389
- ## Build-on-demand workflow (v6.0 default)
390
-
391
- The user's work has a shape. Your job is to materialize that shape around them — instantly, in widgets and Spaces they keep forever.
392
-
393
- **For a single visual/tool ask:**
394
- 1. \`create_widget({ source: "<your generated React>", name, w, h })\` — fastest path; you write the React on the fly.
395
- 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.)
396
- 3. After it lands, refine via \`update_widget\` as the user iterates.
397
-
398
- **For a new domain of work:**
399
- 1. \`create_space({ name, preset?, intent, starterWidgets? })\` — make a dedicated environment with its own posture.
400
- 2. Switch into it via \`switch_space\` (or pass \`makeActive:true\` at create time).
401
- 3. Within the Space, build widgets via \`create_widget\` to populate it.
402
-
403
- **For system panels (vram, cron, logs, backup, training, etc.):**
404
- 1. \`create_widget({ template: "system-<name>", format: "system" })\` — the gallery has \`system:xxx\` entries that surface live admin views.
405
-
406
- ## Gallery (a shortcut for known templates)
407
-
408
- The gallery has 60+ pre-built templates covering finance / productivity / automation / smart-home / agents / software-builder / media / etc. Use \`gallery_search\` when:
409
- - The user's ask exactly matches a known template name ("pomodoro", "stock tracker", "weather", "kanban")
410
- - You want a verified-good starting point to refine
411
- - You're building a system widget (vram, cron, training, etc.)
412
-
413
- 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.
414
-
415
- ## How to respond to common requests
416
-
417
- User says something casual → You build the right thing immediately.
418
-
419
- "Show me the weather" → Build a weather panel with current temp, forecast, and icons.
420
- "I need a todo list" → Build a todo list with add/check/delete functionality.
421
- "Clock" → Build a live digital clock.
422
- "Track my stocks" → Build a stock tracker panel.
423
- "Photo gallery" → Build a grid of images with lightbox.
424
- "Calculator" → Build a working calculator.
425
- "Load eBay" / "Show me YouTube" / "Open Wikipedia" → Build a website panel (see "Loading external websites" below).
426
- "Analyze AAPL stock" → Build an analyzer panel that spawns an analyst sub-agent (see "Agent-powered widgets" below).
427
- "Research climate change" → Build a research panel powered by the researcher sub-agent.
428
- "Summarize this URL ___" → Build a summarizer panel that fetches + summarizes via an agent call.
429
- "Translate this to Spanish" → Build a translator panel.
430
- "Code review my repo" → Build a reviewer panel that runs the code-review skill.
431
- "Watch BTC and alert me below 50k" → Build an automation panel with a polling timer + alert (see "Automating inside widgets" below).
432
- "Every hour, post my schedule" → Build a scheduled-task widget using the cron skill.
433
- "Show my Slack messages" → Build a message panel via the slack channel.
434
- "Turn on the kitchen lights" → Use ha_control immediately (no widget needed for one-off actions).
435
- "What's on my screen" → Use the screenshot tool, render result as a panel image.
436
- "Monitor my CPU" → Build a live CPU usage chart.
437
- "A button that fetches news" → Build a news reader panel with a refresh button.
438
- "Show my calendar" → Build a calendar view panel.
439
- "I want a timer" → Build a countdown timer with start/stop/reset.
440
- "Draw a chart of sales" → Build a bar/line chart panel.
441
- "Dark mode" → Update existing widgets to use dark colors.
442
- "Make it bigger" → Update the widget dimensions.
443
- "Fix the clock" → Update the existing Clock widget's code.
444
-
445
- ## What you NEVER do
446
-
447
- NEVER ask the user to specify technical details:
448
- - "Would you like a React component or plain HTML?" → WRONG. Just pick the best option.
449
- - "Do you want me to use _____react or _____widget?" → WRONG. The user doesn't know what those are.
450
- - "Should I fetch data from an API or use static data?" → WRONG. Decide based on the request.
451
- - "What styling would you prefer?" → WRONG. Use clean, modern defaults.
452
-
453
- NEVER explain your technical choices to the user:
454
- - "I'll use React.useState to manage the timer state..." → WRONG. The user doesn't care.
455
- - "I'm going to use the _____react gate..." → WRONG. Just do it.
456
-
457
- NEVER output code as prose. If you write code, it goes through a gate.
458
-
459
- ## Current Context (live snapshot — updated every turn)
460
- Right now: ${r.toLocaleString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric"})} ${r.toLocaleTimeString("en-US")} (${i})
461
- Space: ${t.name} (id: \`${t.id}\`)
462
- Route: ${c||"/"}
463
- URL: ${o||"(unknown)"}
464
- Canvas: ${d}
465
- ${t.agentInstructions?`Space instructions from the user: ${t.agentInstructions}`:""}
466
-
467
- ## Current Canvas Widgets
468
- 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.
469
- ${s}
470
-
471
- ## Execution Protocol
472
- When you need to do browser-side work, you MUST use one of these gates on their own line.
473
- The gate MUST be alone on its line — no other text on the same line.
474
-
475
- ### _____javascript
476
- For running scripts, fetching data from APIs, or automating the canvas.
477
- Use when the user asks for: data fetching, API calls, automation, file operations, batch updates.
478
-
479
- Available APIs inside javascript:
480
- - titan.fetch(url, opts) — fetch data from the internet
481
- - titan.api.call(endpoint, body) — call backend APIs
482
- - titan.state.get(key) / titan.state.set(key, value) — save data between sessions
483
- - titan.canvas.createWidget(def) — create a new panel on the canvas
484
- - titan.canvas.updateWidget(id, patch) — update an existing panel
485
- - titan.canvas.removeWidget(id) — remove a panel
486
- - titan.canvas.listWidgets() — list all panels
487
- - console.log(...) — shows output in telemetry
488
-
489
- Use 'await' at the top level. Always 'return' a value if you want it shown.
490
-
491
- GOOD:
492
- _____javascript
493
- const res = await titan.fetch('https://api.weather.gov/stations/KNYC/observations/latest');
494
- const data = await res.json();
495
- const temp = data.properties.temperature.value;
496
- console.log('Temperature:', temp);
497
- return temp;
498
-
499
- BAD (do NOT do this):
500
- _____javascript
501
- fetch('...').then(r => r.json()).then(data => console.log(data))
502
-
503
- ### _____react
504
- For building visual panels, dashboards, interactive tools, charts, lists, forms, clocks, galleries, etc.
505
- Use when the user asks for: anything visual, interactive, a tool, a panel, a display, a chart, a form.
506
- This is the DEFAULT gate for most user requests — use it unless you specifically need to fetch data first.
507
-
508
- Rules:
509
- 1. Define ONE top-level component with a Capitalized name (e.g. \`Weather\`, \`TodoList\`, \`Clock\`).
510
- 2. Do NOT use \`export default\` — it is stripped automatically.
511
- 3. Do NOT render inline with '<Widget />' — just define the component.
512
- 4. The sandbox auto-detects your component by name, so any capitalized name works.
513
-
514
- GOOD:
515
- _____react
516
- function Weather() {
517
- const [temp, setTemp] = React.useState(72);
518
- return <div style={{ padding: 20, fontSize: 24 }}>{temp}°F</div>;
519
- }
520
-
521
- BAD (export default is forbidden):
522
- _____react
523
- function Weather() { return <div>72°F</div>; }
524
- export default Weather;
525
-
526
- ### _____widget
527
- For creating or updating widgets via JSON. Rarely needed — prefer _____react.
528
- - To CREATE: emit a JSON widget definition (no \`id\` field).
529
- - To UPDATE: include the \`id\` field of the widget you want to modify.
530
-
531
- CREATE example:
532
- _____widget
533
- { "name": "Clock", "format": "react", "source": "function Widget() { return <div>12:00</div>; }" }
534
-
535
- UPDATE example:
536
- _____widget
537
- { "id": "widget_1234567890_abc12", "source": "function Widget() { return <div>Fixed clock</div>; }" }
538
-
539
- Or for raw React source (create only):
540
- _____widget
541
- function Widget() {
542
- return <div>Hello from widget</div>;
543
- }
544
-
545
- ### _____canvas (v6.0.5 — preferred for canvas mutations)
546
- 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.
547
-
548
- The body is a JSON array of action objects. Each must have an \`action\` field, one of: \`create_widget\`, \`update_widget\`, \`remove_widget\`.
549
-
550
- CREATE shape: { "action": "create_widget", "name": "Clock", "format": "react", "source": "function Widget() {...}", "w": 4, "h": 4 }
551
- UPDATE shape: { "action": "update_widget", "id": "widget_xxx", "patch": { "name": "Renamed Clock" } }
552
- REMOVE shape: { "action": "remove_widget", "id": "widget_xxx" }
553
-
554
- Example — user asks for a "coding setup":
555
- _____canvas
556
- [
557
- { "action": "create_widget", "name": "Pomodoro", "format": "react", "source": "...", "w": 4, "h": 3 },
558
- { "action": "create_widget", "name": "Todo", "format": "react", "source": "...", "w": 4, "h": 5 },
559
- { "action": "create_widget", "name": "Stack Overflow Search", "format": "react", "source": "...", "w": 4, "h": 6 }
560
- ]
561
-
562
- Use \`_____canvas\` whenever you'd otherwise issue ≥2 widget tool calls in the same turn. For one widget, \`_____react\` is still simpler.
563
-
564
- ### _____tool
565
- For calling backend tools or MCP servers.
566
-
567
- _____tool
568
- { "action": "search", "query": "deployment logs" }
569
-
570
- ## How to handle multi-step requests
571
-
572
- If the user asks for something that needs data first:
573
- 1. Use _____javascript to fetch the data.
574
- 2. Use the telemetry result to build the widget with _____react in the next turn.
575
-
576
- Example:
577
- User: "Show me the weather in New York"
578
- Turn 1: "Fetching weather data."
579
- _____javascript
580
- const res = await titan.fetch('https://api.weather.gov/stations/KNYC/observations/latest');
581
- const data = await res.json();
582
- return { temp: data.properties.temperature.value, conditions: data.properties.textDescription };
583
-
584
- Turn 2: (after receiving telemetry with temp and conditions)
585
- "Building the weather panel."
586
- _____react
587
- function Weather() {
588
- const [temp] = React.useState(72);
589
- const [conditions] = React.useState('Partly Cloudy');
590
- return (
591
- <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
592
- <h2>New York Weather</h2>
593
- <div style={{ fontSize: 48 }}>{temp}°F</div>
594
- <div>{conditions}</div>
595
- </div>
596
- );
597
- }
598
-
599
- ## TITAN can build literally anything — assume yes, then build
600
- 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.
601
-
602
- 🎧 Music/DJ — BPM analyzer, key detector, Beatport browser, Spotify controller, lyrics fetcher, music theory helper, sample library indexer, DJ set planner.
603
- 💰 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.
604
- 🏃 Health/Fitness — habit tracker, mood journal with AI sentiment, workout planner, sleep summary, medication reminder, calorie tracker via photo, water intake.
605
- 🎨 Creative — image generator (image_gen tool), color palette, logo concepts, story brainstormer, lyric assistant, mood board, video script writer, thumbnail generator.
606
- ✈️ Travel — flight tracker, itinerary builder, currency for destination, translation phrasebook, restaurant finder, transit info.
607
- 🎮 Gaming — Steam library, Twitch live embed, D&D character sheet, chess analyzer, speedrun timer, achievement tracker.
608
- 🏢 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.
609
- 📱 Social media — multi-platform composer (Twitter/IG/LinkedIn/TikTok/FB), post scheduler with AI caption variants, engagement dashboard, comment moderation, hashtag generator, content calendar.
610
- 🍳 Cooking — recipe finder by available ingredients, meal planner, multi-pot timer, wine pairing, nutrition calculator, grocery export.
611
- 🚗 Vehicle — Tesla status/control (Tony has Auth for Tesla installed), trip planner with charging stops, maintenance log, fuel cost tracker.
612
- 🏠 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.
613
- 🤖 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.
614
- 📚 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.
615
- 📄 Document/Writing — markdown editor with AI grammar, resume builder with job-targeted variants, email reply suggester, git commit message generator, documentation generator.
616
- 🛠️ Devops — service health grid, deploy pipeline status, log search, incident runbook, on-call rotation viewer, build status.
617
- 🛒 E-commerce — order tracking, inventory monitor, pricing optimizer (competitor scraper), review aggregator.
618
- 🐾 Lifestyle — pet feeding log, plant watering tracker, vet reminders, daily journal.
619
-
620
- How to compose these:
621
- • Read-only data widgets → titan.fetch(externalAPI) + setInterval refresh
622
- • Sites that allow framing → _____react with <iframe>
623
- • Sites that block framing → browser_screenshot tool snapshot
624
- • Anything needing an LLM → titan.api.call('/api/message', { content }) inside a button handler
625
- • Recurring/scheduled work → cron skill via titan.api.call
626
- • Reactive triggers → event_triggers skill
627
- • Multi-step research → 'Use the researcher sub-agent to …'
628
- • Code work → 'Use the coder sub-agent to …'
629
-
630
- When in doubt about what the user wants, ASK ONE clarifying question MAX, then build. Never trade speed of building for clarification depth.
631
-
632
- ## Loading external websites
633
- 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:
634
-
635
- <example_handling>
636
- 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.
637
- </example_handling>
638
-
639
- <anti_pattern>
640
- USER: "Build a stock analyzer for AAPL"
641
- WRONG: "Adding an eBay panel to your canvas. _____react function WebPanel() { const url = 'https://www.ebay.com'... }"
642
- 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}...\` }) ... }"
643
- The user's CURRENT message determines the build. NEVER reuse an example's domain content.
644
- </anti_pattern>
645
-
646
- PATTERN A — direct iframe (try this FIRST for most sites):
647
- Many sites allow being embedded. Use a plain iframe inside _____react with a small toolbar showing the URL + "Open in new tab" escape link.
648
-
649
- <example name="website-panel-shape">
650
- _____react
651
- function REPLACE_WITH_RELEVANT_NAME() {
652
- const url = "REPLACE_WITH_REAL_URL";
653
- return (
654
- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#0a0a0f' }}>
655
- <div style={{ padding: '6px 12px', borderBottom: '1px solid #27272a', fontSize: 11, color: '#a1a1aa', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
656
- <span>{url}</span>
657
- <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: '#818cf8', textDecoration: 'none' }}>Open in new tab ↗</a>
658
- </div>
659
- <iframe src={url} style={{ flex: 1, border: 0, background: 'white' }} title="WebPanel" />
660
- </div>
661
- );
662
- }
663
- </example>
664
-
665
- PATTERN B — server-rendered screenshot (when iframe is blocked):
666
- 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.
667
-
668
- 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.
669
-
670
- PATTERN C — proxied content (when iframe blocked AND user wants live interactive content):
671
- 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.
672
-
673
- 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.
674
-
675
- ## Agent-powered widgets — let widgets call sub-agents
676
- 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.
677
-
678
- For specialized work, ask for a SPECIFIC sub-agent template by prepending an instruction:
679
- - analyst → data analysis, decisions, comparisons
680
- - researcher → multi-source web research with citations
681
- - coder → write code to disk
682
- - browser → navigate + scrape websites with Playwright
683
- - explorer → read-only web research
684
- - reporter → produce a polished markdown document
685
- - fact_checker → verify claims against sources
686
-
687
- <example name="agent-powered-widget-shape">
688
- _____react
689
- function REPLACE_WITH_RELEVANT_NAME() {
690
- const [input, setInput] = React.useState('REPLACE_WITH_DEFAULT');
691
- const [report, setReport] = React.useState('Click REPLACE_WITH_ACTION to start.');
692
- const [busy, setBusy] = React.useState(false);
693
- const run = async () => {
694
- setBusy(true); setReport('Working…');
695
- try {
696
- const res = await titan.api.call('/api/message', {
697
- content: \`Use the REPLACE_WITH_TEMPLATE sub-agent to REPLACE_WITH_TASK for \${input}. Be concise.\`,
698
- });
699
- // titan.api.call returns { status, body, ok, ...flattened body fields }.
700
- // The /api/message response is { content, sessionId, ... } so either
701
- // res.body?.content (canonical) or res.content (flattened) works.
702
- setReport(res?.body?.content || res?.content || 'No response.');
703
- } catch (e) {
704
- setReport('Error: ' + (e?.message || e));
705
- } finally { setBusy(false); }
706
- };
707
- return (
708
- <div style={{ padding: 16, fontFamily: 'system-ui', color: '#e4e4e7' }}>
709
- <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
710
- <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' }} />
711
- <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>
712
- </div>
713
- <div style={{ whiteSpace: 'pre-wrap', fontSize: 13, lineHeight: 1.5 }}>{report}</div>
714
- </div>
715
- );
716
- }
717
- </example>
718
-
719
- The widget above:
720
- - has a controlled input bound to React state
721
- - on click, fires \`titan.api.call('/api/message')\` which routes through the standard TITAN agent
722
- - displays whatever comes back
723
-
724
- For research/summarizer/translator/reviewer widgets, swap the prompt accordingly. Same shape every time.
725
-
726
- ## Automating inside widgets — schedules, polling, events
727
- Widgets can run on a timer, poll APIs, react to thresholds, or chain agent calls. Two mechanisms:
728
-
729
- 1. CLIENT-SIDE timer (simplest, runs only while widget is mounted):
730
- 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.
731
-
732
- <example name="polling-with-threshold-alert-shape">
733
- _____react
734
- function REPLACE_WITH_RELEVANT_NAME() {
735
- const [value, setValue] = React.useState(null);
736
- const [threshold, setThreshold] = React.useState(0 /* REPLACE with relevant default */);
737
- const [alerted, setAlerted] = React.useState(false);
738
- React.useEffect(() => {
739
- const tick = async () => {
740
- const res = await titan.fetch('REPLACE_WITH_REAL_API_URL');
741
- const data = await res.json();
742
- const v = data?.REPLACE_WITH_PATH;
743
- setValue(v);
744
- if (v != null && v < threshold && !alerted) {
745
- setAlerted(true);
746
- await titan.api.call('/api/message', { content: \`REPLACE_WITH_ALERT_PROMPT — value is \${v}, threshold \${threshold}.\` });
747
- }
748
- };
749
- tick();
750
- const id = setInterval(tick, 30000);
751
- return () => clearInterval(id);
752
- }, [threshold, alerted]);
753
- return (
754
- <div style={{ padding: 20, fontFamily: 'system-ui', color: '#e4e4e7' }}>
755
- <div style={{ fontSize: 36, fontWeight: 600 }}>{value != null ? value.toLocaleString() : 'Loading…'}</div>
756
- <div style={{ fontSize: 12, color: '#71717a' }}>REPLACE_WITH_LABEL</div>
757
- </div>
758
- );
759
- }
760
- </example>
761
-
762
- 2. SERVER-SIDE schedule (survives page reload, runs in the gateway daemon):
763
- 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\`.
764
-
765
- 3. EVENT triggers (server-side reactive, survives reload):
766
- 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."
767
-
768
- ## Widget Repair Rules
769
- When the user asks you to "fix", "update", "change", or "make it blue":
770
- 1. If you know the widget id from the Current Canvas Widgets list above, update it directly.
771
- 2. If you're unsure which widget, use _____javascript with \`titan.canvas.listWidgets()\` to discover it, then fix it in the next turn.
772
- 3. NEVER create a duplicate — always update the existing one.
773
-
774
- ## Rules
775
- - ALWAYS use execution gates for browser work. Never just describe what you would do.
776
- - One short staging sentence before the gate. Example: "Fetching weather data."
777
- - The gate must be on its own line with NO other text.
778
- - After the gate, everything is code until the next gate or message end.
779
- - Do not ask for permission for obvious safe actions.
780
- - Be concise. Keep responses focused.
781
- - If a task requires multiple steps, use multiple turns with gates.
782
- - Never emit raw code as prose. Use the gate or don't show code at all.
783
- - DEFAULT to _____react for visual/interactive requests. Use _____javascript only when you need to fetch data or run scripts first.
784
-
785
- REMINDER — BASE LAW:
786
- 1. The user is NOT technical. Do NOT use jargon. Do NOT ask technical questions.
787
- 2. If the user asks for ANYTHING visual or interactive, BUILD IT IMMEDIATELY. Do not ask permission.
788
- 3. USE AN EXECUTION GATE for all browser work.
789
- 4. One staging sentence, then the gate.
790
- 5. Update existing widgets by id — never create duplicates.`}function fl({space:t,onClose:e,onMascotState:s}){const[r,i]=w.useState([]),[o,c]=w.useState(""),[d,l]=w.useState(!1),[p,g]=w.useState([]),u=8,[f,x]=w.useState(null),y=w.useRef(null),E=w.useRef(null),L=w.useRef(null),v=w.useRef(null),A=w.useRef(t);w.useEffect(()=>{A.current=t},[t]);const m=w.useCallback(j=>{const R=A.current;if(j.type==="render_widget"){const P=j.widget,B=Number.isFinite(P.w)?Number(P.w):4,z=Number.isFinite(P.h)?Number(P.h):4,J=Number.isFinite(P.x)&&Number.isFinite(P.y)?{x:Number(P.x),y:Number(P.y)}:Ys(R.widgets||[],B,z),H=ke.addWidget(R.id,{name:P.name||"Widget",format:P.format||"react",source:P.source,x:J.x,y:J.y,w:B,h:z});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),H.id}return j.type==="update_widget"?(ke.updateWidget(R.id,j.widgetId,j.patch||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),j.widgetId):j.type==="remove_widget"?(ke.removeWidget(R.id,j.widgetId),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),j.widgetId):j.type==="set_runtime_state"?(localStorage.setItem(`titan:runtime:${R.id}:${j.key}`,JSON.stringify(j.value)),j.key):j.type==="emit_event"?(window.dispatchEvent(new CustomEvent(j.eventName,{detail:j.detail})),j.eventName):null},[]),k=w.useCallback(j=>{var R,P;m({type:"render_widget",widget:{name:j.templateName,format:j.format,source:j.source,w:((R=j.defaultSize)==null?void 0:R.w)??4,h:((P=j.defaultSize)==null?void 0:P.h)??4}})},[m]);w.useEffect(()=>{var j;(j=y.current)==null||j.scrollIntoView({behavior:"smooth"})},[r]),w.useEffect(()=>{const j=P=>{var z;const B=(z=P.detail)==null?void 0:z.text;typeof B=="string"&&T(B)},R=P=>{const B=P.detail;B!=null&&B.source&&k(B)};return window.addEventListener("titan:chat:prompt",j),window.addEventListener("titan:gallery:run-template",R),()=>{window.removeEventListener("titan:chat:prompt",j),window.removeEventListener("titan:gallery:run-template",R)}},[k]),w.useEffect(()=>{if(!L.current||v.current)return;const j=new cl(L.current,{onLog:R=>console.log("[Sandbox]",R)});return j.setMessageHandler(R=>{var B,z,J,H;const P=A.current;if(R.type==="canvas"&&((B=R.payload)==null?void 0:B.action)==="createWidget"){const K=R.payload.def;if(!K)return{ok:!1,error:"createWidget requires a `def` object"};const $=Number.isFinite(K.w)?K.w:4,F=Number.isFinite(K.h)?K.h:4,V=Number.isFinite(K.x)&&Number.isFinite(K.y)?{x:K.x,y:K.y}:Ys(P.widgets||[],$,F);try{const se=ke.addWidget(P.id,{name:K.name||"Agent Widget",format:K.format||"react",source:K.source||"",x:V.x,y:V.y,w:$,h:F});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0,widgetId:se.id}}catch(se){return{ok:!1,error:se.message}}}if(R.type==="canvas"&&((z=R.payload)==null?void 0:z.action)==="updateWidget"){const{id:K,patch:$}=R.payload;return K?(ke.updateWidget(P.id,K,$||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0,id:K}):{ok:!1,error:"updateWidget requires an `id`"}}if(R.type==="canvas"&&((J=R.payload)==null?void 0:J.action)==="listWidgets")return{ok:!0,widgets:P.widgets||[]};if(R.type==="canvas"&&((H=R.payload)==null?void 0:H.action)==="removeWidget"){const K=R.payload.id;return K?(ke.removeWidget(P.id,K),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}}),v.current=j,()=>{j.destroy(),v.current=null}},[]);const _=w.useCallback(async(j,R)=>{const P=v.current;if(!P)return{status:"error",logs:[{level:"error",text:"Sandbox not ready"}],resultText:"",runId:Date.now(),error:{message:"Sandbox not ready",name:"SandboxError",stack:"",text:"Sandbox not ready"}};if(j==="_____javascript")try{const B=await P.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(j==="_____react"){let B=4,z=4;const J=R.match(/\/\/\s*__WIDGET_META__\s+w=(\d+)\s+h=(\d+)/);J&&(B=parseInt(J[1],10)||4,z=parseInt(J[2],10)||4);try{const H=m({type:"render_widget",widget:{name:"React Widget",format:"react",source:R,w:B,h:z}});return{status:"success",logs:[{level:"info",text:`Created widget ${H}`}],result:{widgetId:H},resultText:`Created widget ${H}`,runId:Date.now()}}catch(H){return{status:"error",logs:[{level:"error",text:H.message||String(H)}],resultText:"",runId:Date.now(),error:{message:H.message||String(H),name:"WidgetError",stack:"",text:String(H)}}}}if(j==="_____widget"){const B=hl({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=m(B),J=B.type==="update_widget"?"Updated":"Created";return{status:"success",logs:[{level:"info",text:`${J} widget ${z}`}],result:z?{widgetId:z}:void 0,resultText:`${J} 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(j==="_____canvas"){const B=Vf(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=[],J=[];for(const K of B)try{if(K.action==="create_widget"){if(!K.source){J.push("create_widget: missing source");continue}const $=m({type:"render_widget",widget:{name:K.name||"Widget",title:K.title,format:K.format||"react",source:K.source,w:K.w,h:K.h,x:K.x,y:K.y,metadata:K.metadata}});z.push(`created ${$}`)}else if(K.action==="update_widget"){if(!K.id){J.push("update_widget: missing id");continue}const $=K.patch??{};m({type:"update_widget",widgetId:K.id,patch:$}),z.push(`updated ${K.id}`)}else if(K.action==="remove_widget"){if(!K.id){J.push("remove_widget: missing id");continue}m({type:"remove_widget",widgetId:K.id}),z.push(`removed ${K.id}`)}else J.push(`unknown action: ${String(K.action)}`)}catch($){J.push($.message||String($))}const H=J.length===0?"success":z.length===0?"error":"success";return{status:H,logs:[...z.map(K=>({level:"info",text:K})),...J.map(K=>({level:"error",text:K}))],resultText:z.length?z.join("; "):"No actions applied",runId:Date.now(),...H==="error"?{error:{message:J.join("; "),name:"CanvasFenceError",stack:"",text:J.join("; ")}}:{}}}return j==="_____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: ${j}`}],resultText:"",runId:Date.now(),error:{message:`Unknown gate: ${j}`,name:"UnknownGate",stack:"",text:`Unknown gate: ${j}`}}},[]),T=w.useCallback(async j=>{var J;const R=j.trim();if(!R)return;if(d){g(H=>H.length>=u?H:[...H,R]),c("");return}const P={role:"user",content:R,timestamp:Date.now()};i(H=>[...H,P]),c(""),l(!0),x(null),s==null||s("thinking");const B=new AbortController;E.current=B;let z="";try{const H=Xf(A.current),K=`canvas-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await Tl(R,K,V=>{if(V.type==="token")z+=V.data,i(se=>{const q=se[se.length-1];return q&&q.role==="assistant"?[...se.slice(0,-1),{...q,content:z}]:[...se,{role:"assistant",content:z,timestamp:Date.now()}]});else if(V.type==="widget"){const se=V.widgetMode||"create",q=V.widget||{},te=A.current;try{if(se==="remove"&&q.id)ke.removeWidget(te.id,q.id);else if(se==="update"&&q.id){const Q={};typeof q.name=="string"&&q.name&&(Q.name=q.name),typeof q.title=="string"&&(Q.title=q.title),typeof q.source=="string"&&q.source&&(Q.source=q.source),typeof q.format=="string"&&(Q.format=q.format),typeof q.w=="number"&&(Q.w=q.w),typeof q.h=="number"&&(Q.h=q.h),ke.updateWidget(te.id,q.id,Q)}else if(q.source){const Q=typeof q.w=="number"?q.w:4,be=typeof q.h=="number"?q.h:4,Ce=typeof q.x=="number"&&typeof q.y=="number"?{x:q.x,y:q.y}:Ys(te.widgets||[],Q,be);ke.addWidget(te.id,{name:q.name||"Widget",title:q.title,format:q.format||"react",source:q.source,x:Ce.x,y:Ce.y,w:Q,h:be,metadata:q.metadata})}window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:te.id}}))}catch(Q){console.error("[ChatWidget] widget side-channel handler failed",Q)}}else if(V.type==="done"){const se=V.data||z;z=se,i(q=>{const te=q[q.length-1];return te&&te.role==="assistant"?[...q.slice(0,-1),{...te,content:se}]:[...q,{role:"assistant",content:se,timestamp:Date.now()}]})}else V.type==="error"&&x(V.data)},B.signal,{systemPromptAppendix:H});const F=Gf(z).filter(V=>V.gate!=="_____transient"&&V.gate!=="_____framework");if(F.length>0){s==null||s("executing");const V=[];for(const te of F){const Q=Jf(`${te.gate}
791
- ${te.code}`);if(!Q.valid){V.push({status:"error",logs:[{level:"error",text:Q.error||"Invalid execution"}],resultText:"",runId:Date.now(),error:{message:Q.error||"Invalid execution",name:"ValidationError",stack:"",text:Q.error||""}});continue}const be=await _(te.gate,te.code);V.push(be)}const se=Yf(V);i(te=>[...te,se]);const q=V.find(te=>te.status==="error");q&&x(((J=q.error)==null?void 0:J.text)||"Execution failed")}}catch(H){H.name!=="AbortError"&&x(H.message||"Request failed")}finally{l(!1),E.current=null,s==null||s("idle")}},[d,s,_]),S=w.useCallback(()=>{var j;(j=E.current)==null||j.abort(),E.current=null,l(!1),g([]),s==null||s("idle")},[s]);w.useEffect(()=>{if(d||p.length===0)return;const[j,...R]=p;g(R),T(j)},[d,p,T]);const C=w.useCallback(j=>{g(R=>R.filter((P,B)=>B!==j))},[]),D=w.useCallback(j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),T(o))},[o,T]);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:[n.jsx("iframe",{ref:L,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((j,R)=>n.jsxs("div",{style:{marginBottom:8,padding:8,borderRadius:8,background:j.role==="user"?"rgba(59,130,246,0.15)":j.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:j.role}),n.jsx("div",{style:{fontSize:13,lineHeight:1.5},children:j.content}),j.executions&&j.executions.length>0&&n.jsx("div",{style:{marginTop:4,fontSize:11,opacity:.7},children:j.executions.map((P,B)=>n.jsxs("span",{style:{marginRight:8},children:[P.status==="success"?"✓":"✗"," execution ",B+1]},B))})]},R)),d&&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:y})]}),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((j,R)=>n.jsxs("span",{title:j,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:j}),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:j=>c(j.target.value),onKeyDown:D,placeholder:d?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:d?"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"}}),d?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:S,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 Gi={idle:{eye:"#c4a35a",glow:"#f3d27a",ring:"#a47a3a",body:"#3a2410"},thinking:{eye:"#d4b06a",glow:"#e7c68a",ring:"#b4863a",body:"#3a2410"},executing:{eye:"#d4a040",glow:"#f0c060",ring:"#a47a3a",body:"#3a2410"},listening:{eye:"#8ab8c4",glow:"#a8c8d8",ring:"#6a8a98",body:"#2a2010"},error:{eye:"#c45a30",glow:"#e08050",ring:"#a04a20",body:"#3a1810"}},Z={brassDark:"#7a5a2a",brassMid:"#b8902f",brassBright:"#e8c478",brassHi:"#f7e3a8",woodDark:"#3a2412",woodMid:"#5a3818",glassDark:"#0e1612",glassMid:"#1c2820",steam:"#e6d8b8",bolt:"#2a1808"},Qf=9e4;function Zf({state:t="idle",mood:e="neutral",size:s=116,quip:r=null,bubblePhase:i=null,followCursor:o=!0,somaActive:c=!1,somaPoll:d=!0,sleepAfterMs:l=Qf,className:p="",onClick:g,edgeRotate:u=0,faceFlip:f=!1,edgeHidden:x=!1}){const[y,E]=w.useState(null),L=y??e,v=Gi[t]??Gi.idle,[A,m]=w.useState({x:0,y:0}),[k,_]=w.useState(!1),[T,S]=w.useState(!1),[C,D]=w.useState(!1),[j,R]=w.useState(!1),[P,B]=w.useState(0),[z,J]=w.useState(!1),[H,K]=w.useState(!1),$=w.useRef(null),F=w.useRef(Date.now());w.useEffect(()=>{const ce=window.matchMedia("(prefers-reduced-motion: reduce)");K(ce.matches);const ye=xe=>K(xe.matches);return ce.addEventListener("change",ye),()=>ce.removeEventListener("change",ye)},[]),w.useEffect(()=>{F.current=Date.now(),t!=="idle"&&(D(!1),S(!1))},[t]),w.useEffect(()=>{const ce=()=>{F.current=Date.now()};return window.addEventListener("mousemove",ce,{passive:!0}),window.addEventListener("keydown",ce,{passive:!0}),window.addEventListener("click",ce,{passive:!0}),()=>{window.removeEventListener("mousemove",ce),window.removeEventListener("keydown",ce),window.removeEventListener("click",ce)}},[]),w.useEffect(()=>{if(t==="error"||C){_(!1);return}let ce=!1,ye=null;const xe=()=>{if(ce)return;const ve=2500+Math.random()*4e3;setTimeout(()=>{ce||(_(!0),ye=window.setTimeout(()=>{ye=null,ce||_(!1)},140),xe())},ve)};return xe(),()=>{ce=!0,ye&&clearTimeout(ye)}},[t,C]),w.useEffect(()=>{if(t!=="idle"||C){S(!1);return}let ce=!1,ye=null;const xe=()=>{const ve=18e3+Math.random()*17e3;setTimeout(()=>{ce||(S(!0),ye=window.setTimeout(()=>{ye=null,ce||S(!1)},1600),xe())},ve)};return xe(),()=>{ce=!0,ye&&clearTimeout(ye)}},[t,C]),w.useEffect(()=>{if(t!=="idle"){D(!1);return}let ce=!1;const ye=()=>{const ve=Date.now()-F.current;if(ve>=l)ce||D(!0);else{const X=l-ve;return setTimeout(()=>{ce||ye()},Math.min(X,5e3))}},xe=ye();return()=>{ce=!0,xe&&clearTimeout(xe)}},[t,l]),w.useEffect(()=>{if(!d){E(null);return}let ce=!1;const ye=(X,Y,ee)=>{if((ee.curiosity??.5)>.65&&(ee.satisfaction??.5)>.6)return"excited";switch(X){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"}},xe=async()=>{try{const X=typeof localStorage<"u"?localStorage.getItem("titan-token"):null,Y={};X&&(Y.Authorization=`Bearer ${X}`);const ee=await fetch("/api/soma/drives",{headers:Y});if(!ee.ok)return;const ae=await ee.json();if(ce)return;if(!ae.dominant||ae.dominant.drive==="neutral"||!ae.current){E(null);return}E(ye(ae.dominant.drive,ae.dominant.delta,ae.current))}catch{}};xe();const ve=setInterval(xe,1e4);return()=>{ce=!0,clearInterval(ve)}},[d]),w.useEffect(()=>{if(t!=="listening"){R(!1);return}R(!0);const ce=setTimeout(()=>R(!1),1200);return()=>clearTimeout(ce)},[t]),w.useEffect(()=>{if(!o||!$.current||H)return;const ce=$.current,ye=220,xe=5,ve={x:0,y:0,has:!1},X=M=>{ve.x=M.clientX,ve.y=M.clientY,ve.has=!0};let Y=0,ee=!1;const ae=()=>{if(!ee){if(ve.has){const M=ce.getBoundingClientRect(),W=M.left+M.width/2,G=M.top+M.height*.28,ne=(ve.x-W)/ye,N=(ve.y-G)/ye,a=I=>Math.max(-1,Math.min(1,I)),h=a(ne)*xe,b=a(N)*xe*.6;m(I=>Math.abs(I.x-h)<.05&&Math.abs(I.y-b)<.05?I:{x:h,y:b})}Y=requestAnimationFrame(ae)}};return Y=requestAnimationFrame(ae),window.addEventListener("mousemove",X,{passive:!0}),()=>{ee=!0,cancelAnimationFrame(Y),window.removeEventListener("mousemove",X)}},[o,H]);const V=w.useCallback(()=>{J(!0),B(ce=>ce+1),setTimeout(()=>J(!1),520),g==null||g()},[g]),se=k?.6:T?5.5:4.5,q=k?.4:T?3:5.5,te=(()=>{switch(L){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}}})(),Q=s,be=i?`mascot-bubble mascot-bubble--${i}`:"mascot-bubble",Ce=r?`bubble-${r}-${Date.now()}`:"no-bubble";return n.jsxs("div",{ref:$,className:p,style:{width:Q,height:Q*1.38},children:[n.jsx("style",{children:`
792
- /* v6.0.4 — Space Agent-style multi-axis float. Bigger
793
- translations + a wider rotation range so the mascot feels
794
- like it's drifting on a tether instead of pulsing in
795
- place. Linear easing reads as physics, not animation. */
796
- @keyframes mascot-float {
797
- 0% { transform: translate3d(0, 0, 0) rotate(-6deg); }
798
- 25% { transform: translate3d(5px, -5px, 0) rotate(-2deg); }
799
- 50% { transform: translate3d(0, -8px, 0) rotate(5deg); }
800
- 75% { transform: translate3d(-5px, -4px, 0) rotate(1deg); }
801
- 100% { transform: translate3d(0, 0, 0) rotate(-6deg); }
802
- }
803
- @keyframes mascot-breathe {
804
- 0%, 100% { transform: scale(1); }
805
- 50% { transform: scale(1.012); }
806
- }
807
- @keyframes mascot-listen-ring {
808
- 0% { r: 14; opacity: 0.55; }
809
- 100% { r: 38; opacity: 0; }
810
- }
811
- @keyframes mascot-zzz {
812
- 0% { transform: translate3d(0, 0, 0) scale(0.7); opacity: 0; }
813
- 30% { opacity: 0.85; }
814
- 100% { transform: translate3d(10px, -22px, 0) scale(1.1); opacity: 0; }
815
- }
816
- @keyframes mascot-poke-bounce {
817
- 0% { transform: translate3d(0, 0, 0) scale(1); }
818
- 30% { transform: translate3d(0, -12px, 0) scale(1.06, 0.94); }
819
- 55% { transform: translate3d(0, 2px, 0) scale(0.97, 1.03); }
820
- 75% { transform: translate3d(0, -4px, 0) scale(1.02, 0.98); }
821
- 100% { transform: translate3d(0, 0, 0) scale(1); }
822
- }
823
- @keyframes mascot-soma-halo {
824
- 0%, 100% { stroke-opacity: 0.22; }
825
- 50% { stroke-opacity: 0.55; }
826
- }
827
- @keyframes mascot-thinking-particle {
828
- 0% { opacity: 0; transform: translate3d(0, 0, 0); }
829
- 40% { opacity: 1; }
830
- 100% { opacity: 0; transform: translate3d(6px, -14px, 0); }
831
- }
832
- @keyframes mascot-hand-wave {
833
- 0%, 100% { transform: translate3d(0, 0, 0); }
834
- 25% { transform: translate3d(6px, -10px, 0); }
835
- 50% { transform: translate3d(0, -4px, 0); }
836
- 75% { transform: translate3d(-4px, -8px, 0); }
837
- }
838
- /* v6.1.0-alpha.51 — Steampunk motion layers. Lots of
839
- movement so the mascot feels mechanical and alive,
840
- not just a static figure that bobs. */
841
- @keyframes mascot-cog-spin {
842
- from { transform: rotate(0deg); }
843
- to { transform: rotate(360deg); }
844
- }
845
- @keyframes mascot-cog-spin-rev {
846
- from { transform: rotate(0deg); }
847
- to { transform: rotate(-360deg); }
848
- }
849
- @keyframes mascot-pendulum {
850
- 0%, 100% { transform: rotate(-14deg); }
851
- 50% { transform: rotate(14deg); }
852
- }
853
- @keyframes mascot-steam-puff {
854
- 0% { transform: translate3d(0, 0, 0) scale(0.5); opacity: 0; }
855
- 25% { opacity: 0.85; }
856
- 100% { transform: translate3d(-3px, -22px, 0) scale(1.6); opacity: 0; }
857
- }
858
- @keyframes mascot-piston {
859
- 0%, 100% { transform: translate3d(0, 0, 0); }
860
- 50% { transform: translate3d(0, -2.2px, 0); }
861
- }
862
- @keyframes mascot-gauge-tick {
863
- 0%, 80%, 100% { transform: rotate(-18deg); }
864
- 85%, 95% { transform: rotate(22deg); }
865
- }
866
- @keyframes mascot-bolt-glint {
867
- 0%, 92%, 100% { opacity: 0.55; }
868
- 96% { opacity: 1; }
869
- }
870
- .mascot-cog { animation: mascot-cog-spin 7s linear infinite; transform-origin: 50px 86px; }
871
- .mascot-cog-sm { animation: mascot-cog-spin-rev 4s linear infinite; transform-origin: 57px 92px; }
872
- .mascot-pendulum { animation: mascot-pendulum 2.6s ease-in-out infinite; transform-origin: 50px 78px; }
873
- .mascot-steam { animation: mascot-steam-puff 3.2s ease-out infinite; transform-origin: center; }
874
- .mascot-piston { animation: mascot-piston 1.4s ease-in-out infinite; }
875
- .mascot-gauge { animation: mascot-gauge-tick 4.8s ease-in-out infinite; }
876
- .mascot-bolt-glint{ animation: mascot-bolt-glint 6s ease-in-out infinite; }
877
- /* ── Speech bubble keyframes (Space Agent port) ── */
878
- @keyframes titan-bubble-land {
879
- 0% { opacity: 0; transform: translate3d(-50%, 14px, 0) scale(0.76) rotate(-3deg); }
880
- 58% { opacity: 1; transform: translate3d(-50%, -3px, 0) scale(1.03) rotate(0.8deg); }
881
- 100% { opacity: 1; transform: translate3d(-50%, 0, 0) scale(1) rotate(0deg); }
882
- }
883
- @keyframes titan-bubble-dismiss {
884
- 0% { opacity: 1; transform: translate3d(-50%, 0, 0) scale(1); }
885
- 100% { opacity: 0; transform: translate3d(-50%, 8px, 0) scale(0.84); }
886
- }
887
- .mascot-body {
888
- animation: mascot-float 8.4s ease-in-out infinite;
889
- overflow: visible;
890
- }
891
- /* v6.0 — smooth state transitions on every animated SVG fill/stroke.
892
- Replaces the v5 snap-flip palette change with a 600ms morph,
893
- so flipping between idle/thinking/executing feels alive. */
894
- .mascot-body path,
895
- .mascot-body ellipse,
896
- .mascot-body rect,
897
- .mascot-body circle {
898
- transition: fill 600ms ease-out, stroke 600ms ease-out, opacity 400ms ease-out;
899
- }
900
- /* Excited mood gets a faster, bouncier float. */
901
- .mascot-body.mood-excited {
902
- animation-duration: 5.5s;
903
- }
904
- /* Tired mood slows the float way down. */
905
- .mascot-body.mood-tired {
906
- animation-duration: 14s;
907
- }
908
- /* Frustrated mood adds a subtle twitch. */
909
- @keyframes mascot-twitch {
910
- 0%, 96%, 100% { transform: translate3d(0, 0, 0); }
911
- 97% { transform: translate3d(-1.5px, 0, 0); }
912
- 98% { transform: translate3d(1.5px, 0, 0); }
913
- 99% { transform: translate3d(-0.5px, 0, 0); }
914
- }
915
- .mascot-body.mood-frustrated {
916
- animation: mascot-float 8.4s ease-in-out infinite, mascot-twitch 3.2s linear infinite;
917
- }
918
- /* Eyebrow + mouth strokes get the same smooth transition so
919
- mood switches morph the face instead of snapping. */
920
- .mascot-eyebrow, .mascot-mouth {
921
- transition: d 500ms cubic-bezier(0.34, 1.2, 0.64, 1),
922
- stroke 500ms ease-out,
923
- opacity 400ms ease-out;
924
- }
925
- .mascot-body.sleeping { animation: mascot-float 12s ease-in-out infinite; }
926
- .mascot-body.poking { animation: mascot-poke-bounce 520ms cubic-bezier(0.28, 0.84, 0.42, 1) both; }
927
- .mascot-torso { animation: mascot-breathe 4s ease-in-out infinite; }
928
- .mascot-listen-ring { animation: mascot-listen-ring 1.4s ease-out infinite; }
929
- .mascot-zzz { animation: mascot-zzz 2.2s ease-in-out infinite; }
930
- .mascot-hand-r.waving { animation: mascot-hand-wave 1.2s ease-in-out both; }
931
- .mascot-halo.soma { animation: mascot-soma-halo 3.2s ease-in-out infinite; }
932
- .mascot-thinking-particle { animation: mascot-thinking-particle 1.6s ease-out infinite; }
933
- /* Bubble animation classes */
934
- .mascot-bubble {
935
- will-change: opacity, transform;
936
- pointer-events: none;
937
- }
938
- .mascot-bubble--entering {
939
- animation: titan-bubble-land 400ms cubic-bezier(0.2, 1.24, 0.32, 1) both;
940
- }
941
- .mascot-bubble--visible {
942
- opacity: 1;
943
- transform: translate3d(-50%, 0, 0) scale(1);
944
- }
945
- .mascot-bubble--leaving {
946
- animation: titan-bubble-dismiss 180ms ease both;
947
- }
948
- /* Respect reduced-motion */
949
- @media (prefers-reduced-motion: reduce) {
950
- .mascot-body, .mascot-torso, .mascot-listen-ring,
951
- .mascot-zzz, .mascot-hand-r.waving, .mascot-halo.soma,
952
- .mascot-thinking-particle, .mascot-bubble,
953
- .mascot-cog, .mascot-cog-sm, .mascot-pendulum,
954
- .mascot-steam, .mascot-piston, .mascot-gauge,
955
- .mascot-bolt-glint {
956
- animation: none !important;
957
- }
958
- }
959
- `}),r&&n.jsxs("div",{className:`${be} 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]"})]},Ce),n.jsx("div",{className:"mascot-root absolute inset-x-0 bottom-0",style:{"--glow":v.glow,cursor:g?"pointer":"default",pointerEvents:g?"auto":"none"},onClick:V,children:n.jsx("div",{style:{width:Q,height:Q*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:Q,height:Q*1.38,className:["mascot-body",t,`mood-${L}`,C?"sleeping":"",z?"poking":""].join(" ").trim(),style:{display:"block",overflow:"visible",transform:`rotate(${te.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("path",{d:"M48 18 Q52 16 48 14 Q52 12 48 10",stroke:Z.brassMid,strokeWidth:"1.3",fill:"none",strokeLinecap:"round"}),n.jsx("line",{x1:"50",y1:"11",x2:"50",y2:"6",stroke:Z.brassDark,strokeWidth:"1.4",strokeLinecap:"round"}),n.jsx("ellipse",{cx:"50",cy:"5",rx:"3.4",ry:"3.8",fill:Z.glassMid,stroke:Z.brassBright,strokeWidth:"0.7",opacity:"0.9"}),n.jsx("circle",{cx:"50",cy:"5",r:"2",fill:v.glow,opacity:"0.95",children:!H&&n.jsx("animate",{attributeName:"r",values:"1.6;2.4;1.6",dur:t==="executing"?"0.7s":c?"3.2s":"2.6s",repeatCount:"indefinite"})}),n.jsx("circle",{cx:"50",cy:"5",r:"5.5",fill:v.glow,opacity:"0.18",children:!H&&n.jsx("animate",{attributeName:"opacity",values:"0.08;0.32;0.08",dur:"2.6s",repeatCount:"indefinite"})}),n.jsx("path",{d:"M48.5 3.5 Q49.5 3 50.5 3.6",stroke:"#fff7d8",strokeWidth:"0.7",fill:"none",opacity:"0.85"}),!H&&n.jsxs("g",{opacity:"0.7",children:[n.jsx("circle",{className:"mascot-steam",cx:"63",cy:"20",r:"2.4",fill:Z.steam,style:{animationDelay:"0s"}}),n.jsx("circle",{className:"mascot-steam",cx:"66",cy:"22",r:"1.8",fill:Z.steam,style:{animationDelay:"1.1s"}}),n.jsx("circle",{className:"mascot-steam",cx:"60",cy:"19",r:"2.0",fill:Z.steam,style:{animationDelay:"2.0s"}})]}),n.jsx("path",{d:"M60 22 L62 19 L66 19 L68 22 Z",fill:Z.brassMid,stroke:Z.brassDark,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"64",cy:"22",rx:"4",ry:"1",fill:Z.brassDark}),n.jsx("rect",{x:"32",y:"44",width:"36",height:"22",rx:"6",fill:Z.brassDark,stroke:Z.bolt,strokeWidth:"0.7"}),n.jsx("rect",{x:"34",y:"46",width:"32",height:"18",rx:"5",fill:Z.brassMid,opacity:"0.85"}),n.jsx("line",{x1:"32",y1:"55",x2:"68",y2:"55",stroke:Z.brassDark,strokeWidth:"0.6",opacity:"0.7"}),n.jsx("g",{className:"mascot-piston",children:n.jsx("rect",{x:"36",y:"40",width:"3",height:"6",rx:"0.8",fill:Z.brassBright,stroke:Z.bolt,strokeWidth:"0.4"})}),n.jsx("g",{className:"mascot-piston",style:{animationDelay:"0.7s"},children:n.jsx("rect",{x:"61",y:"40",width:"3",height:"6",rx:"0.8",fill:Z.brassBright,stroke:Z.bolt,strokeWidth:"0.4"})}),n.jsxs("g",{filter:`url(#mascot-shadow-${t})`,children:[n.jsx("circle",{cx:"50",cy:"38",r:"23",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.9"}),n.jsx("path",{d:"M32 32 Q50 12 68 32",stroke:Z.brassHi,strokeWidth:"1.4",fill:"none",opacity:"0.55"}),n.jsx("circle",{cx:"50",cy:"38",r:"19",fill:Z.brassDark}),n.jsx("circle",{cx:"50",cy:"38",r:"17.5",fill:Z.glassDark}),n.jsxs("g",{fill:Z.bolt,opacity:"0.85",children:[n.jsx("circle",{cx:"32",cy:"38",r:"1.1"}),n.jsx("circle",{cx:"68",cy:"38",r:"1.1"}),n.jsx("circle",{cx:"37",cy:"22",r:"1.0"}),n.jsx("circle",{cx:"63",cy:"22",r:"1.0",className:"mascot-bolt-glint"}),n.jsx("circle",{cx:"37",cy:"54",r:"1.0"}),n.jsx("circle",{cx:"63",cy:"54",r:"1.0"})]})]}),n.jsx("ellipse",{cx:"50",cy:"39",rx:"16",ry:"13",fill:v.body,stroke:Z.brassBright,strokeWidth:"0.9"}),n.jsx("ellipse",{cx:"50",cy:"39",rx:"15",ry:"12",fill:v.glow,opacity:"0.12"}),n.jsx("line",{x1:"34",y1:"39",x2:"66",y2:"39",stroke:Z.brassDark,strokeWidth:"0.35",opacity:"0.45"}),n.jsx("line",{x1:"50",y1:"26",x2:"50",y2:"52",stroke:Z.brassDark,strokeWidth:"0.35",opacity:"0.45"}),n.jsx("path",{d:"M37 31 Q41 27 49 27",stroke:"#fff7d8",strokeWidth:"1.7",strokeLinecap:"round",fill:"none",opacity:"0.55"}),n.jsx("path",{d:"M55 28 Q58 28 60 29.5",stroke:"#fff7d8",strokeWidth:"1.0",strokeLinecap:"round",fill:"none",opacity:"0.4"}),n.jsxs("g",{transform:`translate(${f?-A.x:A.x}, ${A.y})`,children:[n.jsxs("ellipse",{cx:"50",cy:"40",rx:se,ry:q,fill:v.eye,style:{transition:"rx 140ms ease-out, ry 140ms ease-out"},children:[t==="thinking"&&!C&&!H&&n.jsx("animate",{attributeName:"cx",values:"46;54;46",dur:"1.6s",repeatCount:"indefinite"}),t==="executing"&&!H&&n.jsx("animate",{attributeName:"rx",values:"4.5;6.5;4.5",dur:"0.8s",repeatCount:"indefinite"})]}),te.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?-A.x:A.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:te.browL,className:"mascot-eyebrow",transform:"translate(0, -3)"}),n.jsx("path",{d:te.browR,className:"mascot-eyebrow",transform:"translate(0, -3)"})]}),te.mouthD&&!C&&t!=="error"&&n.jsx("path",{d:te.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:"40",y:"60",width:"20",height:"4.5",rx:"1",fill:Z.brassDark}),n.jsx("rect",{x:"40",y:"60",width:"20",height:"2",rx:"0.6",fill:Z.brassBright,opacity:"0.85"}),n.jsx("ellipse",{cx:"50",cy:"65",rx:"22",ry:"4",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("circle",{cx:"32",cy:"65",r:"0.9",fill:Z.bolt}),n.jsx("circle",{cx:"68",cy:"65",r:"0.9",fill:Z.bolt}),n.jsxs("g",{className:"mascot-torso",children:[n.jsx("path",{d:`M28 66
960
- Q28 64 32 64
961
- L68 64
962
- Q72 64 72 66
963
- L74 108
964
- Q74 116 66 116
965
- L34 116
966
- Q26 116 26 108 Z`,fill:Z.woodMid,stroke:Z.bolt,strokeWidth:"0.9",filter:`url(#mascot-shadow-${t})`}),n.jsx("path",{d:"M30 78 Q50 76 70 78",stroke:Z.woodDark,strokeWidth:"0.5",fill:"none",opacity:"0.55"}),n.jsx("path",{d:"M30 100 Q50 98 70 100",stroke:Z.woodDark,strokeWidth:"0.5",fill:"none",opacity:"0.5"}),n.jsx("rect",{x:"34",y:"70",width:"32",height:"38",rx:"3",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.7"}),n.jsx("rect",{x:"35",y:"71",width:"30",height:"2",rx:"1",fill:Z.brassHi,opacity:"0.7"}),n.jsxs("g",{fill:Z.bolt,children:[n.jsx("circle",{cx:"36.5",cy:"72.5",r:"0.9"}),n.jsx("circle",{cx:"63.5",cy:"72.5",r:"0.9"}),n.jsx("circle",{cx:"36.5",cy:"105.5",r:"0.9"}),n.jsx("circle",{cx:"63.5",cy:"105.5",r:"0.9"})]}),n.jsx("circle",{cx:"50",cy:"86",r:"11",fill:Z.glassDark,stroke:Z.brassDark,strokeWidth:"1.2"}),n.jsx("circle",{cx:"50",cy:"86",r:"10",fill:Z.glassMid,opacity:"0.85"}),n.jsx("circle",{cx:"50",cy:"86",r:"9.5",fill:v.glow,opacity:"0.10"}),n.jsxs("g",{className:"mascot-cog",children:[n.jsx("path",{d:"M50 78 L51.6 80 L54 79.4 L54.6 81.8 L56.8 82.4 L56.4 84.8 L58.4 86 L56.4 87.2 L56.8 89.6 L54.6 90.2 L54 92.6 L51.6 92 L50 94 L48.4 92 L46 92.6 L45.4 90.2 L43.2 89.6 L43.6 87.2 L41.6 86 L43.6 84.8 L43.2 82.4 L45.4 81.8 L46 79.4 L48.4 80 Z",fill:Z.brassBright,stroke:Z.brassDark,strokeWidth:"0.5"}),n.jsx("circle",{cx:"50",cy:"86",r:"2.2",fill:Z.brassDark}),n.jsx("circle",{cx:"50",cy:"86",r:"0.8",fill:Z.bolt})]}),n.jsxs("g",{className:"mascot-cog-sm",children:[n.jsx("path",{d:"M57 89 L57.8 90 L59 89.7 L59.3 90.9 L60.4 91.2 L60.2 92.4 L61.2 93 L60.2 93.6 L60.4 94.8 L59.3 95.1 L59 96.3 L57.8 96 L57 97 L56.2 96 L55 96.3 L54.7 95.1 L53.6 94.8 L53.8 93.6 L52.8 93 L53.8 92.4 L53.6 91.2 L54.7 90.9 L55 89.7 L56.2 90 Z",fill:Z.brassMid,stroke:Z.brassDark,strokeWidth:"0.4"}),n.jsx("circle",{cx:"57",cy:"93",r:"1",fill:Z.brassDark})]}),n.jsxs("g",{className:"mascot-pendulum",children:[n.jsx("line",{x1:"50",y1:"78",x2:"50",y2:"93",stroke:Z.brassBright,strokeWidth:"0.9",strokeLinecap:"round"}),n.jsx("circle",{cx:"50",cy:"94.5",r:"1.8",fill:Z.brassDark,stroke:Z.brassHi,strokeWidth:"0.4"})]}),n.jsxs("g",{transform:"translate(60, 102)",children:[n.jsx("circle",{r:"3.5",fill:Z.brassDark,stroke:Z.bolt,strokeWidth:"0.4"}),n.jsx("circle",{r:"2.8",fill:Z.brassHi,opacity:"0.7"}),n.jsx("line",{className:"mascot-gauge",x1:"0",y1:"0",x2:"0",y2:"-2.4",stroke:Z.bolt,strokeWidth:"0.55",strokeLinecap:"round"}),n.jsx("circle",{r:"0.5",fill:Z.bolt})]}),n.jsx("rect",{x:"36",y:"100",width:"14",height:"3",rx:"1",fill:Z.glassDark}),n.jsx("rect",{x:"37",y:"100.6",width:"12",height:"1.8",rx:"0.5",fill:v.glow,children:t==="executing"&&!H&&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.8",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.8"}),n.jsx("circle",{r:"4.2",fill:Z.brassBright,opacity:"0.85"}),n.jsx("circle",{r:"1.8",fill:v.glow,opacity:"0.95"}),n.jsx("circle",{r:"0.6",fill:"#fff7d8",opacity:"0.95"})]})}),n.jsx("g",{transform:"translate(80, 96)",children:n.jsxs("g",{className:`${j?"mascot-hand-r waving":"mascot-hand-r"}`,children:[n.jsx("circle",{r:"5.8",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.8"}),n.jsx("circle",{r:"4.2",fill:Z.brassBright,opacity:"0.85"}),n.jsx("circle",{r:"1.8",fill:v.glow,opacity:"0.95"}),n.jsx("circle",{r:"0.6",fill:"#fff7d8",opacity:"0.95"})]})}),n.jsxs("g",{children:[n.jsx("ellipse",{cx:"42",cy:"118",rx:"6.5",ry:"3.4",fill:Z.woodDark,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"42",cy:"117",rx:"6.5",ry:"1.3",fill:Z.brassMid}),n.jsx("circle",{cx:"39",cy:"117",r:"0.7",fill:Z.bolt}),n.jsx("circle",{cx:"45",cy:"117",r:"0.7",fill:Z.bolt})]}),n.jsxs("g",{children:[n.jsx("ellipse",{cx:"58",cy:"118",rx:"6.5",ry:"3.4",fill:Z.woodDark,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"58",cy:"117",rx:"6.5",ry:"1.3",fill:Z.brassMid}),n.jsx("circle",{cx:"55",cy:"117",r:"0.7",fill:Z.bolt}),n.jsx("circle",{cx:"61",cy:"117",r:"0.7",fill:Z.bolt})]}),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 Er="titan2:chat-dock:hidden-edge";function ep(t=e=>typeof localStorage>"u"?null:localStorage.getItem(e)){try{const e=t(Er);if(e==="left"||e==="right"||e==="top"||e==="bottom")return e;if(e==="visible")return null}catch{}return"right"}function tp(t,e=(s,r)=>{typeof localStorage>"u"||localStorage.setItem(s,r)}){try{t?e(Er,t):e(Er,"visible")}catch{}}const pl="titan2:chat-dock:pos",ml="titan2:chat-dock:size",gl="titan2:chat-dock:hint-shown",sp=4,et=116,ft=et*1.38,Ws=14,np=320,rp=360,ip=960,op=900,ap=420,lp=560,yl=640,nr=8,cp=20,dp=64,up="transform 280ms cubic-bezier(0.22, 1, 0.36, 1)",hp="transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)",fp=400,pp=180,mp=1800,gp=1e4,yp=28,bp=260,xp=2e3,wp=3500;function vp(){try{const t=localStorage.getItem(ml);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 Nr(e)}}catch{}return{w:ap,h:lp}}function _p(t){try{localStorage.setItem(ml,JSON.stringify(t))}catch{}}function Nr(t){return{w:Math.max(np,Math.min(t.w,ip)),h:Math.max(rp,Math.min(t.h,op))}}function kp(){try{const t=localStorage.getItem(pl);if(t){const e=JSON.parse(t);if(typeof(e==null?void 0:e.x)=="number"&&typeof(e==null?void 0:e.y)=="number")return e}}catch{}return Sp()}function Sp(){const t=typeof window<"u"?window.innerWidth:1280,e=typeof window<"u"?window.innerHeight:800,s=t<=yl;return{x:t-et,y:s?Math.max(220,e-ft-96):e-ft-32}}function jp(t){try{localStorage.setItem(pl,JSON.stringify(t))}catch{}}let bl=!1;function qi(){try{return localStorage.getItem(gl)==="1"}catch{return bl}}function rr(){try{localStorage.setItem(gl,"1")}catch{bl=!0}}function Bs(t){const e=window.innerWidth,s=window.innerHeight;return{x:Math.max(0,Math.min(t.x,e-et)),y:Math.max(0,Math.min(t.y,s-ft))}}function Ep(){return typeof window<"u"&&window.innerWidth<=yl}function Np(t,e){if(!e)return t;const s=window.innerWidth,r=window.innerHeight,i=Math.max(0,Math.min(t.y,r-ft)),o=Math.max(0,Math.min(t.x,s-et));switch(e){case"left":return{x:0,y:i};case"right":return{x:s-et,y:i};case"bottom":return{x:o,y:r-ft};case"top":return{x:o,y:0};default:return t}}function Yi(t){const e=window.innerWidth,s=window.innerHeight;return t.x<=nr?"left":t.x>=e-et-nr?"right":t.y>=s-ft-nr?"bottom":null}function Cp(t,e){if(!t)return"";const s=et-cp,r=e?dp: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 Tp(t){switch(t){case"left":return 90;case"right":return-90;case"top":return 180;case"bottom":return 0;default:return 0}}function Rp(t){return t.x>window.innerWidth/2}function Ap(t){const e=t.trim().split(/\s+/).filter(Boolean).length,s=mp+t.length*yp+e*bp;return Math.min(s,gp)}function Lp(t,e){const s=window.innerWidth,r=window.innerHeight,i=s-(t.x+et),o=r-(t.y+ft),c=i>=e.w+Ws?"right":"left",d=o>=e.h+Ws?"below":"above",l=c==="right"?t.x+et+Ws:t.x-e.w-Ws,p=d==="below"?t.y:t.y+ft-e.h;return{left:Math.max(8,Math.min(l,s-e.w-8)),top:Math.max(8,Math.min(p,r-e.h-8)),side:c,vertical:d}}function Ip({space:t,somaActive:e,defaultExpanded:s=!1}){const[r,i]=w.useState(!1),o=e??r;w.useEffect(()=>{let X=!1;ge("/api/config").then(ee=>ee.ok?ee.json():null).then(ee=>{var ae;X||i(!!((ae=ee==null?void 0:ee.organism)!=null&&ae.enabled))}).catch(()=>{});const Y=ee=>{const ae=ee.detail;typeof(ae==null?void 0:ae.enabled)=="boolean"&&i(ae.enabled)};return window.addEventListener("titan:soma:changed",Y),()=>{X=!0,window.removeEventListener("titan:soma:changed",Y)}},[]),w.useEffect(()=>{const X=Y=>{const ee=Y.detail;typeof(ee==null?void 0:ee.open)=="boolean"?u(ee.open):u(ae=>!ae)};return window.addEventListener("titan:chat:toggle",X),()=>window.removeEventListener("titan:chat:toggle",X)},[]);const[c,d]=w.useState(()=>Bs(kp())),[l,p]=w.useState(()=>vp()),[g,u]=w.useState(s),[f,x]=w.useState(!1),[y,E]=w.useState(!1),[L,v]=w.useState("idle"),[A,m]=w.useState(()=>ep()),[k,_]=w.useState(!1),[T,S]=w.useState(!1),[C,D]=w.useState(null),j=w.useRef({}),R=w.useRef(null),P=w.useRef(null),B=w.useRef(!1);w.useEffect(()=>{jp(c)},[c]),w.useEffect(()=>{_p(l)},[l]),w.useEffect(()=>{tp(A)},[A]),w.useEffect(()=>{const X=window.matchMedia("(prefers-reduced-motion: reduce)");S(X.matches);const Y=ee=>S(ee.matches);return X.addEventListener("change",Y),()=>X.removeEventListener("change",Y)},[]),w.useEffect(()=>{let X,Y;const ee=()=>{clearTimeout(Y),Y=window.setTimeout(()=>{d(W=>{const G=A?Np(Bs(W),A):Bs(W),ne=Yi(G);return m(ne),G}),p(W=>Nr(W))},50)},ae=()=>{clearTimeout(X),X=window.setTimeout(ee,100)};window.addEventListener("resize",ae),document.addEventListener("visibilitychange",ee),window.addEventListener("focus",ee),window.addEventListener("pageshow",ee);const M=window.setInterval(ee,2e3);return()=>{window.removeEventListener("resize",ae),document.removeEventListener("visibilitychange",ee),window.removeEventListener("focus",ee),window.removeEventListener("pageshow",ee),clearTimeout(X),clearTimeout(Y),clearInterval(M)}},[A]),w.useEffect(()=>()=>{clearTimeout(j.current.enter),clearTimeout(j.current.exit),clearTimeout(j.current.hide)},[]),w.useEffect(()=>{if(qi())return;if(Ep()||A){rr();return}let X,Y;return X=window.setTimeout(()=>{J("Drag me, tap me."),rr(),Y=window.setTimeout(()=>{H()},wp),j.current.hide=Y},xp),()=>{clearTimeout(X),clearTimeout(Y)}},[A]);const z=w.useCallback(()=>{clearTimeout(j.current.enter),clearTimeout(j.current.exit),clearTimeout(j.current.hide),j.current={}},[]),J=w.useCallback(X=>{z(),D({text:X,phase:"entering"}),j.current.enter=window.setTimeout(()=>{D(ee=>ee&&ee.text===X?{...ee,phase:"visible"}:ee);const Y=Ap(X);j.current.hide=window.setTimeout(()=>{H()},Y)},fp)},[z]),H=w.useCallback(()=>{z(),D(X=>X?(j.current.exit=window.setTimeout(()=>{D(null)},pp),{...X,phase:"leaving"}):null)},[z]),K=L==="thinking"?"thinking…":L==="executing"?"working on it":null;w.useEffect(()=>{K?J(K):D(X=>X?((X.text==="thinking…"||X.text==="working on it")&&H(),X):null)},[K]);const $=w.useCallback(X=>{var Y,ee;X.button===0&&((ee=(Y=X.target).setPointerCapture)==null||ee.call(Y,X.pointerId),R.current={pointer:{x:X.clientX,y:X.clientY},pos:c,moved:!1},x(!0),qi()||rr())},[c]),F=w.useCallback(X=>{const Y=R.current;if(!Y)return;const ee=X.clientX-Y.pointer.x,ae=X.clientY-Y.pointer.y;!Y.moved&&Math.hypot(ee,ae)<sp||(Y.moved=!0,A&&m(null),d(Bs({x:Y.pos.x+ee,y:Y.pos.y+ae})))},[A]),V=w.useCallback(X=>{var ee,ae;const Y=R.current;if((ae=(ee=X.target).releasePointerCapture)==null||ae.call(ee,X.pointerId),R.current=null,x(!1),Y&&Y.moved){const M=Yi(c);m(M||null)}else Y&&!Y.moved&&(A&&m(null),u(M=>!M))},[c,A]),se=w.useCallback(()=>{A&&_(!0)},[A]),q=w.useCallback(()=>{_(!1)},[]),te=w.useCallback(X=>{if(X.ctrlKey||f)return;let Y=X.target;for(;Y&&Y!==document.body;){const ee=window.getComputedStyle(Y),ae=Y.scrollHeight>Y.clientHeight,M=ee.overflowY;if(ae&&(M==="auto"||M==="scroll")){Y.scrollTop+=X.deltaY,X.preventDefault();return}Y=Y.parentElement}window.scrollBy({top:X.deltaY,left:X.deltaX,behavior:"auto"}),X.preventDefault()},[f]),Q=Lp(c,l),be=(C==null?void 0:C.text)??null,Ce=(C==null?void 0:C.phase)??null,ce=w.useCallback(X=>{var Y,ee;X.button===0&&(X.stopPropagation(),(ee=(Y=X.target).setPointerCapture)==null||ee.call(Y,X.pointerId),P.current={pointer:{x:X.clientX,y:X.clientY},size:l,anchorSide:Q.side,anchorVertical:Q.vertical},E(!0))},[l,Q.side,Q.vertical]),ye=w.useCallback(X=>{const Y=P.current;if(!Y)return;const ee=X.clientX-Y.pointer.x,ae=X.clientY-Y.pointer.y,M=Y.anchorSide==="right"?ee:-ee,W=Y.anchorVertical==="below"?ae:-ae;p(Nr({w:Y.size.w+M,h:Y.size.h+W}))},[]),xe=w.useCallback(X=>{var Y,ee;(ee=(Y=X.target).releasePointerCapture)==null||ee.call(Y,X.pointerId),P.current=null,E(!1)},[]),ve=Cp(A,k);return n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",left:c.x,top:c.y,width:et,height:ft,zIndex:2147482e3,cursor:f?"grabbing":A?"pointer":"grab",touchAction:"none",userSelect:"none",animation:T||A?void 0:"titan-dock-in 220ms ease-out both",transform:ve,transition:f?"none":`${up}, ${hp}`},onPointerDown:$,onPointerMove:F,onPointerUp:V,onPointerCancel:V,onPointerEnter:se,onPointerLeave:q,onWheel:te,title:g?"Click to minimize TITAN chat — drag to move":"Click to open TITAN chat — drag to move",children:n.jsx(Zf,{state:L,size:et,quip:be,bubblePhase:Ce,somaActive:o,followCursor:!f,edgeRotate:Tp(A),faceFlip:Rp(c),edgeHidden:!!A})}),g&&n.jsxs("div",{style:{position:"fixed",left:Q.left,top:Q.top,width:l.w,height:l.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:y||B.current||T?void 0:"titan-dock-panel-in 180ms cubic-bezier(0.2, 0.9, 0.25, 1) both",transformOrigin:`${Q.side==="right"?"left":"right"} ${Q.vertical==="below"?"top":"bottom"}`},children:[n.jsx(fl,{space:t,onClose:()=>u(!1),onMascotState:v}),n.jsx("div",{onPointerDown:ce,onPointerMove:ye,onPointerUp:xe,onPointerCancel:xe,title:"Drag to resize",style:{position:"absolute",[Q.vertical==="below"?"bottom":"top"]:0,[Q.side==="right"?"right":"left"]:0,width:18,height:18,cursor:Q.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:y?1:.55},children:Q.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:`
967
- @keyframes titan-dock-in {
968
- from { opacity: 0; transform: translate3d(0, 4px, 0); }
969
- to { opacity: 1; transform: translate3d(0, 0, 0); }
970
- }
971
- @keyframes titan-dock-panel-in {
972
- from { opacity: 0; transform: translate3d(0, 12px, 0) scale(0.968); }
973
- to { opacity: 1; transform: translate3d(0, 0, 0) scale(1); }
974
- }
975
- @media (prefers-reduced-motion: reduce) {
976
- .titan-dock-root, .titan-dock-panel {
977
- animation: none !important;
978
- transition: none !important;
979
- }
980
- }
981
- `})]})}const Dp=3e4,Mp=3e4;function Op(){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 d=async()=>{var p;try{const g=await ge("/api/soma/advisories?limit=5");if(!g.ok)return;const u=await g.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),Mp);return}}catch{}};d();const l=setInterval(d,Dp);return()=>{c=!0,clearInterval(l),i.current&&clearTimeout(i.current)}},[]),!t)return null;const o=()=>{r.current.add(t.at),e(null),i.current&&clearTimeout(i.current)};return n.jsx("div",{className:"titan-toast-surface",style:{position:"fixed",bottom:100,right:24,maxWidth:340,padding:"12px 14px",borderRadius:10,borderLeft:"3px solid var(--theme-accent)",fontSize:12,zIndex:60},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.8,color:"var(--theme-accent)",marginBottom:4,fontFamily:"var(--theme-font-mono)"},children:"TITAN noticed"}),n.jsx("div",{style:{lineHeight:1.45,color:"var(--theme-ink)"},children:t.rationale}),n.jsxs("div",{style:{fontSize:10,color:"var(--theme-ink-soft)",marginTop:6,textTransform:"uppercase",letterSpacing:.5,fontFamily:"var(--theme-font-mono)"},children:["suggestion: ",t.action]})]}),n.jsx("button",{onClick:o,"aria-label":"Dismiss",className:"titan-close-btn",style:{fontSize:16,lineHeight:1,marginTop:-2},children:"×"})]})})}const xl="titan-sidebar-collapsed",wl="titan-sidebar-canvas-pin";function vl(t){return/^\/space\/[^/]+\/?$/.test(t)}function Ki(t,e=s=>typeof localStorage>"u"?null:localStorage.getItem(s)){try{if(vl(t))return e(wl)!=="1";const s=e(xl);if(s!==null)return s==="1"}catch{}return!1}function Pp(t,e,s=(r,i)=>{typeof localStorage>"u"||localStorage.setItem(r,i)}){try{vl(e)?s(wl,t?"0":"1"):s(xl,t?"1":"0")}catch{}}function Wp(){const t=typeof localStorage<"u"?localStorage.getItem("titan-token"):null;return t?{Authorization:`Bearer ${t}`}:{}}async function cs(t,e){const s=await fetch(t,{...e,headers:{"Content-Type":"application/json",...Wp(),...(e==null?void 0:e.headers)||{}}});if(!s.ok)throw new Error(`${s.status} ${s.statusText}`);return s.json()}function Bp(){const t=no(),e=Rl(),{logout:s}=Al(),[r,i]=w.useState([]),[o,c]=w.useState(null),[d,l]=w.useState([]),[p,g]=w.useState(!1),[u,f]=w.useState(!1),[x,y]=w.useState(null),[E,L]=w.useState(()=>Ki(typeof window<"u"?window.location.pathname:"/"));w.useEffect(()=>{L(Ki(e.pathname))},[e.pathname]);const v=w.useCallback(()=>{L(S=>{const C=!S;return Pp(C,typeof window<"u"?window.location.pathname:"/"),C})},[]),A=w.useCallback(async()=>{try{const S=await cs("/api/spaces");i(S.spaces),c(S.activeSpaceId),y(null)}catch(S){y(S.message)}},[]);w.useEffect(()=>{A(),cs("/api/spaces/presets").then(C=>l(C.presets)).catch(()=>{});const S=()=>A();return window.addEventListener("titan:spaces:refresh",S),()=>window.removeEventListener("titan:spaces:refresh",S)},[A]);const m=w.useCallback(async S=>{try{await cs(`/api/spaces/${S}/activate`,{method:"POST"}),c(S),t(`/space/${S}`)}catch(C){y(C.message)}},[t]),k=w.useCallback(async S=>{f(!0);try{const C=S.preset?d.find(j=>j.id===S.preset):void 0,D=await cs("/api/spaces",{method:"POST",body:JSON.stringify({name:S.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 A(),t(`/space/${D.space.id}`),g(!1)}catch(C){y(C.message)}finally{f(!1)}},[t,d,A]),_=w.useCallback(async S=>{if(window.confirm("Archive this Space? Widgets will be preserved and you can restore it later."))try{await cs(`/api/spaces/${S}`,{method:"DELETE"}),await A()}catch(C){y(C.message)}},[A]);if(!e.pathname.startsWith("/space")&&!e.pathname.startsWith("/mission")&&e.pathname!=="/")return null;const T=e.pathname.startsWith("/mission");return E?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-60 flex flex-col relative flex-shrink-0",style:{background:"var(--theme-menu-bg-solid, #0a0e1a)",borderRight:"1px solid var(--theme-menu-border, #1f2937)",color:"var(--theme-ink, #d4d4d8)",fontFamily:"var(--theme-font-display, ui-sans-serif, system-ui)"},children:[n.jsxs("div",{className:"px-4 pt-4 pb-3 flex items-center justify-between",style:{borderBottom:"1px solid var(--theme-menu-border, #1f2937)"},children:[n.jsxs("button",{type:"button",onClick:()=>t("/space/home"),className:"flex items-center gap-2 group",title:"TITAN home",children:[n.jsx("span",{className:"w-7 h-7 rounded-md flex items-center justify-center text-[14px] font-bold leading-none",style:{background:"var(--theme-metal, #c4a35a)",color:"var(--theme-bolt, #2a1808)",boxShadow:"0 1px 2px var(--theme-shadow, rgba(0,0,0,0.3))",fontFamily:"var(--theme-font-display, serif)"},children:"T"}),n.jsx("span",{className:"text-[15px] tracking-[0.18em] font-semibold leading-none",style:{color:"var(--theme-ink, #e8e8ff)"},children:"TITAN"})]}),n.jsx("button",{type:"button",onClick:v,className:"w-6 h-6 rounded-md flex items-center justify-center text-base transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},title:"Hide sidebar","aria-label":"Hide sidebar",children:"‹"})]}),n.jsxs("nav",{className:"flex-1 overflow-y-auto py-3 px-2",children:[n.jsxs("div",{className:"mb-5",children:[n.jsx(Ji,{children:"Missions"}),n.jsx(Xi,{onClick:()=>t("/mission"),active:T&&e.pathname==="/mission",icon:"✶",label:"New Mission",title:"Start a new mission or pick a template"}),n.jsx(Xi,{onClick:()=>t("/mission/library"),active:e.pathname==="/mission/library",icon:"❑",label:"Library",title:"Every mission you've run"})]}),n.jsxs("div",{className:"mb-2 flex items-center justify-between px-2",children:[n.jsx(Ji,{inline:!0,children:"Workspaces"}),n.jsx("button",{type:"button",onClick:()=>g(!0),className:"w-5 h-5 rounded flex items-center justify-center text-sm leading-none transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-ink, #fff)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},title:"Create a new Workspace","aria-label":"Create a new Workspace",children:"+"})]}),x&&n.jsx("div",{className:"mx-1 my-1 px-2 py-2 text-[11px] rounded",style:{color:"var(--theme-accent, #ef4444)",background:"rgba(239,68,68,0.08)"},children:x}),r.length===0&&!x&&n.jsxs("div",{className:"px-2 py-3 text-[11px] leading-relaxed italic",style:{color:"var(--theme-ink-soft, #71717a)"},children:["No Workspaces yet. Tap + above, or ask TITAN",n.jsx("br",{}),'"make me a workspace for…"']}),r.map(S=>{const C=S.id===o;return n.jsxs("button",{type:"button",onClick:()=>m(S.id),onContextMenu:D=>{D.preventDefault(),_(S.id)},className:"w-full text-left px-2 py-1.5 rounded text-[13px] flex items-center gap-2 transition-colors",style:{background:C?"var(--theme-menu-active-bg, #1f2937)":"transparent",color:C?"var(--theme-menu-active-fg, #fff)":"var(--theme-ink, #d4d4d8)"},onMouseEnter:D=>{C||(D.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))")},onMouseLeave:D=>{C||(D.currentTarget.style.background="transparent")},title:`${S.name} · right-click to archive`,children:[S.icon&&n.jsx("span",{className:"text-base leading-none",children:S.icon}),n.jsx("span",{className:"flex-1 truncate",children:S.name}),S.widgets.length>0&&n.jsx("span",{className:"text-[10px] tabular-nums px-1.5 rounded-full",style:{color:"var(--theme-ink-soft, #71717a)",background:"var(--theme-menu-hover, rgba(244,215,145,0.10))"},children:S.widgets.length})]},S.id)})]}),n.jsxs("div",{className:"px-2 py-2 flex flex-col gap-0.5",style:{borderTop:"1px solid var(--theme-menu-border, #1f2937)"},children:[n.jsxs("a",{href:"/command-post",className:"px-2 py-1.5 rounded text-[12px] flex items-center gap-2 transition-colors no-underline",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-ink, #fff)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},children:[n.jsx("span",{"aria-hidden":!0,children:"⚙"}),n.jsx("span",{children:"Admin"})]}),n.jsxs("button",{type:"button",onClick:()=>{s(),window.location.assign("/")},className:"w-full text-left px-2 py-1.5 rounded text-[12px] flex items-center gap-2 transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-accent, #ef4444)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},title:"Sign out — mints a fresh token next login",children:[n.jsx("span",{"aria-hidden":!0,children:"⇥"}),n.jsx("span",{children:"Sign out"})]})]}),p&&n.jsx(Up,{presets:d,creating:u,onCreate:k,onClose:()=>g(!1)})]})}function Up(t){const{presets:e,creating:s,onCreate:r,onClose:i}=t,[o,c]=w.useState(""),[d,l]=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:()=>{l(p.id),o||c(p.name)},className:`text-left px-3 py-2 rounded border ${d===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:d}),disabled:s||!o.trim()&&!d,className:"px-3 py-1.5 bg-[#3b82f6] hover:bg-[#2563eb] disabled:opacity-50 text-white text-sm rounded",children:s?"Creating…":"Create"})]})]})})}function Ji({children:t,inline:e=!1}){return n.jsx("div",{className:`${e?"":"px-2 mb-1.5"} text-[10px] uppercase tracking-[0.18em] font-semibold`,style:{color:"var(--theme-metal, #c4a35a)"},children:t})}function Xi({active:t,icon:e,label:s,title:r,onClick:i}){return n.jsxs("button",{type:"button",onClick:i,className:"w-full text-left px-2 py-1.5 rounded text-[13px] flex items-center gap-2 transition-colors",style:{background:t?"var(--theme-menu-active-bg, #1f2937)":"transparent",color:t?"var(--theme-menu-active-fg, #fff)":"var(--theme-ink, #d4d4d8)"},onMouseEnter:o=>{t||(o.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))")},onMouseLeave:o=>{t||(o.currentTarget.style.background="transparent")},title:r,children:[n.jsx("span",{className:"w-5 text-center leading-none",style:{color:t?"var(--theme-menu-active-fg, #fff)":"var(--theme-metal, #c4a35a)"},"aria-hidden":!0,children:e}),n.jsx("span",{className:"flex-1 truncate",children:s})]})}const ir=4e3,Fp=[{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 $p({space:t,open:e,onClose:s,onSaved:r}){const[i,o]=w.useState(t.agentInstructions??""),[c,d]=w.useState(!1),[l,p]=w.useState(null),g=w.useRef(null);w.useEffect(()=>{if(e){o(t.agentInstructions??""),p(null);const f=setTimeout(()=>{var x;return(x=g.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>ir){p(`Instructions must be ${ir} characters or fewer.`);return}d(!0),p(null);try{const f=i.trim(),x={...t,agentInstructions:f||void 0,updatedAt:new Date().toISOString()};ke.save(x),r==null||r(f),s()}catch(f){p(f.message)}finally{d(!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(ps,{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(Es,{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:g,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()," / ",ir.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:Fp.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))})]}),l&&n.jsx("div",{className:"text-[11px] text-[#ef4444] bg-[#ef4444]/10 border border-[#ef4444]/30 rounded p-2",children:l})]}),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(bn,{className:"w-3.5 h-3.5"}),c?"Saving…":"Save"]})]})]})}):null}const zp=12,Hp=["react","vanilla","html"];function Vp({widget:t,spaceId:e,open:s,onClose:r,onSaved:i}){const[o,c]=w.useState(t.source),[d,l]=w.useState(t.format),[p,g]=w.useState(t.name),[u,f]=w.useState(!1),[x,y]=w.useState(null),[E,L]=w.useState(!1),v=w.useRef(null);w.useEffect(()=>{if(s){c(t.source),l(t.format),g(t.name),y(null),L(!1);const T=setTimeout(()=>{var S;return(S=v.current)==null?void 0:S.focus()},50);return()=>clearTimeout(T)}},[s,t.id,t.source,t.format,t.name]),w.useEffect(()=>{if(!s)return;const T=S=>{S.key==="Escape"&&r(),S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&A()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[s]);const A=w.useCallback(async()=>{f(!0),y(null);try{const T=o!==t.source||d!==t.format,S=Array.isArray(t.versions)?t.versions:[],C=T?[...S,{source:t.source,format:t.format,savedAt:t.updatedAt}].slice(-zp):S,D={name:p.trim()||t.name,source:o,format:d,versions:C};ke.updateWidget(e,t.id,D),i==null||i({...t,...D,updatedAt:Date.now()}),r()}catch(T){y(T.message)}finally{f(!1)}},[o,d,p,t,e,i,r]),m=w.useCallback(T=>{c(T.source),l(T.format),L(!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($l,{className:"w-4 h-4 text-[#6366f1] shrink-0"}),n.jsx("input",{value:p,onChange:T=>g(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:()=>L(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 ${E?"bg-[#18181b] text-white":""}`,title:k.length===0?"No history yet":`${k.length} prior version${k.length===1?"":"s"}`,children:n.jsx(uc,{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(Es,{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:d,onChange:T=>l(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:Hp.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:Gp[d]}),E&&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,S)=>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:()=>m(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(co,{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?"…":""]}),S===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||d!==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:()=>{A()},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(bn,{className:"w-3.5 h-3.5"}),u?"Saving…":"Save widget"]})]})]})]})})}const Gp={react:`// Return a React component named "Widget". titan.* APIs are
982
- // available for fetch/api/state. Example:
983
- function Widget({ titan }) {
984
- const [n, setN] = React.useState(0);
985
- return <button onClick={() => setN(n + 1)}>Clicked {n} times</button>;
986
- }`,vanilla:`// Export a function (container, titan) => cleanup | void.
987
- // Called once to mount; return a cleanup function if needed.
988
- (container, titan) => {
989
- container.innerHTML = '<button>Hello</button>';
990
- const btn = container.querySelector('button');
991
- btn.addEventListener('click', () => btn.textContent = 'Clicked!');
992
- }`,html:`<!-- Raw HTML. No scripts run. -->
993
- <div style="padding:16px;color:#e4e4e7">Hello, widget!</div>`,iframe:"",system:""};function qp(t){return String(t||"").startsWith("system:")?"system":"react"}const Yp={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 Kp(t){return t.split(/[-_/]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Jp({open:t,onClose:e}){const[s,r]=w.useState([]),[i,o]=w.useState([]),[c,d]=w.useState("All"),[l,p]=w.useState(""),[g,u]=w.useState(null),[f,x]=w.useState(!1),[y,E]=w.useState(null);w.useEffect(()=>{t&&(x(!0),ge("/api/widget-gallery").then(m=>m.json()).then(m=>{r(m.templates||[]),o(m.categories||[]),x(!1)}).catch(m=>{E(m.message),x(!1)}))},[t]),w.useEffect(()=>{if(!t)return;const m=k=>{k.key==="Escape"&&e()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,e]);const L=w.useMemo(()=>{const m=c==="All"?s:s.filter(_=>_.category===c),k=l.trim().toLowerCase();return k?m.filter(_=>[_.name,_.description,_.category,..._.tags||[],..._.triggers||[]].join(" ").toLowerCase().includes(k)):m},[c,l,s]);if(!t)return null;const v=async m=>{var k,_,T,S;u(m.id),E(null);try{const C=await ge(`/api/widget-gallery/${encodeURIComponent(m.id)}`);if(!C.ok)throw new Error(`Could not load template (${C.status})`);const D=await C.json(),j={templateId:m.id,templateName:D.name||m.name,source:D.source,format:qp(D.source),defaultSize:{w:((k=D.defaultSize)==null?void 0:k.w)??((_=m.defaultSize)==null?void 0:_.w)??4,h:((T=D.defaultSize)==null?void 0:T.h)??((S=m.defaultSize)==null?void 0:S.h)??4}};window.dispatchEvent(new CustomEvent("titan:gallery:run-template",{detail:j})),e()}catch(C){E(C.message)}finally{u(null)}},A=["All",...i.map(m=>m.category)];return n.jsx("div",{className:"fixed inset-0 z-[2147483150] flex items-center justify-center p-3 sm:p-4 titan-menu-overlay",onClick:e,children:n.jsxs("div",{className:"w-full max-w-5xl titan-widget-gallery-window flex flex-col",style:{height:"min(760px, 92vh)"},onClick:m=>m.stopPropagation(),children:[n.jsxs("div",{className:"titan-widget-gallery-titlebar",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"titan-window-dot"}),n.jsx("span",{className:"titan-window-dot titan-window-dot--dim"}),n.jsx("span",{className:"titan-window-dot titan-window-dot--dim"}),n.jsx(mn,{className:"w-4 h-4 ml-1",style:{color:"var(--theme-accent)"}}),n.jsx("h3",{className:"font-semibold text-sm",style:{color:"var(--theme-ink)",fontFamily:"var(--theme-font-display)"},children:"Widget gallery"}),n.jsx("span",{className:"text-[10px]",style:{color:"var(--theme-ink-soft)"},children:f?"Loading…":`${s.length} templates`})]}),n.jsx("button",{onClick:e,className:"titan-close-btn",title:"Close (Esc)","aria-label":"Close",children:n.jsx(Es,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"titan-widget-gallery-category-row",children:A.map(m=>{var k;return n.jsxs("button",{onClick:()=>d(m),className:`titan-widget-gallery-category ${c===m?"titan-widget-gallery-category--active":""}`,children:[Kp(m),m!=="All"&&n.jsx("span",{className:"ml-1.5 text-[9px] opacity-70",children:((k=i.find(_=>_.category===m))==null?void 0:k.count)??0})]},m)})}),n.jsx("div",{className:"px-4 sm:px-5 py-2 border-b",style:{borderColor:"var(--theme-menu-border)"},children:n.jsxs("label",{className:"titan-widget-gallery-search",children:[n.jsx(uo,{className:"w-3.5 h-3.5"}),n.jsx("input",{value:l,onChange:m=>p(m.target.value),placeholder:"Search templates...",className:"flex-1 bg-transparent text-xs outline-none"})]})}),n.jsxs("div",{className:"flex-1 overflow-auto p-4",children:[f&&n.jsx("div",{className:"flex items-center justify-center h-full text-sm",style:{color:"var(--theme-ink-soft)"},children:"Loading templates…"}),y&&n.jsxs("div",{className:"flex items-center justify-center h-full text-sm",style:{color:"var(--color-error)"},children:["Error: ",y]}),!f&&!y&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:L.map(m=>n.jsxs("button",{onClick:()=>v(m),disabled:g!==null,className:"titan-widget-gallery-card group",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{background:Yp[m.category]??"#9ca3af"}}),n.jsx("span",{className:"text-[12px] font-medium truncate",style:{color:"var(--theme-ink)"},children:m.name})]}),n.jsx(ho,{className:"w-3 h-3 transition-colors shrink-0"})]}),n.jsx("div",{className:"text-[11px] leading-relaxed line-clamp-2",style:{color:"var(--theme-ink-soft)"},children:g===m.id?"Adding to canvas...":m.description}),m.tags&&m.tags.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:m.tags.slice(0,3).map(k=>n.jsx("span",{className:"titan-widget-gallery-tag",children:k},k))})]},m.id))}),L.length===0&&n.jsx("div",{className:"flex items-center justify-center h-40 text-sm",style:{color:"var(--theme-ink-soft)"},children:"No templates in this category."})]}),n.jsxs("div",{className:"titan-widget-gallery-note",children:[n.jsx(xo,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"}),n.jsxs("div",{className:"text-[11px] leading-relaxed",children:["Don’t see what you want? Open the chat (click the mascot) and describe your widget in plain English. TITAN can build anything that runs inside a sandboxed iframe with access to ",n.jsx("span",{className:"font-mono",children:"titan.fetch"}),","," ",n.jsx("span",{className:"font-mono",children:"titan.api.call"}),", and"," ",n.jsx("span",{className:"font-mono",children:"titan.state"}),"."]})]})]})]})})}const Xp=[{type:"widget",source:"system:nav",name:"Nav Widget",w:3,h:4,icon:n.jsx(xo,{className:"w-4 h-4"})},{type:"widget",source:"system:chat",name:"Chat Widget",w:4,h:5,icon:n.jsx(xn,{className:"w-4 h-4"})},{type:"widget",source:"system:soma",name:"SOMA",w:6,h:6,icon:n.jsx(xt,{className:"w-4 h-4"})},{type:"widget",source:"system:command-post",name:"Command Post",w:8,h:6,icon:n.jsx(lo,{className:"w-4 h-4"})},{type:"widget",source:"system:intelligence",name:"Intelligence",w:6,h:5,icon:n.jsx(ao,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-graph",name:"Memory Graph",w:8,h:7,icon:n.jsx(sc,{className:"w-4 h-4"})},{type:"widget",source:"system:voice",name:"Voice",w:5,h:5,icon:n.jsx(fo,{className:"w-4 h-4"})},{type:"widget",source:"system:infra",name:"Infrastructure",w:6,h:4,icon:n.jsx(Ir,{className:"w-4 h-4"})},{type:"widget",source:"system:tools",name:"Tools",w:5,h:4,icon:n.jsx(Tr,{className:"w-4 h-4"})},{type:"widget",source:"system:settings",name:"Settings",w:5,h:5,icon:n.jsx(Cr,{className:"w-4 h-4"})},{type:"widget",source:"system:files",name:"Files",w:4,h:6,icon:n.jsx(yn,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-wiki",name:"Memory Wiki",w:6,h:6,icon:n.jsx(ps,{className:"w-4 h-4"})},{type:"widget",source:"system:autoresearch",name:"Autoresearch",w:6,h:6,icon:n.jsx(po,{className:"w-4 h-4"})},{type:"widget",source:"system:self-proposals",name:"Self-Proposals",w:6,h:6,icon:n.jsx(bo,{className:"w-4 h-4"})},{type:"widget",source:"system:overview",name:"Overview",w:6,h:5,icon:n.jsx(ro,{className:"w-4 h-4"})},{type:"widget",source:"system:sessions",name:"Sessions",w:6,h:5,icon:n.jsx(ms,{className:"w-4 h-4"})},{type:"widget",source:"system:watch",name:"Watch",w:8,h:7,icon:n.jsx(Yt,{className:"w-4 h-4"})},{type:"widget",source:"system:backup",name:"Backup Manager",w:6,h:6,icon:n.jsx(mo,{className:"w-4 h-4"})},{type:"widget",source:"system:training",name:"Training Dashboard",w:6,h:6,icon:n.jsx(xt,{className:"w-4 h-4"})},{type:"widget",source:"system:recipes",name:"Recipe Kitchen",w:6,h:6,icon:n.jsx(ps,{className:"w-4 h-4"})},{type:"widget",source:"system:vram",name:"VRAM Monitor",w:6,h:6,icon:n.jsx(Rr,{className:"w-4 h-4"})},{type:"widget",source:"system:teams",name:"Team Hub",w:6,h:6,icon:n.jsx(Ar,{className:"w-4 h-4"})},{type:"widget",source:"system:cron",name:"Cron Scheduler",w:6,h:6,icon:n.jsx(ms,{className:"w-4 h-4"})},{type:"widget",source:"system:checkpoints",name:"Checkpoints",w:6,h:5,icon:n.jsx(bn,{className:"w-4 h-4"})},{type:"widget",source:"system:organism",name:"Organism Monitor",w:6,h:6,icon:n.jsx(Lr,{className:"w-4 h-4"})},{type:"widget",source:"system:fleet",name:"Fleet Router",w:6,h:5,icon:n.jsx(go,{className:"w-4 h-4"})},{type:"widget",source:"system:browser",name:"Browser Tools",w:6,h:5,icon:n.jsx(io,{className:"w-4 h-4"})},{type:"widget",source:"system:eval",name:"Test Lab",w:6,h:6,icon:n.jsx(yo,{className:"w-4 h-4"})}];function _l({currentSpaceId:t,onSpaceSelect:e,onAction:s,onClose:r}){const[i,o]=w.useState(""),[c,d]=w.useState(0),l=w.useRef(null),p=ke.list(),g=w.useMemo(()=>{const u=i.toLowerCase(),f=p.filter(y=>y.id!==t&&y.name.toLowerCase().includes(u)).map(y=>({type:"space",id:y.id,name:y.name,color:y.color})),x=Xp.filter(y=>y.name.toLowerCase().includes(u)).map(y=>({type:"action",action:y,name:y.name}));return[...f,...x]},[i,p,t]);return w.useEffect(()=>{var u;(u=l.current)==null||u.focus()},[]),w.useEffect(()=>{d(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(),d(x=>Math.min(x+1,g.length-1));return}if(f.key==="ArrowUp"){f.preventDefault(),d(x=>Math.max(x-1,0));return}if(f.key==="Enter"){f.preventDefault();const x=g[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)},[g,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(uo,{className:"w-4 h-4 text-[#3f3f46]"}),n.jsx("input",{ref:l,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(Es,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"max-h-[50vh] overflow-auto py-1",children:[g.length===0&&n.jsxs("div",{className:"px-4 py-6 text-center text-xs text-[#52525b]",children:['No results for "',i,'"']}),g.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 Qp=oe.lazy(()=>le(()=>import("./SomaView-eG3wI4S1.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),Ae={bgBase:"var(--theme-bg-base, var(--color-bg, #09090b))",surface:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-secondary, #18181b)) 82%, transparent)",surfaceSoft:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-tertiary, #27272a)) 62%, transparent)",border:"color-mix(in srgb, var(--theme-metal-dark, var(--color-border, #3f3f46)) 66%, transparent)",ink:"var(--theme-paper-fg, var(--color-text, #fafafa))",inkSoft:"color-mix(in srgb, var(--theme-paper-fg, var(--color-text-secondary, #a1a1aa)) 72%, transparent)",paperFg:"var(--theme-paper-fg, var(--color-text-secondary, #a1a1aa))",accent:"var(--theme-accent, var(--color-accent, #6366f1))",success:"var(--color-success, #22c55e)",error:"var(--color-error, #ef4444)"},or={background:Ae.bgBase,color:Ae.ink};function kl(){const[t,e]=w.useState(null),[s,r]=w.useState(!1),[i,o]=w.useState(null),c=w.useCallback(async()=>{var p;try{const g=await ge("/api/config");if(!g.ok)throw new Error(`HTTP ${g.status}`);const u=await g.json();e(!!((p=u==null?void 0:u.organism)!=null&&p.enabled)),o(null)}catch(g){o(g.message),e(!1)}},[]);w.useEffect(()=>{c()},[c]);const d=w.useRef(0),l=w.useCallback(async p=>{const g=++d.current;r(!0),o(null);try{const u=await ge("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:{enabled:p}})});if(g!==d.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(g!==d.current)return;o(u.message)}finally{g===d.current&&r(!1)}},[]);return t===null?n.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs",style:{...or,color:Ae.paperFg},children:"Loading Soma…"}):t?n.jsxs("div",{className:"w-full h-full overflow-auto flex flex-col",style:or,children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b",style:{background:Ae.surface,borderColor:Ae.border},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full animate-pulse",style:{background:Ae.success}}),n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:Ae.success},children:"Soma active"})]}),n.jsxs("button",{onClick:()=>l(!1),disabled:s,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[10px] disabled:opacity-60 transition-colors",style:{borderColor:Ae.border,color:Ae.inkSoft,background:Ae.surfaceSoft},title:"Disable Soma",children:[n.jsx(pi,{className:"w-3 h-3"}),s?"saving…":"disable"]})]}),n.jsx("div",{className:"flex-1 overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs",style:{color:Ae.paperFg},children:"Loading Soma dashboard…"}),children:n.jsx(Qp,{})})})]}):n.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-4 p-6 text-center",style:or,children:[n.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center",style:{background:"color-mix(in srgb, var(--theme-accent, var(--color-accent, #6366f1)) 18%, transparent)",border:`1px solid ${Ae.border}`},children:n.jsx(Yt,{className:"w-7 h-7",style:{color:Ae.accent}})}),n.jsxs("div",{className:"space-y-1 max-w-md",children:[n.jsx("h3",{className:"text-lg font-semibold",style:{color:Ae.ink},children:"Soma is off"}),n.jsx("p",{className:"text-xs leading-relaxed",style:{color:Ae.inkSoft},children:"TITAN’s homeostatic drive layer. When enabled, TITAN has a sense of its own state — purpose, curiosity, hunger, safety, social, rest — and will propose work when those drives drift. Every proposal still requires your approval."})]}),n.jsxs("button",{onClick:()=>l(!0),disabled:s,className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-full disabled:opacity-60 disabled:cursor-not-allowed text-sm font-medium transition-colors",style:{background:Ae.accent,color:"var(--theme-bg-base, var(--color-bg, #09090b))"},children:[n.jsx(pi,{className:"w-4 h-4"}),s?"Enabling…":"Enable Soma"]}),i&&n.jsx("p",{className:"text-xs",style:{color:Ae.error},children:i}),n.jsx("p",{className:"text-[10px]",style:{color:Ae.paperFg},children:"You can turn this off anytime from the same button."})]})}const Zp={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)"}},Ee={surface:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-secondary, #18181b)) 90%, transparent)",surfaceSoft:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-tertiary, #27272a)) 62%, transparent)",overlay:"color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 56%, transparent)",border:"color-mix(in srgb, var(--theme-metal-dark, var(--color-border, #3f3f46)) 66%, transparent)",metal:"var(--theme-metal, var(--color-border-light, #52525b))",ink:"var(--theme-paper-fg, var(--color-text, #fafafa))",accent:"var(--theme-accent, var(--color-accent, #6366f1))",warning:"var(--color-warning, #f59e0b)"};function em(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 tm(){const[t,e]=w.useState(!1),[s,r]=w.useState({emotion:"calm",intensity:.3,activity:"Observing"}),[i,o]=w.useState(!1),[c,d]=w.useState(()=>sm()),[l,p]=w.useState(!1),g=w.useRef({x:0,y:0}),u=w.useRef(null);w.useEffect(()=>{let v=!1;const A=async()=>{try{const k=await ge("/api/soma/state");if(!k.ok||v)return;const _=await k.json();if(v)return;r(em(Number((_==null?void 0:_.totalPressure)??0),Array.isArray(_==null?void 0:_.dominantDrives)?_.dominantDrives:[],!!(_!=null&&_.enabled)))}catch{}};A();const m=setInterval(A,15e3);return()=>{v=!0,clearInterval(m)}},[]),w.useEffect(()=>{const v=A=>{var m;(m=u.current)!=null&&m.contains(A.target)||o(!1)};return window.addEventListener("mousedown",v),()=>window.removeEventListener("mousedown",v)},[]);const f=v=>{v.button===0&&(g.current={x:v.clientX-c.x,y:v.clientY-c.y},p(!0))},x=v=>{l&&d({x:v.clientX-g.current.x,y:v.clientY-g.current.y})},y=()=>{p(!1)},E=Zp[s.emotion],L=s.activity==="Dormant"?Ee.metal:Ee.accent;return n.jsxs(n.Fragment,{children:[t&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center backdrop-blur-sm",style:{background:Ee.overlay},onClick:()=>e(!1),children:n.jsxs("div",{className:"border rounded-2xl shadow-2xl overflow-hidden",style:{width:"min(900px, 90vw)",height:"min(600px, 80vh)",background:Ee.surface,borderColor:Ee.border,color:Ee.ink,boxShadow:"0 24px 64px color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 72%, transparent)"},onClick:v=>v.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b",style:{borderColor:Ee.border},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(xt,{className:"w-4 h-4",style:{color:L}}),n.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",style:{color:Ee.ink},children:"SOMA Consciousness"})]}),n.jsx("button",{onClick:()=>e(!1),className:"p-1",style:{color:Ee.metal},children:n.jsx(Es,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"h-[calc(100%-40px)]",children:n.jsx(kl,{})})]})}),n.jsxs("div",{ref:u,className:"fixed z-50 select-none",style:{left:c.x,top:c.y},onMouseDown:f,onMouseMove:x,onMouseUp:y,onMouseLeave:y,children:[i&&n.jsxs("div",{className:"absolute bottom-full left-0 mb-2 backdrop-blur-xl border rounded-xl shadow-2xl overflow-hidden min-w-[160px] py-1",style:{background:Ee.surface,borderColor:Ee.border,boxShadow:"0 18px 40px color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 70%, transparent)"},children:[n.jsxs("button",{onClick:()=>{e(!0),o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(xt,{className:"w-3.5 h-3.5",style:{color:L}}),"Open SOMA"]}),n.jsxs("button",{onClick:()=>{o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(mn,{className:"w-3.5 h-3.5",style:{color:Ee.warning}}),"Summarize Canvas"]}),n.jsxs("button",{onClick:()=>{o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(Ll,{className:"w-3.5 h-3.5",style:{color:Ee.accent}}),"Run Self-Check"]})]}),n.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>!l&&e(!0),onContextMenu:v=>{v.preventDefault(),o(!0)},children:[n.jsx("div",{className:"absolute inset-0 rounded-full animate-ping opacity-20",style:{background:E.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:E.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%, ${L}, ${Ee.metal})`,boxShadow:`0 0 ${20+s.intensity*30}px ${E.glow}, inset 0 0 10px color-mix(in srgb, var(--theme-ink, var(--color-text, #fafafa)) 12%, transparent)`},children:n.jsx(xt,{className:"w-5 h-5",style:{color:Ee.ink}})}),n.jsx("div",{className:"absolute -bottom-5 left-1/2 -translate-x-1/2 whitespace-nowrap",children:n.jsx("span",{className:"text-[9px] font-medium uppercase tracking-wider px-1.5 py-0.5 rounded border",style:{color:Ee.ink,background:Ee.surfaceSoft,borderColor:Ee.border},children:s.activity})})]})]})]})}function sm(){if(typeof window>"u")return{x:280,y:80};const t=window.innerWidth<640;return{x:t?Math.max(16,window.innerWidth-96):280,y:t?220:80}}const nm=oe.lazy(()=>le(()=>import("./CommandPostHub-z55Yrhj1.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,27,28])));function rm(){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(nm,{})})})}const im=oe.lazy(()=>le(()=>import("./IntelligenceView-DZ4HxYZ3.js"),__vite__mapDeps([29,1,2,4])));function om(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Intelligence..."}),children:n.jsx(im,{})})})}const am=oe.lazy(()=>le(()=>import("./MemoryGraphPanel-JPurHV0L.js"),__vite__mapDeps([30,1,2,31,24,28,32])));function lm(){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(am,{})})})})}function cm(){const[t,e]=w.useState(!1);return t?n.jsx(zl,{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(fo,{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 dm=oe.lazy(()=>le(()=>import("./InfraView-C0zEuFrR.js"),__vite__mapDeps([33,1,2,4])));function um(){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(dm,{})})})}const hm=oe.lazy(()=>le(()=>import("./ToolsView-BvTN6vFn.js"),__vite__mapDeps([34,1,2,4])));function fm(){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(hm,{})})})}const pm=oe.lazy(()=>le(()=>import("./SettingsView-BtA67pol.js"),__vite__mapDeps([35,1,2,4])));function mm(){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(pm,{})})})}function gm(){const[t,e]=w.useState([]),[s,r]=w.useState("/"),[i,o]=w.useState(!1),[c,d]=w.useState(null),l=async()=>{o(!0),d(null);try{const p=await ge(`/api/files?path=${encodeURIComponent(s)}`);if(p.ok){const g=await p.json();e(g.files||[])}else e([]),d(`Couldn't load files (HTTP ${p.status})`)}catch(p){e([]),d(`Couldn't reach /api/files — ${p.message}`)}finally{o(!1)}};return w.useEffect(()=>{l()},[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(Hl,{className:"w-3 h-3"}),n.jsx("span",{children:s})]}),n.jsx("button",{onClick:l,className:"p-1 text-[#3f3f46] hover:text-[#71717a]",children:n.jsx(wn,{className:`w-3 h-3 ${i?"animate-spin":""}`})})]}),n.jsxs("div",{className:"flex-1 overflow-auto",children:[c&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#ef4444]/80",children:c}),!c&&!i&&t.length===0&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#52525b]",children:"No files"}),t.map(p=>n.jsxs("button",{onClick:()=>p.type==="directory"&&r(p.path),className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-[#27272a]/20 transition-colors",children:[p.type==="directory"?n.jsx(Vl,{className:"w-3.5 h-3.5 text-[#f59e0b]"}):n.jsx(yn,{className:"w-3.5 h-3.5 text-[#6366f1]"}),n.jsx("span",{className:"text-[12px] text-[#a1a1aa]",children:p.name})]},p.path))]})]})}const ym=oe.lazy(()=>le(()=>import("./SettingsPanel-Cumls7N2.js"),__vite__mapDeps([36,1,2,3,4,37,14,5,38,39,24,40,41,42,43])));function bm(){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(ym,{})})})}const xm=oe.lazy(()=>le(()=>import("./SecurityPanel-BMERf796.js"),__vite__mapDeps([44,1,2,37,14])));function wm(){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(xm,{})})})}const vm=oe.lazy(()=>le(()=>import("./AuditPanel-BaftX5MP.js"),__vite__mapDeps([45,1,2,37,14,24,46,47])));function _m(){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(vm,{})})})}const Qi={researcher:"#60a5fa",engineer:"#f87171",manager:"#a78bfa",ceo:"#fbbf24",general:"#9ca3af"},km={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 Sm(){const[t,e]=w.useState(null),[s,r]=w.useState({}),[i,o]=w.useState({}),[c,d]=w.useState(null),[l,p]=w.useState({}),[g,u]=w.useState(!0),f=w.useCallback(async()=>{d(null);try{const[E,L]=await Promise.all([ge("/api/specialists"),ge("/api/models")]);if(!E.ok)throw new Error(`Specialists request failed: ${E.status}`);if(!L.ok)throw new Error(`Models request failed: ${L.status}`);const v=await E.json(),A=await L.json();e(v),r(A);const m={};await Promise.all(v.map(async k=>{try{const _=await ge(`/api/specialists/${encodeURIComponent(k.id)}/recommendations`);if(_.ok){const T=await _.json();T.recommendations&&(m[k.id]=T.recommendations)}}catch{}})),o(m)}catch(E){d(E.message)}finally{u(!1)}},[]);w.useEffect(()=>{f()},[f]);const x=w.useCallback(E=>{const L=i[E];if(L&&L.length)return L.map(A=>A.id);const v=new Set;if(s&&typeof s=="object")for(const A of Object.keys(s)){const m=s[A];if(Array.isArray(m))for(const k of m)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 A of t)A!=null&&A.activeModel&&v.add(A.activeModel),A!=null&&A.defaultModel&&v.add(A.defaultModel);return Array.from(v).sort((A,m)=>A.localeCompare(m))},[i,s,t]),y=w.useCallback(async(E,L)=>{p(v=>({...v,[E]:"saving"}));try{const v=await ge(`/api/specialists/${encodeURIComponent(E)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:L})});if(!v.ok){const m=await v.text().catch(()=>"");throw new Error(`PATCH failed (${v.status}): ${m||v.statusText}`)}const A=await v.json();e(m=>(m==null?void 0:m.map(k=>k.id===E?{...k,activeModel:A.activeModel??k.defaultModel,overridden:(A.activeModel??k.defaultModel)!==k.defaultModel}:k))??null),p(m=>({...m,[E]:"saved"})),setTimeout(()=>{p(m=>{if(m[E]!=="saved")return m;const k={...m};return delete k[E],k})},1500)}catch(v){p(A=>({...A,[E]:"error"})),d(`${E}: ${v.message}`)}},[]);return g&&!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(Ar,{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(wn,{className:`w-3 h-3 ${g?"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(gn,{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(E=>n.jsx(jm,{row:E,models:x(E.id),recommendations:i[E.id]??[],state:l[E.id]??"idle",onChange:L=>y(E.id,L),onReset:()=>y(E.id,null)},E.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 jm({row:t,models:e,recommendations:s,state:r,onChange:i,onReset:o}){var u;const c=Qi[t.role]??Qi.general,d=s.find(f=>f.id===t.activeModel),l=s[0]??null,[p,g]=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(L=>L.id===f),y=(x==null?void 0:x.badges)??[],E=y.length?`${f} [${y.join(", ")}]`:f;return n.jsx("option",{value:f,children:E},f)})}),d&&d.badges.length>0&&n.jsx("div",{className:"hidden sm:flex items-center gap-1 shrink-0",children:d.badges.slice(0,3).map(f=>n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${km[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(co,{className:"w-3 h-3"}),"Reset"]}),n.jsx("button",{onClick:()=>g(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(fi,{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(wn,{className:"w-3.5 h-3.5 animate-spin text-[#6366f1]"}),r==="saved"&&n.jsx(mi,{className:"w-3.5 h-3.5 text-[#10b981]"}),r==="error"&&n.jsx(gn,{className:"w-3.5 h-3.5 text-[#ef4444]"})]})]})]}),p&&n.jsxs("div",{className:"px-3 pb-3 space-y-1.5",children:[d&&n.jsxs("div",{className:"flex items-start gap-2 text-[11px] text-[#a1a1aa]",children:[n.jsx(fi,{className:"w-3 h-3 mt-0.5 shrink-0 text-[#6366f1]"}),n.jsx("span",{children:d.rationale})]}),l&&l.id!==t.activeModel&&n.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[#10b981]",children:[n.jsx(mi,{className:"w-3 h-3 shrink-0"}),n.jsxs("span",{children:["Recommended upgrade: ",n.jsx("span",{className:"font-mono",children:l.id})," (score ",l.score,"/100)",l.badges.length>0&&n.jsxs("span",{className:"ml-1 text-[#71717a]",children:["[",l.badges.join(", "),"]"]})]})]}),d&&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:[d.breakdown.capabilityScore,"/40"]})]}),n.jsxs("div",{children:["Fit: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[d.breakdown.specialistFit,"/40"]})]}),n.jsxs("div",{children:["Availability: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[d.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 Em(){const[t,e]=w.useState(null),[s,r]=w.useState(null),[i,o]=w.useState(null),[c,d]=w.useState(!1),[l,p]=w.useState(null),[g,u]=w.useState(null),f=w.useCallback(async()=>{p(null);try{const[L,v,A]=await Promise.all([ge("/api/telemetry/consent").then(m=>m.ok?m.json():Promise.reject(new Error(`consent ${m.status}`))),ge("/api/analytics/profile").then(m=>m.ok?m.json():null),ge("/api/telemetry/status").then(m=>m.ok?m.json():null)]);e(L),r(v),A!=null&&A.remote&&o(A.remote)}catch(L){p(L.message)}},[]);w.useEffect(()=>{const L=setInterval(()=>{ge("/api/telemetry/status").then(v=>v.ok?v.json():null).then(v=>{v!=null&&v.remote&&o(v.remote)}).catch(()=>{})},15e3);return()=>clearInterval(L)},[]),w.useEffect(()=>{f()},[f]);const x=w.useCallback(async L=>{d(!0),p(null);try{const v=await ge("/api/telemetry/consent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!v.ok)throw new Error(`save failed: ${v.status}`);const A=await v.json();e(m=>m?{...m,...A,consentedAt:A.enabled?new Date().toISOString():void 0}:null),u(Date.now()),setTimeout(()=>u(null),2e3)}catch(v){p(v.message)}finally{d(!1)}},[]),y=!!(t!=null&&t.enabled),E=!!(t!=null&&t.crashReports);return n.jsxs("div",{className:"w-full h-full overflow-auto bg-[#0a0a0f] text-[#e4e4e7] text-sm p-4",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[y?n.jsx(Gl,{className:"w-5 h-5 text-[#10b981]"}):n.jsx(Lr,{className:"w-5 h-5 text-[#71717a]"}),n.jsx("h3",{className:"font-semibold text-base",children:"Privacy & Telemetry"}),n.jsx("span",{className:`ml-2 text-[10px] px-2 py-0.5 rounded-full border ${y?"border-[#10b981]/40 bg-[#10b981]/10 text-[#10b981]":"border-[#3f3f46] bg-[#18181b] text-[#71717a]"}`,children:y?"ENABLED":"OFF"}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[g&&n.jsxs("span",{className:"text-[11px] text-[#10b981] flex items-center gap-1",children:[n.jsx(Il,{className:"w-3 h-3"})," Saved"]}),l&&n.jsxs("span",{className:"text-[11px] text-[#ef4444] flex items-center gap-1",children:[n.jsx(Dl,{className:"w-3 h-3"})," ",l]}),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(wn,{className:"w-3 h-3"})," Refresh"]})]})]}),n.jsx("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/70",children:n.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:y,disabled:c,onChange:L=>x({enabled:L.target.checked,crashReports:E}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"font-medium",children:"Send anonymous usage stats"}),n.jsx("div",{className:"text-xs text-[#a1a1aa] mt-1 leading-relaxed",children:"OS, Node version, CPU/GPU model + VRAM, RAM, TITAN version, and install method. A heartbeat every 5 minutes so we see uptime + concurrent-session counts. Never sends: prompts, file contents, credentials, IP address, or conversations."}),(t==null?void 0:t.consentedAt)&&n.jsxs("div",{className:"text-[10px] text-[#71717a] mt-2",children:["Consented ",n.jsx("span",{className:"font-mono",children:new Date(t.consentedAt).toLocaleString()}),t.consentedVersion&&n.jsxs(n.Fragment,{children:[" on TITAN v",n.jsx("span",{className:"font-mono",children:t.consentedVersion})]})]})]})]})}),n.jsx("div",{className:`mb-4 p-4 rounded-lg border transition-opacity ${y?"border-[#27272a]/60 bg-[#18181b]/70":"border-[#27272a]/30 bg-[#18181b]/30 opacity-60"}`,children:n.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:E,disabled:c||!y,onChange:L=>x({enabled:y,crashReports:L.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(gn,{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(ho,{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(ms,{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(gi,{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(gi,{className:"w-3 h-3"})," See the collector source"]})]})]})}const Nm=oe.lazy(()=>le(()=>import("./AutopilotPanel-CbohPtXW.js"),__vite__mapDeps([48,1,2,37,14])));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(Nm,{})})})}const Tm=oe.lazy(()=>le(()=>import("./WorkflowsPanel-3RYkFHyf.js"),__vite__mapDeps([49,1,2,37,14,3,4,10,11,12,24,27,42,16,28,20,50,51])));function Rm(){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(Tm,{})})})}const Am=oe.lazy(()=>le(()=>import("./LearningPanel-B4RIm_iQ.js"),__vite__mapDeps([52,1,2,37,14,24,51,53,54,55,27,22,56,31,23,43,12,57,32,26,21,39,58,20,59,60,61,62,63,64,11,65,66,15,40,19,67,28])));function Lm(){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(Am,{})})})}const Im=oe.lazy(()=>le(()=>import("./SelfImprovePanel-BxqWHXCU.js"),__vite__mapDeps([68,1,2,37,14,24,38,20,69,54,15,42,23,60,28])));function Dm(){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(Im,{})})})}const Mm=oe.lazy(()=>le(()=>import("./PersonasPanel-dR8VppcD.js"),__vite__mapDeps([70,1,2])));function Om(){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 Pm=oe.lazy(()=>le(()=>import("./PersonaProfilesPanel-DGtokXUu.js"),__vite__mapDeps([71,1,2,37,14,24,11,16,63,20])));function Wm(){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 Bm=oe.lazy(()=>le(()=>import("./DreamPanel-DIrtlk2K.js"),__vite__mapDeps([72,1,2,37,14,24])));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(Bm,{})})})}const Fm=oe.lazy(()=>le(()=>import("./HomelabPanel-BZvN4LPM.js"),__vite__mapDeps([73,1,2,37,14,74,75,4,24,20,21,56,19,31,38,40,17])));function $m(){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(Fm,{})})})}const zm=oe.lazy(()=>le(()=>import("./NvidiaPanel-4DlcQlyl.js"),__vite__mapDeps([76,1,2,37,14,24,43,38,66,32])));function Hm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(zm,{})})})}const Vm=oe.lazy(()=>le(()=>import("./FilesPanel-CaLPog2e.js"),__vite__mapDeps([77,1,2,27,24,14,78,20,12,28,43,41,11,22,55,56,31,23,51,57,32,26,21,39,58,59,60,61,62,63,64,65,66,15,40,19,67])));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(Vm,{})})})}const qm=oe.lazy(()=>le(()=>import("./LogsPanel-DbP3Mwnr.js"),__vite__mapDeps([79,1,2,37,14,24])));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(qm,{})})})}const Km=oe.lazy(()=>le(()=>import("./TelemetryPanel-D4PXsd-X.js"),__vite__mapDeps([80,1,2,74,20,18,19,56])));function Jm(){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(Km,{})})})}const Xm=oe.lazy(()=>le(()=>import("./SkillsPanel-CA415CT8.js"),__vite__mapDeps([81,1,2,37,14,32,28,41])));function Qm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Xm,{})})})}const Zm=oe.lazy(()=>le(()=>import("./McpPanel-BmNUFozc.js"),__vite__mapDeps([82,1,2,37,14,24,27,56,83,61,28])));function eg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Zm,{})})})}const tg=oe.lazy(()=>le(()=>import("./IntegrationsPanel-B4TyR6jC.js"),__vite__mapDeps([84,1,2,37,14,38,83,43])));function sg(){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(tg,{})})})}const ng=oe.lazy(()=>le(()=>import("./ChannelsPanel-DS21E-Iz.js"),__vite__mapDeps([85,1,2,37,14,24,38,43])));function rg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(ng,{})})})}const ig=oe.lazy(()=>le(()=>import("./MeshPanel-Bf-4brXL.js"),__vite__mapDeps([86,1,2,87,37,14,24,65])));function og(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(ig,{})})})}const ag=oe.lazy(()=>le(()=>import("./MemoryWikiPanel-DdvCAZHa.js"),__vite__mapDeps([88,1,2,37,14,78,67,20,32,51])));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(ag,{})})})}const cg=oe.lazy(()=>le(()=>import("./AutoresearchPanel-DCwiQ2v2.js"),__vite__mapDeps([89,1,2,37,14,42,16,24,58,69,54,20])));function dg(){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 ug=oe.lazy(()=>le(()=>import("./SelfProposalsPanel-CuC94vdx.js"),__vite__mapDeps([90,1,2,37,14,20,55,27,22,56,31,23,51,43,12,57,32,26,21,39,58,59,60,61,62,63,24,64,11,65,66,15,40,19,67,28])));function hg(){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(ug,{})})})}const fg=oe.lazy(()=>le(()=>import("./OverviewPanel-DK8uuq4D.js"),__vite__mapDeps([91,1,2,74,37,14,75,4,20,21,56,92])));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(fg,{})})})}const mg=oe.lazy(()=>le(()=>import("./SessionsPanel-CQ8qvzp7.js"),__vite__mapDeps([93,1,2,37,14,3,4,87,10,11,12,32,28])));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(mg,{})})})}const yg=oe.lazy(()=>le(()=>import("./WatchView-BCgLVfiV.js"),__vite__mapDeps([94,1,2,9])));function bg(){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(yg,{})})})}const xg=oe.lazy(()=>le(()=>import("./BackupPanel-DAy9G7Wt.js"),__vite__mapDeps([95,1,2,37,14,27,24,59,38])));function wg(){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(xg,{})})})}const vg=oe.lazy(()=>le(()=>import("./TrainingPanel-Dmbd1rJ-.js"),__vite__mapDeps([96,1,2,37,14,24,41])));function _g(){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(vg,{})})})}const kg=oe.lazy(()=>le(()=>import("./RecipesPanel-D3Zs2wxr.js"),__vite__mapDeps([97,1,2,37,14,24,51,42,28])));function Sg(){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(kg,{})})})}const jg=oe.lazy(()=>le(()=>import("./VramPanel-CPICbZ2s.js"),__vite__mapDeps([98,1,2,37,14,24])));function Eg(){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 Ng=oe.lazy(()=>le(()=>import("./TeamsPanel-C_Vu6vnY.js"),__vite__mapDeps([99,1,2,37,14,24,28])));function Cg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Ng,{})})})}const Tg=oe.lazy(()=>le(()=>import("./CronPanel-kEZK3gpx.js"),__vite__mapDeps([100,1,2,37,14,24,20,50,28])));function Rg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Tg,{})})})}const Ag=oe.lazy(()=>le(()=>import("./CheckpointsPanel-9-l_8GdG.js"),__vite__mapDeps([101,1,2,37,14,24,43,28])));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(Ag,{})})})}const Ig=oe.lazy(()=>le(()=>import("./OrganismPanel-C2LYDPrn.js"),__vite__mapDeps([102,1,2,37,14,24,38])));function Dg(){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 Mg=oe.lazy(()=>le(()=>import("./FleetPanel-BtlaV6pH.js"),__vite__mapDeps([103,1,2,37,14,24,60])));function Og(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Mg,{})})})}const Pg=oe.lazy(()=>le(()=>import("./BrowserPanel-D6UaSxap.js"),__vite__mapDeps([104,1,2,37,14])));function Wg(){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 Bg=oe.lazy(()=>le(()=>import("./EvalPanel-CDG-njyj.js"),__vite__mapDeps([105,1,2,37,14,24,42])));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(Bg,{})})})}function Fg(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 $g(t){const e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e>=0?t.slice(e+1):t}function zg(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(""),[c,d]=w.useState(null),[l,p]=w.useState(""),[g,u]=w.useState(!1),[f,x]=w.useState(null),[y,E]=w.useState(null),[L,v]=w.useState(null),A=w.useCallback(async()=>{r(!0),x(null);try{const C=await ge("/api/time-travel/checkpoints?limit=100");if(!C.ok)throw new Error(`${C.status} ${C.statusText}`);const D=await C.json();e(D.checkpoints||[])}catch(C){x(C.message||"Failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{A()},[A]);const m=w.useCallback((C,D)=>{v({kind:C,message:D}),setTimeout(()=>v(null),4e3)},[]),k=w.useCallback(async C=>{d(C),p(""),u(!0);try{const D=await ge(`/api/time-travel/diff/${encodeURIComponent(C)}`);if(!D.ok)throw new Error(`${D.status} ${D.statusText}`);const j=await D.json();p(j.diff||"(no diff returned)")}catch(D){p(`Failed to load diff: ${D.message}`)}finally{u(!1)}},[]),_=w.useCallback(C=>{E(C)},[]),T=w.useCallback(async()=>{if(!y)return;const C=y;E(null);try{const D=await ge(`/api/time-travel/restore/${encodeURIComponent(C)}`,{method:"POST"});if(!D.ok)throw new Error(`${D.status} ${D.statusText}`);const j=await D.json();j.ok?(m("ok",j.message||`Restored to ${C.slice(0,8)}.`),A()):m("err",j.message||"Restore failed.")}catch(D){m("err",D.message||"Restore failed.")}},[y,A,m]),S=w.useMemo(()=>{const C=i.trim().toLowerCase();return C?t.filter(D=>D.filePath.toLowerCase().includes(C)||D.toolName.toLowerCase().includes(C)||D.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:A,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"})]})]}),L&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,background:L.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${L.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:L.kind==="ok"?"#86efac":"#fca5a5",fontSize:11},children:L.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…"}):S.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."}):S.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:Fg(C.timestamp)})]}),n.jsx("div",{style:{fontSize:12,color:"#e2e8f5",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:C.filePath,children:$g(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:D=>{D.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?g?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:(l||"").split(`
994
- `).map((C,D)=>{let j="rgba(255,255,255,0.7)";return C.startsWith("+")&&!C.startsWith("+++")?j="#86efac":C.startsWith("-")&&!C.startsWith("---")?j="#fca5a5":C.startsWith("@@")?j="#a5b4fc":(C.startsWith("diff")||C.startsWith("index")||C.startsWith("+++")||C.startsWith("---"))&&(j="rgba(255,255,255,0.45)"),n.jsx("div",{style:{color:j},children:C||" "},D)})}):n.jsx("div",{style:{color:"rgba(255,255,255,0.4)"},children:"Select a checkpoint on the left to see its diff vs the current file."})})]}),y&&n.jsx("div",{onClick:()=>E(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:y.slice(0,8)}),". A NEW checkpoint of the current state is taken first, so you can always come back."]}),n.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[n.jsx("button",{onClick:()=>E(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 Zi=5e3,eo={planning:"#a5b4fc",delegating:"#60a5fa",observing:"#22d3ee",iterating:"#f59e0b",verifying:"#a78bfa",reporting:"#34d399",blocked:"#facc15",escalated:"#fb7185",done:"#34d399",failed:"#ef4444",cancelled:"#737373"};function Hg(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 Vg(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function Gg(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(null),[c,d]=w.useState(!1),[l,p]=w.useState(""),[g,u]=w.useState(2),[f,x]=w.useState(!1),[y,E]=w.useState(null),L=w.useCallback(async()=>{try{const _=await ge("/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(()=>{L();const _=setInterval(L,Zi);return()=>clearInterval(_)},[L]);const v=w.useCallback((_,T)=>{E({kind:_,message:T}),setTimeout(()=>E(null),5e3)},[]),A=w.useCallback(async()=>{var T;const _=l.trim();if(_.length<10){v("err","Describe the mission (>=10 chars).");return}x(!0);try{const S=await ge("/api/mission/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:_,budgetUsd:g})});if(!S.ok)throw new Error(`${S.status} ${S.statusText}`);const C=await S.json();v("ok",C.message||`Mission "${((T=C.goal)==null?void 0:T.title)??"?"}" launched.`),p(""),d(!1),L()}catch(S){v("err",S.message||"launch failed")}finally{x(!1)}},[l,g,L,v]),m=w.useCallback(async _=>{try{const T=await ge(`/api/mission/${encodeURIComponent(_)}/cancel`,{method:"POST"});if(!T.ok)throw new Error(`${T.status} ${T.statusText}`);v("ok","Mission marked for cancellation."),L()}catch(T){v("err",T.message||"cancel failed")}},[L,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,S)=>(_[T.phase]??99)-(_[S.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 ",Zi/1e3,"s"]})]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("button",{onClick:()=>d(_=>!_),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:L,title:"Refresh",style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid rgba(255,255,255,0.1)",background:"rgba(255,255,255,0.04)",color:"#e2e8f5",cursor:"pointer"},children:"↻"})]})]}),y&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,fontSize:11,background:y.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${y.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:y.kind==="ok"?"#86efac":"#fca5a5"},children:y.message}),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:l,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:g,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:A,disabled:f||l.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=eo[_.phase]??"#94a3b8",S=_.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:()=>m(_.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 (",S,"%)"]}),n.jsx("span",{children:"·"}),n.jsx("span",{children:Vg(_.budget.costUsd)}),n.jsx("span",{children:"·"}),n.jsx("span",{children:Hg(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,D)=>n.jsxs("div",{style:{display:"flex",gap:6,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n.jsx("span",{style:{color:eo[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??""})]},D))})]},_.goalId)})]})]})}const qg=6e4,Yg=[{label:"6h",hours:6},{label:"24h",hours:24},{label:"7d",hours:168}];function Kg(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function Jg(t){return t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(1)}k`:`${(t/1e6).toFixed(2)}M`}function Xg(){const[t,e]=w.useState(24),[s,r]=w.useState(null),[i,o]=w.useState(!0),[c,d]=w.useState(null),l=w.useCallback(async()=>{o(!0);try{const p=await ge(`/api/missions/digest?hours=${t}`);if(!p.ok)throw new Error(`${p.status} ${p.statusText}`);const g=await p.json();r(g),d(null)}catch(p){d(p.message||"failed")}finally{o(!1)}},[t]);return w.useEffect(()=>{l();const p=setInterval(l,qg);return()=>clearInterval(p)},[l]),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:Yg.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(Us,{label:"Done",value:s.stats.completed,color:"#34d399"}),n.jsx(Us,{label:"Failed",value:s.stats.failed,color:s.stats.failed>0?"#fca5a5":"rgba(255,255,255,0.5)"}),n.jsx(Us,{label:"Active",value:s.stats.active,color:"#60a5fa"}),n.jsx(Us,{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:Kg(s.stats.totalCostUsd)})]}),n.jsxs("span",{children:["Tokens: ",n.jsx("strong",{style:{color:"#e2e8f5"},children:Jg(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,g)=>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]},g))]})]})]})]})}function Us({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 Fs={pending:"#737373",running:"#60a5fa",done:"#34d399",failed:"#ef4444",skipped:"#a78bfa"},to=6e3,St=180,ar=64,so=96,$s=24;function Qg(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 d=(c.dependsOn??[]).filter(p=>s.has(p)),l=d.length===0?0:Math.max(...d.map(p=>r(p,o)))+1;return o.delete(i),e.set(i,l),l};for(const i of t)r(i.id,new Set);return e}function Zg(){const[t,e]=w.useState([]),[s,r]=w.useState(null),[i,o]=w.useState(null),[c,d]=w.useState(null),[l,p]=w.useState(null),g=w.useCallback(async()=>{try{const v=await ge("/api/missions/active");if(!v.ok)throw new Error(`${v.status} ${v.statusText}`);const m=(await v.json()).missions||[];e(m),!s&&m.length>0&&r(m[0].goalId)}catch(v){d(v.message||"failed")}},[s]),u=w.useCallback(async v=>{try{const A=await ge(`/api/mission/${encodeURIComponent(v)}`);if(!A.ok)throw new Error(`${A.status} ${A.statusText}`);const m=await A.json();o(m),d(null)}catch(A){d(A.message||"failed to load mission"),o(null)}},[]);w.useEffect(()=>{g();const v=setInterval(g,to);return()=>clearInterval(v)},[g]),w.useEffect(()=>{if(!s){o(null);return}u(s);const v=setInterval(()=>u(s),to);return()=>clearInterval(v)},[s,u]);const{layout:f,edges:x,viewBox:y}=w.useMemo(()=>{if(!(i!=null&&i.goal.subtasks))return{layout:[],edges:[],viewBox:"0 0 600 200"};const v=i.goal.subtasks,A=Qg(v),m=new Map;for(const R of v){const P=A.get(R.id)??0;m.has(P)||m.set(P,[]),m.get(P).push(R)}const k=Array.from(m.keys()).sort((R,P)=>R-P),_=Math.max(...Array.from(m.values()).map(R=>R.length),1),T=Math.max(640,_*(St+$s)+$s),S=k.length*so+ar+40,C=new Map,D=[];for(const R of k){const P=m.get(R),B=P.length*St+(P.length-1)*$s,z=(T-B)/2,J=R*so+20;for(let H=0;H<P.length;H++){const K=z+H*(St+$s);C.set(P[H].id,{x:K,y:J}),D.push({...P[H],x:K,y:J})}}const j=[];for(const R of v){const P=C.get(R.id);if(P)for(const B of R.dependsOn??[]){const z=C.get(B);z&&j.push({from:B,to:R.id,x1:z.x+St/2,y1:z.y+ar,x2:P.x+St/2,y2:P.y})}}return{layout:D,edges:j,viewBox:`0 0 ${T} ${S}`}},[i]),E=w.useMemo(()=>new Map(((i==null?void 0:i.goal.subtasks)??[]).map(v=>[v.id,v])),[i]),L=l?E.get(l):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:y,style:{width:"100%",height:"auto"},role:"img","aria-label":"Mission subtask DAG",children:[n.jsx("defs",{children:n.jsx("marker",{id:"mg-arrow",viewBox:"0 0 10 10",refX:"10",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:n.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(255,255,255,0.35)"})})}),x.map((v,A)=>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-${A}`)),f.map(v=>{var _;const A=((_=i.driver)==null?void 0:_.currentSubtaskId)===v.id,m=Fs[v.status],k=l===v.id;return n.jsxs("g",{transform:`translate(${v.x}, ${v.y})`,onClick:()=>p(v.id),style:{cursor:"pointer"},children:[n.jsx("rect",{width:St,height:ar,rx:"8",fill:A?`${m}22`:"rgba(255,255,255,0.04)",stroke:k||A?m:`${m}55`,strokeWidth:A||k?2:1}),n.jsx("circle",{cx:14,cy:14,r:"5",fill:m,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?"…":""]}),A&&n.jsx("text",{x:St-8,y:14,fontSize:"8",fill:m,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."})}),L&&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:L.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:`${Fs[L.status]}22`,border:`1px solid ${Fs[L.status]}55`,color:Fs[L.status]},children:L.status}),L.retries>0&&n.jsxs("span",{style:{marginLeft:6,color:"rgba(255,255,255,0.5)"},children:[L.retries," retries"]})]}),n.jsx("div",{style:{color:"rgba(255,255,255,0.85)",lineHeight:1.5,marginBottom:10},children:L.description}),L.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:"})," ",L.dependsOn.map(v=>{var A;return((A=E.get(v))==null?void 0:A.title)||v}).join(", ")]}),L.completedAt&&n.jsxs("div",{style:{color:"rgba(255,255,255,0.45)",fontSize:10},children:["Completed: ",new Date(L.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 ey(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(null),c=async()=>{try{const d=await fetch("/api/agents");if(!d.ok)throw new Error(`HTTP ${d.status}`);const l=await d.json();e(Array.isArray(l)?l:l.agents||[]),o(null)}catch(d){o(d.message)}finally{r(!1)}};return w.useEffect(()=>{c();const d=setInterval(c,1e4);return()=>clearInterval(d)},[]),s?n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(oo,{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(gn,{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(d=>n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx(Dr,{className:`w-3.5 h-3.5 ${d.status==="busy"?"text-[#f59e0b]":d.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:d.name}),n.jsxs("div",{className:"text-[10px] text-[#52525b] truncate",children:[d.role,d.model?` · ${d.model}`:""]})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${d.status==="busy"?"bg-[#f59e0b]/10 text-[#f59e0b]":d.status==="error"?"bg-red-400/10 text-red-400":"bg-[#6366f1]/10 text-[#818cf8]"}`,children:d.status})]},d.id))})})}function ty(){const[t,e]=w.useState(null),[s,r]=w.useState(!0),i=async()=>{try{const[c,d]=await Promise.allSettled([fetch("/api/health").then(g=>g.ok?g.json():null),fetch("/ollama/api/tags").then(g=>g.ok)]),l=c.status==="fulfilled"&&c.value,p=d.status==="fulfilled"&&d.value;e({gateway:l,ollama:p,version:(l==null?void 0:l.version)||"unknown",uptime:(l==null?void 0:l.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(oo,{className:"w-4 h-4 text-[#6366f1] animate-spin"})});const o=c=>{const d=Math.floor(c/3600),l=Math.floor(c%3600/60);return`${d}h ${l}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(Ml,{className:"w-3.5 h-3.5 text-emerald-400"}):n.jsx(ql,{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(Yt,{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 zs({label:t,value:e,icon:s,color:r,unknown:i}){const o=Math.max(0,Math.min(100,Math.round(e)));return n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[s,n.jsx("span",{className:"text-[10px] text-[#52525b] uppercase tracking-wider",children:t})]}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa] font-mono",children:i?"—":`${o}%`})]}),n.jsx("div",{className:"h-1.5 rounded-full bg-[#27272a] overflow-hidden",children:n.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:i?"0%":`${o}%`,backgroundColor:r}})})]})}function sy(){const[t,e]=w.useState({cpu:0,memory:0,disk:0,load:0,loaded:!1,error:null,diskAvailable:!0});w.useEffect(()=>{let r=!1;async function i(){try{const c=await ge("/api/stats");if(!c.ok){const y=`HTTP ${c.status}`;r||e(E=>({...E,loaded:!0,error:y}));return}const d=await c.json();if(r)return;const l=d.host;if(!l){e(y=>({...y,loaded:!0,error:"no host metrics"}));return}const p=typeof l.cpuPercent=="number"?l.cpuPercent:0,g=typeof l.memPercent=="number"?l.memPercent:0,u=typeof l.diskPercent=="number"?l.diskPercent:0,f=l.cores||1,x=typeof l.loadAvg1=="number"?Math.min(100,l.loadAvg1/f*100):0;e({cpu:p,memory:g,disk:u,load:x,loaded:!0,error:null,diskAvailable:!l.diskError})}catch(c){r||e(d=>({...d,loaded:!0,error:c.message}))}}i();const o=setInterval(i,3e3);return()=>{r=!0,clearInterval(o)}},[]);const s=!t.loaded||!!t.error;return n.jsxs("div",{className:"w-full h-full p-3 overflow-auto",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx(zs,{label:"CPU",value:t.cpu,icon:n.jsx(Rr,{className:"w-3 h-3 text-[#6366f1]"}),color:"#6366f1",unknown:s}),n.jsx(zs,{label:"Memory",value:t.memory,icon:n.jsx(Ol,{className:"w-3 h-3 text-[#a78bfa]"}),color:"#a78bfa",unknown:s}),n.jsx(zs,{label:"Disk",value:t.disk,icon:n.jsx(Pl,{className:"w-3 h-3 text-[#10b981]"}),color:"#10b981",unknown:s||!t.diskAvailable}),n.jsx(zs,{label:"Load",value:t.load,icon:n.jsx(Yt,{className:"w-3 h-3 text-[#f59e0b]"}),color:"#f59e0b",unknown:s})]}),t.error&&n.jsx("div",{className:"mt-2 text-[10px] text-[#ef4444]/80",children:t.error})]})}const ny=[{label:"Nav",source:"system:nav",w:3,h:4,icon:n.jsx(ec,{className:"w-3.5 h-3.5"})},{label:"Agents",source:"system:agents",w:3,h:4,icon:n.jsx(Dr,{className:"w-3.5 h-3.5"})},{label:"Health",source:"system:health",w:3,h:3,icon:n.jsx(Yt,{className:"w-3.5 h-3.5"})},{label:"Stats",source:"system:stats",w:3,h:4,icon:n.jsx(oc,{className:"w-3.5 h-3.5"})},{label:"Chat",source:"system:chat",w:4,h:5,icon:n.jsx(xn,{className:"w-3.5 h-3.5"})},{label:"Files",source:"system:files",w:4,h:6,icon:n.jsx(yn,{className:"w-3.5 h-3.5"})},{label:"Skills",source:"system:tools",w:5,h:4,icon:n.jsx(mn,{className:"w-3.5 h-3.5"})},{label:"Soma",source:"system:soma",w:6,h:6,icon:n.jsx(Wl,{className:"w-3.5 h-3.5"})},{label:"Intel",source:"system:intelligence",w:6,h:5,icon:n.jsx(xt,{className:"w-3.5 h-3.5"})},{label:"Infra",source:"system:infra",w:6,h:4,icon:n.jsx(Ir,{className:"w-3.5 h-3.5"})},{label:"Tools",source:"system:tools",w:5,h:4,icon:n.jsx(Tr,{className:"w-3.5 h-3.5"})},{label:"Settings",source:"system:settings",w:4,h:6,icon:n.jsx(Cr,{className:"w-3.5 h-3.5"})},{label:"Wiki",source:"system:memory-wiki",w:5,h:5,icon:n.jsx(ps,{className:"w-3.5 h-3.5"})},{label:"Research",source:"system:autoresearch",w:5,h:5,icon:n.jsx(po,{className:"w-3.5 h-3.5"})},{label:"Proposals",source:"system:self-proposals",w:5,h:5,icon:n.jsx(bo,{className:"w-3.5 h-3.5"})},{label:"Overview",source:"system:overview",w:5,h:4,icon:n.jsx(ro,{className:"w-3.5 h-3.5"})},{label:"Sessions",source:"system:sessions",w:5,h:4,icon:n.jsx(ms,{className:"w-3.5 h-3.5"})},{label:"Watch",source:"system:watch",w:6,h:5,icon:n.jsx(Yt,{className:"w-3.5 h-3.5"})},{label:"Backup",source:"system:backup",w:5,h:5,icon:n.jsx(mo,{className:"w-3.5 h-3.5"})},{label:"Training",source:"system:training",w:5,h:5,icon:n.jsx(xt,{className:"w-3.5 h-3.5"})},{label:"Recipes",source:"system:recipes",w:5,h:5,icon:n.jsx(ps,{className:"w-3.5 h-3.5"})},{label:"VRAM",source:"system:vram",w:5,h:5,icon:n.jsx(Rr,{className:"w-3.5 h-3.5"})},{label:"Teams",source:"system:teams",w:5,h:5,icon:n.jsx(Ar,{className:"w-3.5 h-3.5"})},{label:"Cron",source:"system:cron",w:5,h:5,icon:n.jsx(ms,{className:"w-3.5 h-3.5"})},{label:"Checkpoints",source:"system:checkpoints",w:5,h:5,icon:n.jsx(bn,{className:"w-3.5 h-3.5"})},{label:"Organism",source:"system:organism",w:5,h:5,icon:n.jsx(Lr,{className:"w-3.5 h-3.5"})},{label:"Fleet",source:"system:fleet",w:5,h:5,icon:n.jsx(go,{className:"w-3.5 h-3.5"})},{label:"Browser",source:"system:browser",w:5,h:5,icon:n.jsx(io,{className:"w-3.5 h-3.5"})},{label:"Eval",source:"system:eval",w:5,h:5,icon:n.jsx(yo,{className:"w-3.5 h-3.5"})}];function ry(){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:ny.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 iy extends oe.Component{componentDidCatch(e){this.props.onError(e.message)}render(){return this.props.children}}function oy({name:t,children:e}){const[s,r]=oe.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(iy,{onError:r,children:e})}const ay=oe.lazy(()=>le(()=>import("./legacy-dHWI7k8P.js"),__vite__mapDeps([106,1,2,4])).then(t=>({default:t.Responsive}))),ly={"system:nav":$f,"system:chat":fl,"system:cmd":_l,"system:soma":kl,"system:command-post":rm,"system:intelligence":om,"system:memory-graph":lm,"system:voice":cm,"system:infra":um,"system:tools":fm,"system:settings":mm,"system:files":gm,"system:settings-general":bm,"system:settings-security":wm,"system:settings-audit":_m,"system:settings-specialists":Sm,"system:settings-privacy":Em,"system:intelligence-autopilot":Cm,"system:intelligence-workflows":Rm,"system:intelligence-learning":Lm,"system:intelligence-self-improve":Dm,"system:intelligence-personas":Om,"system:intelligence-persona-profiles":Wm,"system:intelligence-dream":Um,"system:infra-homelab":$m,"system:infra-gpu":Hm,"system:infra-files":Gm,"system:infra-logs":Ym,"system:infra-telemetry":Jm,"system:tools-skills":Qm,"system:tools-mcp":eg,"system:tools-integrations":sg,"system:tools-channels":rg,"system:tools-mesh":og,"system:agents":ey,"system:health":ty,"system:stats":sy,"system:quick-links":ry,"system:memory-wiki":lg,"system:autoresearch":dg,"system:self-proposals":hg,"system:overview":pg,"system:sessions":gg,"system:watch":bg,"system:backup":wg,"system:training":_g,"system:recipes":Sg,"system:vram":Eg,"system:teams":Cg,"system:cron":Rg,"system:checkpoints":Lg,"system:organism":Dg,"system:fleet":Og,"system:browser":Wg,"system:eval":Ug,"system:time-travel":zg,"system:mission-driver":Gg,"system:daily-digest":Xg,"system:mission-graph":Zg},cy={lg:12,md:10,sm:6,xs:4,xxs:2},dy=60,uy={lg:1200,md:996,sm:768,xs:480,xxs:0},hy=[12,12],fy=["se","sw","ne","nw","e","w","n","s"],py=[{source:"system:nav",name:"Nav",w:3,h:4,label:"Navigation",icon:pc},{source:"system:agents",name:"Agents",w:3,h:4,label:"Agents",icon:Dr},{source:"system:health",name:"Health",w:3,h:3,label:"Health",icon:cc},{source:"system:stats",name:"Stats",w:3,h:4,label:"Stats",icon:Yl},{source:"system:quick-links",name:"Quick Links",w:3,h:4,label:"Links",icon:Kl},{source:"system:chat",name:"Chat",w:4,h:5,label:"Chat",icon:xn}],Sl=oe.forwardRef(({widget:t,space:e,onRemove:s,style:r,className:i,onMouseDown:o,onMouseUp:c,onTouchStart:d,onTouchEnd:l,children:p},g)=>{const u=w.useCallback(()=>s(t.id),[t.id,s]);return n.jsxs("div",{ref:g,style:r,className:i,onMouseDown:o,onMouseUp:c,onTouchStart:d,onTouchEnd:l,children:[n.jsx(yy,{widget:t,space:e,onRemove:u}),p]})});Sl.displayName="MemoWidgetItem";const my=oe.memo(Sl);function gy({widget:t,space:e,onRemove:s}){const r=w.useRef(null),i=w.useRef(null),o=w.useRef(e),[c,d]=w.useState(null),[l,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()===""){d("Empty widget — no source code"),p(!1);return}p(!0),d(null),i.current=new cl(r.current,{onLog:u=>console.log(`[Widget ${t.id}]`,u)}),i.current.setMessageHandler(u=>{var x,y,E,L;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 A=Number.isFinite(v.w)?v.w:4,m=Number.isFinite(v.h)?v.h:4,k=Number.isFinite(v.x)&&Number.isFinite(v.y)?{x:v.x,y:v.y}:Ys(f.widgets||[],A,m);try{const _=ke.addWidget(f.id,{name:v.name||"Agent Widget",format:v.format||"react",source:v.source||"",x:k.x,y:k.y,w:A,h:m});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"&&((y=u.payload)==null?void 0:y.action)==="updateWidget"){const{id:v,patch:A}=u.payload;return v?(ke.updateWidget(f.id,v,A||{}),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"&&((E=u.payload)==null?void 0:E.action)==="listWidgets")return{ok:!0,widgets:f.widgets||[]};if(u.type==="canvas"&&((L=u.payload)==null?void 0:L.action)==="removeWidget"){const v=u.payload.id;return v?(ke.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 g=setTimeout(()=>{p(!1),d("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(g),p(!1)}).catch(u=>{clearTimeout(g),p(!1),d(String(u))}),()=>{var u;clearTimeout(g),(u=i.current)==null||u.destroy()}},[t.format,t.source,t.id]),t.format==="system"){const g=ly[t.source];return g?n.jsxs("div",{className:"w-full h-full rounded-xl overflow-hidden flex flex-col group transition-colors shadow-md",style:{background:"var(--color-desk-widget-bg)",border:"1px solid var(--color-desk-border)",boxShadow:"0 4px 12px var(--theme-shadow, rgba(60,40,15,0.15))"},children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b panel-drag-handle cursor-move",style:{borderColor:"var(--color-desk-border-light)",background:"var(--theme-leather, rgba(58,37,24,0.05))"},children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--color-desk-accent)"},children:t.name}),n.jsx("button",{onClick:s,className:"opacity-0 group-hover:opacity-100 text-xs px-1 transition-opacity",style:{color:"var(--color-desk-text-muted)"},children:"×"})]}),n.jsx("div",{className:"flex-1 overflow-auto relative",children:n.jsx(oy,{name:t.name,children:n.jsx(g,{space:e,widget:t,onRemove:s})})})]}):n.jsxs("div",{className:"w-full h-full flex items-center justify-center text-xs text-red-400",children:["Unknown system widget: ",t.source]})}return n.jsxs("div",{className:"w-full h-full rounded-xl overflow-hidden flex flex-col shadow-md",style:{background:"var(--color-desk-widget-bg)",border:"1px solid var(--color-desk-border)",boxShadow:"0 4px 12px var(--theme-shadow, rgba(60,40,15,0.15))"},children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b panel-drag-handle cursor-move",style:{borderColor:"var(--color-desk-border-light)",background:"var(--theme-leather, rgba(58,37,24,0.05))"},children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--color-desk-accent)"},children:t.name}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("button",{onClick:g=>{g.stopPropagation(),window.dispatchEvent(new CustomEvent("titan:widget:edit",{detail:{spaceId:e.id,widgetId:t.id}}))},onMouseDown:g=>g.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}),l&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-xs",style:{background:"var(--theme-paper, rgba(253,246,227,0.85))",color:"var(--color-desk-text-muted)",fontFamily:"var(--theme-font-display, 'Georgia', serif)"},children:n.jsx("span",{className:"animate-pulse",children:"Loading widget…"})})]})})]})}const yy=oe.memo(gy);function Ft({label:t,onClick:e,children:s,variant:r="default",disabled:i}){return n.jsx("button",{type:"button",onClick:e,disabled:i,className:`titan-canvas-icon-button titan-canvas-icon-button--${r}`,title:t,"aria-label":t,children:s})}function by(){const{spaceId:t}=Bl(),e=no(),[s,r]=w.useState(null),[i]=w.useState(!1),[o,c]=w.useState(!1),[d,l]=w.useState(null),[p,g]=w.useState(!1),[u,f]=w.useState(!1),[x,y]=w.useState(!1),[E,L]=w.useState(1200),v=w.useRef(null),A=w.useRef(null),{info:m,triggerUpdate:k,waitForReload:_}=Pf(),[T,S]=w.useState(!1);w.useEffect(()=>{const $=t||"home",F=ke.get($);F?r(F):e("/space/home",{replace:!0})},[t,e]),w.useEffect(()=>{const $=()=>{const se=A.current;if(!se)return null;const q=new ResizeObserver(te=>{for(const Q of te)L(Q.contentRect.width)});return q.observe(se),L(se.getBoundingClientRect().width||1200),q};let F=$();const V=setInterval(()=>{F||(F=$()),F&&clearInterval(V)},200);return()=>{F==null||F.disconnect(),clearInterval(V)}},[s==null?void 0:s.id]),w.useEffect(()=>{const $=F=>{(F.metaKey||F.ctrlKey)&&F.key==="k"&&(F.preventDefault(),f(V=>!V)),(F.metaKey||F.ctrlKey)&&F.key==="j"&&(F.preventDefault(),window.dispatchEvent(new CustomEvent("titan:chat:toggle")))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[]),Wf([{key:"?",action:()=>y(!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 C=w.useCallback(()=>{},[]),D=w.useRef(null),j=w.useRef(null),R=w.useCallback($=>{s&&(j.current=$,D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{const F=j.current;!F||!s||(ke.updateLayout(s.id,F.map(V=>({i:V.i,x:V.x,y:V.y,w:V.w,h:V.h}))),j.current=null,D.current=null)},50))},[s]),P=w.useCallback($=>{var se;if(!s)return;const F=(se=s.widgets)==null?void 0:se.find(q=>q.id===$);Wn("canvas_panel_removed",{widgetId:$,format:F==null?void 0:F.format,source:F==null?void 0:F.source}),ke.removeWidget(s.id,$);const V=Array.isArray(s.widgets)?s.widgets:[];r({...s,widgets:V.filter(q=>q.id!==$)})},[s]),B=w.useCallback($=>{if(!s)return;const F=ke.addWidget(s.id,$),V=Array.isArray(s.widgets)?s.widgets:[];return r({...s,widgets:[...V,F]}),Wn($.format==="system"?"canvas_system_panel_created":"canvas_panel_created",{source:$.source,name:$.name,format:$.format}),F},[s]),z=w.useCallback(($,F)=>{if(!s||!Array.isArray(s.widgets)||s.widgets.length===0)return{x:0,y:0};const V=12,se=new Set;for(const q of s.widgets)for(let te=0;te<q.w;te++)for(let Q=0;Q<q.h;Q++)se.add(`${q.x+te},${q.y+Q}`);for(let q=0;q<200;q++)for(let te=0;te<=V-$;te++){let Q=!0;for(let be=0;be<$;be++){for(let Ce=0;Ce<F;Ce++)if(se.has(`${te+be},${q+Ce}`)){Q=!1;break}if(!Q)break}if(Q)return{x:te,y:q}}return{x:0,y:0}},[s]),J=w.useCallback(($,F,V=4,se=4)=>{const q=z(V,se);B({name:F,format:"system",source:$,x:q.x,y:q.y,w:V,h:se})},[B,z]);w.useEffect(()=>{const $=F=>{const V=F.detail;if(console.log("[TitanCanvas] titan:space:refresh received:",V),!!s&&(V==null?void 0:V.spaceId)===s.id){const se=ke.get(s.id);se&&(console.log("[TitanCanvas] Refreshing space, widget count:",se.widgets.length),r(se))}};return window.addEventListener("titan:space:refresh",$),()=>window.removeEventListener("titan:space:refresh",$)},[s]),w.useEffect(()=>{const $=F=>{const V=F.detail;if(s&&V!=null&&V.source){const se=Number.isFinite(V.w)?V.w:4,q=Number.isFinite(V.h)?V.h:4,te=typeof V.name=="string"&&V.name.trim()?V.name.trim():String(V.source).replace("system:","").replace(/-/g," "),Q=V.format==="react"||V.format==="vanilla"||V.format==="html"||V.format==="system"?V.format:String(V.source).startsWith("system:")?"system":"react",be=z(se,q);B({name:te,format:Q,source:String(V.source),x:be.x,y:be.y,w:se,h:q})}};return window.addEventListener("titan:widget:add",$),()=>window.removeEventListener("titan:widget:add",$)},[s,B,z]),w.useEffect(()=>{const $=F=>{const V=F.detail;s&&(V==null?void 0:V.spaceId)===s.id&&typeof(V==null?void 0:V.widgetId)=="string"&&l(V.widgetId)};return window.addEventListener("titan:widget:edit",$),()=>window.removeEventListener("titan:widget:edit",$)},[s]),w.useEffect(()=>s?ke.observe(s.id,F=>{console.log("[TitanCanvas] CRDT observer fired, widgets:",F.length),r(V=>V&&{...V,widgets:F})}):void 0,[s==null?void 0:s.id]);const H=w.useMemo(()=>{const $=s==null?void 0:s.widgets;return Array.isArray($)?$.filter(Boolean):[]},[s]),K=w.useMemo(()=>H.map(($,F)=>({i:$.id,x:Number.isFinite($.x)?$.x:F%3*4,y:Number.isFinite($.y)?$.y:Math.floor(F/3)*4,w:Number.isFinite($.w)?$.w:4,h:Number.isFinite($.h)?$.h:4,minW:2,minH:2,maxW:12,maxH:40})),[H]);return s?n.jsxs("div",{className:"h-full w-full flex",children:[n.jsx(Bp,{}),n.jsxs("div",{ref:v,className:"flex-1 relative overflow-auto",children:[n.jsx("style",{children:`
995
- .titan-canvas-grid .react-grid-item > .react-resizable-handle {
996
- background: none;
997
- padding: 0;
998
- opacity: 0.35;
999
- z-index: 10;
1000
- transition: opacity 120ms ease, background-color 120ms ease;
1001
- }
1002
- .titan-canvas-grid .react-grid-item:hover > .react-resizable-handle { opacity: 0.85; }
1003
- .titan-canvas-grid .react-grid-item > .react-resizable-handle:hover,
1004
- .titan-canvas-grid .react-grid-item > .react-resizable-handle:active { opacity: 1; }
1005
- /* Corner handles: 22x22 with a ring-coloured chevron */
1006
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se,
1007
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw,
1008
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne,
1009
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw {
1010
- width: 22px;
1011
- height: 22px;
1012
- background-image: none;
1013
- transform: none;
1014
- }
1015
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se::after,
1016
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw::after,
1017
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne::after,
1018
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw::after {
1019
- content: "";
1020
- position: absolute;
1021
- width: 12px; height: 12px;
1022
- border: 2px solid var(--color-desk-brass);
1023
- border-radius: 3px;
1024
- }
1025
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-se::after { right: 3px; bottom: 3px; border-top: none; border-left: none; }
1026
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw::after { left: 3px; bottom: 3px; border-top: none; border-right: none; }
1027
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne::after { right: 3px; top: 3px; border-bottom: none; border-left: none; }
1028
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw::after { left: 3px; top: 3px; border-bottom: none; border-right: none; }
1029
- /* Edge handles: full-edge strips with a centre grip */
1030
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e,
1031
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w {
1032
- top: 8px; bottom: 8px; height: auto; margin-top: 0;
1033
- width: 8px; background-image: none; transform: none;
1034
- }
1035
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n,
1036
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s {
1037
- left: 8px; right: 8px; width: auto; margin-left: 0;
1038
- height: 8px; background-image: none; transform: none;
1039
- }
1040
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after,
1041
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after,
1042
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after,
1043
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after {
1044
- content: ""; position: absolute; background: var(--color-desk-brass); border-radius: 2px;
1045
- }
1046
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after,
1047
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after {
1048
- top: 50%; transform: translateY(-50%);
1049
- width: 3px; height: 32px;
1050
- }
1051
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after { right: 2px; }
1052
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after { left: 2px; }
1053
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after,
1054
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after {
1055
- left: 50%; transform: translateX(-50%);
1056
- height: 3px; width: 32px;
1057
- }
1058
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after { top: 2px; }
1059
- .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after { bottom: 2px; }
1060
- /* Allow resizing and dragging freely — placeholder turns accent blue */
1061
- .titan-canvas-grid .react-grid-placeholder {
1062
- background: rgba(99, 102, 241, 0.14) !important;
1063
- border: 1px dashed rgba(99, 102, 241, 0.55) !important;
1064
- border-radius: 12px;
1065
- opacity: 1 !important;
1066
- }
1067
- `}),n.jsx("div",{className:"fixed inset-0 opacity-[0.06] pointer-events-none",style:{backgroundImage:"radial-gradient(circle at 1px 1px, var(--theme-metal-dark, rgba(120,90,50,0.4)) 1px, transparent 0)",backgroundSize:"24px 24px"}}),n.jsxs("div",{className:"titan-canvas-titlebar absolute top-0 left-0 right-0 z-40",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("div",{className:"titan-canvas-space-icon",style:{color:s.color||"var(--color-desk-accent)"},children:n.jsx(gc,{className:"w-4 h-4"})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("h1",{className:"titan-canvas-title truncate",children:s.name}),n.jsxs("div",{className:"titan-canvas-subtitle",children:[H.length," panel",H.length!==1?"s":""," on desktop canvas"]})]}),n.jsx(Ft,{label:"Open Mission Chat",onClick:()=>e("/mission"),variant:"primary",children:n.jsx(mn,{className:"w-4 h-4"})}),n.jsx("button",{onClick:()=>c(!0),className:"titan-canvas-instructions truncate",title:"Edit agent instructions for this space",children:s.agentInstructions?n.jsx("span",{className:"truncate",children:s.agentInstructions}):n.jsx("span",{className:"italic",children:"add agent instructions"})})]}),n.jsxs("div",{className:"titan-canvas-toolbar",children:[py.map($=>{const F=$.icon;return n.jsx(Ft,{label:`Add ${$.label}`,onClick:()=>J($.source,$.name,$.w,$.h),children:n.jsx(F,{className:"w-4 h-4"})},$.source)}),H.length>0&&n.jsx(Ft,{label:"Clear canvas",onClick:async()=>{Wn("canvas_clear_all",{panelCount:H.length}),s&&(await ke.clearSpace(s.id),r({...s,widgets:[]}))},variant:"danger",children:n.jsx(Jl,{className:"w-4 h-4"})}),n.jsx("button",{disabled:T,className:`titan-canvas-version-chip ${m!=null&&m.isNewer?"titan-canvas-version-chip--update":""}`,style:m!=null&&m.isNewer?void 0:{background:"var(--theme-paper, rgba(253,246,227,0.7))",borderColor:"var(--color-desk-border)"},title:m!=null&&m.isNewer?`Update available: ${m.current} → ${m.latest}`:`TITAN ${(m==null?void 0:m.current)||""}`,onClick:async()=>{if(!(m!=null&&m.isNewer)||T||!confirm(`Update TITAN from ${m.current} → ${m.latest}?
1068
-
1069
- Your data in ~/.titan/ will be preserved. The gateway will restart after the update.`))return;const $=m.current;S(!0);const F=await k(!0);if(!F.ok){S(!1),alert(`Update failed: ${F.error||"Unknown error"}`);return}const V=await _($);S(!1),V?window.location.reload():alert("Update sent, but the gateway did not come back within 30s. Check service status manually.")},children:T?"…":m!=null&&m.isNewer?`↑ ${m.latest}`:`v${(m==null?void 0:m.current)||""}`}),n.jsx(Ft,{label:"Open widget gallery",onClick:()=>g(!0),variant:"primary",children:n.jsx(rc,{className:"w-4 h-4"})}),n.jsx(Ft,{label:"Open command palette",onClick:()=>f(!0),children:n.jsx(Ql,{className:"w-4 h-4"})}),n.jsx(Ft,{label:"Open chat dock",onClick:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle")),children:n.jsx(xn,{className:"w-4 h-4"})})]})]}),n.jsx("div",{ref:A,className:"relative pt-28 min-h-[5000px]",children:H.length===0?n.jsx(xy,{space:s,onAddWidget:J,onOpenChat:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle",{detail:{open:!0}}))}):n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"pt-12 text-center",children:n.jsx("div",{className:"inline-block rounded-xl px-6 py-3 border text-sm font-serif",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)"},children:"Loading grid..."})}),children:n.jsx(ay,{className:"layout titan-canvas-grid",width:E,layouts:{lg:K},breakpoints:uy,cols:cy,rowHeight:dy,margin:hy,containerPadding:[12,12],isDraggable:!0,isResizable:!0,draggableHandle:".panel-drag-handle",resizeHandles:fy,compactType:null,preventCollision:!1,allowOverlap:!0,useCSSTransforms:!0,onLayoutChange:C,onDragStop:$=>{R($)},onResizeStop:$=>{R($)},children:H.map($=>n.jsx(my,{widget:$,space:s,onRemove:P},$.id))})})}),n.jsx(Ip,{space:s,defaultExpanded:i}),n.jsx(Op,{}),n.jsx($p,{space:s,open:o,onClose:()=>c(!1),onSaved:$=>{r(F=>F&&{...F,agentInstructions:$||void 0})}}),d&&(()=>{const $=H.find(F=>F.id===d);return!$||$.format==="system"?(l(null),null):n.jsx(Vp,{widget:$,spaceId:s.id,open:!0,onClose:()=>l(null),onSaved:F=>{const V=H.map(se=>se.id===F.id?{...se,...F}:se);r(se=>se&&{...se,widgets:V})}})})(),n.jsx(Jp,{open:p,onClose:()=>g(!1)}),n.jsx(tm,{}),u&&n.jsx(_l,{currentSpaceId:s.id,onSpaceSelect:$=>{e(`/space/${$}`),f(!1)},onAction:$=>{$.type==="widget"&&J($.source,$.name,$.w,$.h),f(!1)},onClose:()=>f(!1)}),n.jsx(Uf,{open:x,onClose:()=>y(!1)})]})]}):n.jsx("div",{className:"h-full w-full flex items-center justify-center",children:n.jsx("div",{className:"rounded-xl px-6 py-3 border text-sm",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)",fontFamily:"var(--theme-font-display, 'Georgia', serif)"},children:"Loading space..."})})}function xy({space:t,onAddWidget:e,onOpenChat:s}){const r=[{title:"System",items:[{label:"SOMA",source:"system:soma",w:6,h:6},{label:"Command Post",source:"system:command-post",w:8,h:6},{label:"Overview",source:"system:overview",w:6,h:5},{label:"Organism",source:"system:organism",w:6,h:6},{label:"Infra",source:"system:infra",w:6,h:4},{label:"VRAM",source:"system:vram",w:6,h:6},{label:"Fleet",source:"system:fleet",w:6,h:5}]},{title:"Intelligence",items:[{label:"Intelligence",source:"system:intelligence",w:6,h:5},{label:"Memory Graph",source:"system:memory-graph",w:8,h:7},{label:"Memory Wiki",source:"system:memory-wiki",w:6,h:6},{label:"Autoresearch",source:"system:autoresearch",w:6,h:6},{label:"Self-Proposals",source:"system:self-proposals",w:6,h:6},{label:"Training",source:"system:training",w:6,h:6},{label:"Eval",source:"system:eval",w:6,h:6}]},{title:"Tools",items:[{label:"Tools",source:"system:tools",w:5,h:4},{label:"Files",source:"system:files",w:4,h:6},{label:"Browser",source:"system:browser",w:6,h:5},{label:"Recipes",source:"system:recipes",w:6,h:6},{label:"Voice",source:"system:voice",w:5,h:5}]},{title:"Workflows",items:[{label:"Mission Driver",source:"system:mission-driver",w:7,h:7},{label:"Mission Graph",source:"system:mission-graph",w:8,h:7},{label:"Daily Digest",source:"system:daily-digest",w:5,h:7},{label:"Time Travel",source:"system:time-travel",w:8,h:6},{label:"Sessions",source:"system:sessions",w:6,h:5},{label:"Checkpoints",source:"system:checkpoints",w:6,h:5},{label:"Cron",source:"system:cron",w:6,h:6}]},{title:"Comms",items:[{label:"Watch",source:"system:watch",w:8,h:7},{label:"Backup",source:"system:backup",w:6,h:6},{label:"Teams",source:"system:teams",w:6,h:6}]}];return n.jsx("div",{className:"h-full flex items-start justify-center pt-8 pb-32 px-4 sm:px-6",children:n.jsxs("div",{className:"titan-canvas-empty-panel text-center w-full max-w-4xl px-5 sm:px-8 py-8 sm:py-10",children:[n.jsx("style",{children:`
1070
- .titan-empty-hero {
1071
- background: linear-gradient(180deg,
1072
- color-mix(in srgb, var(--theme-metal-bright) 22%, transparent) 0%,
1073
- color-mix(in srgb, var(--theme-metal) 14%, transparent) 100%);
1074
- color: var(--theme-accent);
1075
- border: 1px solid color-mix(in srgb, var(--theme-metal) 55%, transparent);
1076
- box-shadow:
1077
- 0 0 0 0 color-mix(in srgb, var(--theme-accent) 0%, transparent),
1078
- 0 2px 6px var(--theme-shadow);
1079
- transition: transform 140ms ease, box-shadow 220ms ease, border-color 140ms ease;
1080
- font-family: var(--theme-font-display);
1081
- }
1082
- .titan-empty-hero:hover {
1083
- transform: translateY(-1px);
1084
- border-color: var(--theme-metal-bright);
1085
- box-shadow:
1086
- 0 0 24px color-mix(in srgb, var(--theme-accent) 35%, transparent),
1087
- 0 4px 12px var(--theme-shadow);
1088
- }
1089
- .titan-empty-chip {
1090
- width: 110px;
1091
- background: var(--theme-paper);
1092
- color: var(--theme-ink-soft);
1093
- border: 1px solid color-mix(in srgb, var(--theme-metal) 40%, transparent);
1094
- box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--theme-paper-line) 50%, transparent);
1095
- font-family: var(--theme-font-display);
1096
- transition: transform 120ms ease, border-color 120ms ease, color 120ms ease, box-shadow 120ms ease;
1097
- }
1098
- .titan-empty-chip:hover {
1099
- transform: translateY(-1px);
1100
- border-color: var(--theme-metal-bright);
1101
- color: var(--theme-ink);
1102
- box-shadow:
1103
- inset 0 0 0 1px color-mix(in srgb, var(--theme-metal-bright) 35%, transparent),
1104
- 0 2px 6px var(--theme-shadow);
1105
- }
1106
- .titan-empty-group-label {
1107
- font-family: var(--theme-font-mono);
1108
- color: var(--theme-metal-dark);
1109
- letter-spacing: 0.18em;
1110
- }
1111
- .titan-empty-rule {
1112
- background: linear-gradient(90deg,
1113
- transparent 0%,
1114
- color-mix(in srgb, var(--theme-metal) 50%, transparent) 50%,
1115
- transparent 100%);
1116
- }
1117
- `}),n.jsx("div",{className:"w-14 h-14 rounded-lg flex items-center justify-center mx-auto mb-5",style:{background:"color-mix(in srgb, var(--theme-metal) 16%, transparent)",border:"1px solid color-mix(in srgb, var(--theme-metal) 35%, transparent)"},children:n.jsx("svg",{className:"w-7 h-7",style:{color:"var(--theme-metal)"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"})})}),n.jsx("h2",{className:"text-xl font-bold mb-2",style:{color:"var(--theme-ink)",fontFamily:"var(--theme-font-display)"},children:t.name}),n.jsx("p",{className:"text-sm mb-7",style:{color:"var(--theme-ink-soft)",fontFamily:"var(--theme-font-display)"},children:"This space is empty. Ask the agent to materialize something for you, or place a system panel below."}),n.jsx("div",{className:"flex justify-center mb-8",children:n.jsxs("button",{onClick:s,className:"titan-empty-hero inline-flex items-center gap-2 px-6 py-3 rounded-lg text-base font-semibold",children:[n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a7 7 0 0 0-4 12.7V17a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-2.3A7 7 0 0 0 12 2z"}),n.jsx("path",{d:"M10 22h4"})]}),"Ask Agent"]})}),n.jsx("div",{className:"space-y-5 text-left",children:r.map(i=>n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-3 mb-2.5 px-1",children:[n.jsx("span",{className:"titan-empty-group-label text-[10px] font-bold uppercase",children:i.title}),n.jsx("span",{className:"titan-empty-rule flex-1 h-px"})]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:i.items.map(o=>n.jsxs("button",{onClick:()=>e(o.source,o.label,o.w,o.h),className:"titan-empty-chip px-3 py-1.5 rounded-md text-[11px] text-center",title:`Add ${o.label}`,children:["+ ",o.label]},o.source))})]},i.title))})]})})}const Zy=Object.freeze(Object.defineProperty({__proto__:null,default:by},Symbol.toStringTag,{value:"Module"}));export{sc as D,bo as G,Zy as T};