titan-agent 5.0.2 → 5.0.3

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 (176) hide show
  1. package/dist/agent/agent.js +48 -3
  2. package/dist/agent/agent.js.map +1 -1
  3. package/dist/agent/agentLoop.js +83 -5
  4. package/dist/agent/agentLoop.js.map +1 -1
  5. package/dist/agent/commandPost.js +1 -1
  6. package/dist/agent/commandPost.js.map +1 -1
  7. package/dist/agent/goalProposer.js +2 -2
  8. package/dist/agent/goalProposer.js.map +1 -1
  9. package/dist/agent/missionDriver.js +1 -1
  10. package/dist/agent/missionDriver.js.map +1 -1
  11. package/dist/agent/promptBudget.js +85 -0
  12. package/dist/agent/promptBudget.js.map +1 -0
  13. package/dist/agent/structuredSpawn.js +1 -1
  14. package/dist/agent/structuredSpawn.js.map +1 -1
  15. package/dist/agent/subtaskTaxonomy.js +1 -1
  16. package/dist/agent/subtaskTaxonomy.js.map +1 -1
  17. package/dist/agent/systemPromptParts.js +10 -1
  18. package/dist/agent/systemPromptParts.js.map +1 -1
  19. package/dist/agent/toolRunner.js +16 -0
  20. package/dist/agent/toolRunner.js.map +1 -1
  21. package/dist/agent/toolSearch.js +4 -1
  22. package/dist/agent/toolSearch.js.map +1 -1
  23. package/dist/analytics/bugReports.js +1 -1
  24. package/dist/analytics/bugReports.js.map +1 -1
  25. package/dist/channels/messenger.js +1 -1
  26. package/dist/channels/messenger.js.map +1 -1
  27. package/dist/eval/harness.js +141 -0
  28. package/dist/eval/harness.js.map +1 -0
  29. package/dist/gateway/server.js +374 -74
  30. package/dist/gateway/server.js.map +1 -1
  31. package/dist/hooks/shellHooks.js +1 -1
  32. package/dist/hooks/shellHooks.js.map +1 -1
  33. package/dist/lib/auto-heal/repair-strategies.js.map +1 -1
  34. package/dist/memory/promptIncludes.js +58 -0
  35. package/dist/memory/promptIncludes.js.map +1 -0
  36. package/dist/organism/alertsStore.js +70 -0
  37. package/dist/organism/alertsStore.js.map +1 -0
  38. package/dist/plugins/memoryRetrieval.js.map +1 -1
  39. package/dist/providers/ollama.js +7 -7
  40. package/dist/providers/ollama.js.map +1 -1
  41. package/dist/safety/invariants.js +60 -0
  42. package/dist/safety/invariants.js.map +1 -0
  43. package/dist/safety/opusReview.js +1 -1
  44. package/dist/safety/opusReview.js.map +1 -1
  45. package/dist/security/commandScanner.js +2 -2
  46. package/dist/security/commandScanner.js.map +1 -1
  47. package/dist/security/secretGuard.js +4 -4
  48. package/dist/security/secretGuard.js.map +1 -1
  49. package/dist/skills/builtin/widget_gallery.js +28 -1
  50. package/dist/skills/builtin/widget_gallery.js.map +1 -1
  51. package/dist/skills/frontmatterLoader.js +119 -0
  52. package/dist/skills/frontmatterLoader.js.map +1 -0
  53. package/dist/skills/registry.js +20 -0
  54. package/dist/skills/registry.js.map +1 -1
  55. package/dist/testing/testHealthMonitor.js +1 -2
  56. package/dist/testing/testHealthMonitor.js.map +1 -1
  57. package/dist/utils/constants.js +2 -2
  58. package/dist/utils/constants.js.map +1 -1
  59. package/dist/utils/replyQuality.js +1 -1
  60. package/dist/utils/replyQuality.js.map +1 -1
  61. package/dist/utils/tokens.js +1 -1
  62. package/dist/utils/tokens.js.map +1 -1
  63. package/docs/bleeding-edge-agents-2026.md +450 -0
  64. package/docs/langchain-analysis.md +598 -0
  65. package/docs/langchain-code-analysis.md +363 -0
  66. package/docs/space-agent-analysis.md +300 -0
  67. package/package.json +1 -1
  68. package/ui/dist/assets/{AuditPanel-G7YA1HzV.js → AuditPanel-B84Mp16G.js} +2 -2
  69. package/ui/dist/assets/AutonomyPanel-DOtiTFxV.js +11 -0
  70. package/ui/dist/assets/{AutopilotPanel-CHRjxdh0.js → AutopilotPanel-nTb1Dnru.js} +1 -1
  71. package/ui/dist/assets/AutoresearchPanel-D46mX8VF.js +6 -0
  72. package/ui/dist/assets/BackupPanel-DGM1XXbG.js +1 -0
  73. package/ui/dist/assets/BrowserPanel-Cn1tTN3y.js +6 -0
  74. package/ui/dist/assets/{CPAgents-D5533PhK.js → CPAgents-CEraUkME.js} +1 -1
  75. package/ui/dist/assets/{CPDashboard-C-GgqDsI.js → CPDashboard-B_yidGAe.js} +2 -2
  76. package/ui/dist/assets/CPFiles-BBS8jtYH.js +1 -0
  77. package/ui/dist/assets/CPGoals-DL5v21TZ.js +1 -0
  78. package/ui/dist/assets/CPInbox-CyLQJBYF.js +11 -0
  79. package/ui/dist/assets/{CPSocial-mUQsrSh5.js → CPSocial-BkEtQ1Um.js} +3 -3
  80. package/ui/dist/assets/ChannelsPanel-CD2kHhA5.js +1 -0
  81. package/ui/dist/assets/CheckpointsPanel-BrUTFPu_.js +1 -0
  82. package/ui/dist/assets/CommandPostHub-BPPaUv1B.js +29 -0
  83. package/ui/dist/assets/CronPanel-CsfQctFp.js +1 -0
  84. package/ui/dist/assets/DaemonPanel-CNUggBbL.js +1 -0
  85. package/ui/dist/assets/DataTable-DuAEp_QJ.js +1 -0
  86. package/ui/dist/assets/{EmptyState-D60-wQrz.js → EmptyState-DFrAEZDm.js} +1 -1
  87. package/ui/dist/assets/EvalPanel-DEX0a5-b.js +1 -0
  88. package/ui/dist/assets/{FilesPanel-BNN3h_HW.js → FilesPanel-DATsiAqG.js} +1 -1
  89. package/ui/dist/assets/FleetPanel-QYQKqx4W.js +1 -0
  90. package/ui/dist/assets/{HomelabPanel-1mfhRBh6.js → HomelabPanel-DhuXd3ZD.js} +2 -2
  91. package/ui/dist/assets/{InfraView-Df6SFI7b.js → InfraView-eS7cpESw.js} +2 -2
  92. package/ui/dist/assets/InlineEditableField-zIAnW4AR.js +1 -0
  93. package/ui/dist/assets/{Input-DYukme8A.js → Input-bFsLI0fq.js} +1 -1
  94. package/ui/dist/assets/IntegrationsPanel-C_FswSRN.js +1 -0
  95. package/ui/dist/assets/IntelligenceView-smQ6aBwx.js +2 -0
  96. package/ui/dist/assets/{LearningPanel-BPx05bBu.js → LearningPanel-BEgF_iND.js} +1 -1
  97. package/ui/dist/assets/{LogsPanel-D3Qfp2SE.js → LogsPanel-Br1P8ST6.js} +1 -1
  98. package/ui/dist/assets/McpPanel-ByvQ12J_.js +1 -0
  99. package/ui/dist/assets/{MemoryGraphPanel-BFovwaSG.js → MemoryGraphPanel-BGOeSaET.js} +1 -1
  100. package/ui/dist/assets/MemoryWikiPanel-CR8btd66.js +11 -0
  101. package/ui/dist/assets/MeshPanel-BjkcSOMz.js +11 -0
  102. package/ui/dist/assets/NvidiaPanel-NYt42w7L.js +1 -0
  103. package/ui/dist/assets/OrganismPanel-PHvISvVn.js +1 -0
  104. package/ui/dist/assets/OverviewPanel-q35zdMr6.js +6 -0
  105. package/ui/dist/assets/{PageHeader-BdvxKoad.js → PageHeader-Cwn3OALc.js} +1 -1
  106. package/ui/dist/assets/PaperclipPanel-BDpQki0d.js +1 -0
  107. package/ui/dist/assets/{PersonasPanel-BpI6Npxv.js → PersonasPanel-DxrGW5C4.js} +1 -1
  108. package/ui/dist/assets/RecipesPanel-CYRdBx5u.js +1 -0
  109. package/ui/dist/assets/{SecurityPanel-CBDsEAFz.js → SecurityPanel-i1QMctV0.js} +1 -1
  110. package/ui/dist/assets/SelfImprovePanel-DbybAZWp.js +1 -0
  111. package/ui/dist/assets/SelfProposalsPanel-DtcTUDDd.js +2 -0
  112. package/ui/dist/assets/SessionsPanel-B7QmOizR.js +1 -0
  113. package/ui/dist/assets/SessionsTab-BdJj_vsI.js +1 -0
  114. package/ui/dist/assets/{SettingsPanel-BiWHsOAJ.js → SettingsPanel-DnEvJUFe.js} +1 -1
  115. package/ui/dist/assets/SettingsView-C39dk_yr.js +2 -0
  116. package/ui/dist/assets/{SkeletonLoader-CGtpZJ-7.js → SkeletonLoader-CsiR8ED9.js} +1 -1
  117. package/ui/dist/assets/{SkillsPanel-Z_9jA6dU.js → SkillsPanel-DM4qBFDS.js} +1 -1
  118. package/ui/dist/assets/{SomaView-AP3BXqf-.js → SomaView-CWnPKEQI.js} +1 -1
  119. package/ui/dist/assets/{StatCard-CrnvXPg5.js → StatCard-CY8lgeWm.js} +1 -1
  120. package/ui/dist/assets/{StatusBadge-B6r5EWBA.js → StatusBadge-CGvKbP7R.js} +1 -1
  121. package/ui/dist/assets/TeamsPanel-Bf6GaUni.js +1 -0
  122. package/ui/dist/assets/{TelemetryPanel-D6o14H-i.js → TelemetryPanel-JZ90gJXC.js} +1 -1
  123. package/ui/dist/assets/TitanCanvas-Hk49NFcA.js +1092 -0
  124. package/ui/dist/assets/ToolsView-Cq7Fuq3i.js +2 -0
  125. package/ui/dist/assets/{Tooltip-DNsYGHC9.js → Tooltip-CcoZrKsl.js} +1 -1
  126. package/ui/dist/assets/{TraceViewer-TOpdmqLF.js → TraceViewer-ojGf0drx.js} +1 -1
  127. package/ui/dist/assets/TrainingPanel-CWnP4H2l.js +1 -0
  128. package/ui/dist/assets/{VoiceOverlay-XIyCbAP7.js → VoiceOverlay-Dn6iaYgd.js} +1 -1
  129. package/ui/dist/assets/VramPanel-CLd9Ggck.js +1 -0
  130. package/ui/dist/assets/WatchView-CQBemwsm.js +13 -0
  131. package/ui/dist/assets/WorkTab-BOfTN-Bd.js +1 -0
  132. package/ui/dist/assets/WorkflowsPanel-qzNS0p0u.js +11 -0
  133. package/ui/dist/assets/{arrow-left-CQF-yBIU.js → arrow-left-c-8OFZUV.js} +1 -1
  134. package/ui/dist/assets/{chart-column-1smg0GbX.js → chart-column-x6L66Qw7.js} +1 -1
  135. package/ui/dist/assets/{circle-check-big-BiMDFx6C.js → circle-check-big-WaW3U3Xl.js} +1 -1
  136. package/ui/dist/assets/{dollar-sign-DMYH4Q_a.js → dollar-sign-D2Oce4Ru.js} +1 -1
  137. package/ui/dist/assets/{download-BYFd-yl6.js → download-YvPDLlFJ.js} +1 -1
  138. package/ui/dist/assets/eye-off-DIMcxsdQ.js +6 -0
  139. package/ui/dist/assets/{funnel-pWBglhfw.js → funnel-DqD9srZu.js} +1 -1
  140. package/ui/dist/assets/{git-branch-Cgqic2Us.js → git-branch-0FamUEbU.js} +1 -1
  141. package/ui/dist/assets/index-D932CbpQ.css +1 -0
  142. package/ui/dist/assets/index-NatBSFxj.js +227 -0
  143. package/ui/dist/assets/{legacy-BHbi-Nm_.js → legacy-DOO7F5cq.js} +1 -1
  144. package/ui/dist/assets/{lightbulb-D_y0Mtyq.js → lightbulb-Bk6KlR6q.js} +1 -1
  145. package/ui/dist/assets/pause-DDC_zUiJ.js +6 -0
  146. package/ui/dist/assets/{play-2xR4_zUG.js → play-BPXbHToG.js} +1 -1
  147. package/ui/dist/assets/{plug-DhvhYYy_.js → plug-Dxp-sWVF.js} +1 -1
  148. package/ui/dist/assets/proxy-vU7v4NVM.js +9 -0
  149. package/ui/dist/assets/square-Bn_0tYME.js +6 -0
  150. package/ui/dist/assets/target-BrtxUtzl.js +6 -0
  151. package/ui/dist/assets/toggle-right-CYphlpN5.js +11 -0
  152. package/ui/dist/assets/{trash-2-DmRaMz9e.js → trash-2-C_Jsp23A.js} +1 -1
  153. package/ui/dist/assets/{trending-up-DsDcs3Jo.js → trending-up-DrtLViSm.js} +1 -1
  154. package/ui/dist/assets/trophy-DdRzAOfo.js +6 -0
  155. package/ui/dist/index.html +2 -2
  156. package/ui/dist/assets/CPFiles-G7veSjMg.js +0 -6
  157. package/ui/dist/assets/CPGoals-C3DlKJrJ.js +0 -1
  158. package/ui/dist/assets/CPInbox-D10curQs.js +0 -16
  159. package/ui/dist/assets/ChannelsPanel-M3pO2htW.js +0 -1
  160. package/ui/dist/assets/CommandPostHub-CW9OY1A4.js +0 -37
  161. package/ui/dist/assets/InlineEditableField-CH-jR3LC.js +0 -11
  162. package/ui/dist/assets/IntegrationsPanel-EaN999Te.js +0 -1
  163. package/ui/dist/assets/IntelligenceView-Q4DBmJpJ.js +0 -2
  164. package/ui/dist/assets/McpPanel-zC7jTaSx.js +0 -6
  165. package/ui/dist/assets/MeshPanel-CqtYZ74K.js +0 -11
  166. package/ui/dist/assets/NvidiaPanel-BVIZFHet.js +0 -1
  167. package/ui/dist/assets/SelfImprovePanel-PSCYO6sx.js +0 -11
  168. package/ui/dist/assets/SessionsTab-Cn3dGgjX.js +0 -1
  169. package/ui/dist/assets/SettingsView-3BSIzAfW.js +0 -2
  170. package/ui/dist/assets/TitanCanvas-cnb7R1gS.js +0 -1056
  171. package/ui/dist/assets/ToolsView-Dp-xUWJG.js +0 -2
  172. package/ui/dist/assets/WorkTab-Pgq-iLz9.js +0 -1
  173. package/ui/dist/assets/WorkflowsPanel-B91LeW7r.js +0 -21
  174. package/ui/dist/assets/eye-BfW7UcEC.js +0 -11
  175. package/ui/dist/assets/index-BWSnB6Kr.js +0 -227
  176. package/ui/dist/assets/index-Dtw1pbjc.css +0 -1
@@ -0,0 +1,1092 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SomaView-CWnPKEQI.js","assets/index-NatBSFxj.js","assets/index-D932CbpQ.css","assets/Input-bFsLI0fq.js","assets/Tooltip-CcoZrKsl.js","assets/VoiceOverlay-Dn6iaYgd.js","assets/SomaView-BtCkeWfZ.css","assets/CommandPostHub-BPPaUv1B.js","assets/proxy-vU7v4NVM.js","assets/InlineEditableField-zIAnW4AR.js","assets/pause-DDC_zUiJ.js","assets/dollar-sign-D2Oce4Ru.js","assets/git-branch-0FamUEbU.js","assets/chart-column-x6L66Qw7.js","assets/target-BrtxUtzl.js","assets/trash-2-C_Jsp23A.js","assets/IntelligenceView-smQ6aBwx.js","assets/MemoryGraphPanel-BGOeSaET.js","assets/InfraView-eS7cpESw.js","assets/ToolsView-Cq7Fuq3i.js","assets/SettingsView-C39dk_yr.js","assets/SettingsPanel-DnEvJUFe.js","assets/PageHeader-Cwn3OALc.js","assets/circle-check-big-WaW3U3Xl.js","assets/download-YvPDLlFJ.js","assets/play-BPXbHToG.js","assets/SecurityPanel-i1QMctV0.js","assets/AuditPanel-B84Mp16G.js","assets/funnel-DqD9srZu.js","assets/AutopilotPanel-nTb1Dnru.js","assets/WorkflowsPanel-qzNS0p0u.js","assets/toggle-right-CYphlpN5.js","assets/LearningPanel-BEgF_iND.js","assets/lightbulb-Bk6KlR6q.js","assets/trending-up-DrtLViSm.js","assets/SelfImprovePanel-DbybAZWp.js","assets/trophy-DdRzAOfo.js","assets/PersonasPanel-DxrGW5C4.js","assets/HomelabPanel-DhuXd3ZD.js","assets/StatCard-CY8lgeWm.js","assets/SkeletonLoader-CsiR8ED9.js","assets/NvidiaPanel-NYt42w7L.js","assets/eye-off-DIMcxsdQ.js","assets/FilesPanel-DATsiAqG.js","assets/arrow-left-c-8OFZUV.js","assets/LogsPanel-Br1P8ST6.js","assets/TelemetryPanel-JZ90gJXC.js","assets/SkillsPanel-DM4qBFDS.js","assets/McpPanel-ByvQ12J_.js","assets/plug-Dxp-sWVF.js","assets/IntegrationsPanel-C_FswSRN.js","assets/ChannelsPanel-CD2kHhA5.js","assets/MeshPanel-BjkcSOMz.js","assets/DataTable-DuAEp_QJ.js","assets/DaemonPanel-CNUggBbL.js","assets/MemoryWikiPanel-CR8btd66.js","assets/AutoresearchPanel-D46mX8VF.js","assets/SelfProposalsPanel-DtcTUDDd.js","assets/OverviewPanel-q35zdMr6.js","assets/SessionsPanel-B7QmOizR.js","assets/WatchView-CQBemwsm.js","assets/BackupPanel-DGM1XXbG.js","assets/TrainingPanel-CWnP4H2l.js","assets/RecipesPanel-CYRdBx5u.js","assets/VramPanel-CLd9Ggck.js","assets/TeamsPanel-Bf6GaUni.js","assets/CronPanel-CsfQctFp.js","assets/CheckpointsPanel-BrUTFPu_.js","assets/OrganismPanel-PHvISvVn.js","assets/FleetPanel-QYQKqx4W.js","assets/BrowserPanel-Cn1tTN3y.js","assets/PaperclipPanel-BDpQki0d.js","assets/square-Bn_0tYME.js","assets/EvalPanel-DEX0a5-b.js","assets/legacy-DOO7F5cq.js"])))=>i.map(i=>d[i]);
2
+ var Xa=Object.defineProperty;var Za=(t,e,s)=>e in t?Xa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var We=(t,e,s)=>Za(t,typeof e!="symbol"?e+"":e,s);import{c as re,a as Xe,g as Qa,r as S,b as Pe,j as r,s as el,X as ws,S as hr,A as gt,C as fr,d as pr,G as Ii,R as te,_ as se,Z as tl,e as nn,f as sl,h as nl,W as rl,M as il,H as ol,u as al,i as ll,t as Sn}from"./index-NatBSFxj.js";import{M as Di,V as cl,C as dl}from"./VoiceOverlay-Dn6iaYgd.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 ul=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],Mi=re("archive",ul);/**
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 hl=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],os=re("book-open",hl);/**
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 fl=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Oi=re("bot",fl);/**
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 pl=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]],mt=re("brain",pl);/**
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 gl=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ml=re("check",gl);/**
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 yl=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],wl=re("chevron-up",yl);/**
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 bl=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]],as=re("clock",bl);/**
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 xl=[["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"}]],vl=re("compass",xl);/**
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 _l=[["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"}]],kl=re("database",_l);/**
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 El=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Xr=re("external-link",El);/**
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 Sl=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Pi=re("eye",Sl);/**
58
+ * @license lucide-react v0.513.0 - ISC
59
+ *
60
+ * This source code is licensed under the ISC license.
61
+ * See the LICENSE file in the root directory of this source tree.
62
+ */const jl=[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],rn=re("file-text",jl);/**
63
+ * @license lucide-react v0.513.0 - ISC
64
+ *
65
+ * This source code is licensed under the ISC license.
66
+ * See the LICENSE file in the root directory of this source tree.
67
+ */const Nl=[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]],Ui=re("flask-conical",Nl);/**
68
+ * @license lucide-react v0.513.0 - ISC
69
+ *
70
+ * This source code is licensed under the ISC license.
71
+ * See the LICENSE file in the root directory of this source tree.
72
+ */const Cl=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],Tl=re("folder",Cl);/**
73
+ * @license lucide-react v0.513.0 - ISC
74
+ *
75
+ * This source code is licensed under the ISC license.
76
+ * See the LICENSE file in the root directory of this source tree.
77
+ */const Al=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Rl=re("gauge",Al);/**
78
+ * @license lucide-react v0.513.0 - ISC
79
+ *
80
+ * This source code is licensed under the ISC license.
81
+ * See the LICENSE file in the root directory of this source tree.
82
+ */const Ll=[["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"}]],Wi=re("git-pull-request",Ll);/**
83
+ * @license lucide-react v0.513.0 - ISC
84
+ *
85
+ * This source code is licensed under the ISC license.
86
+ * See the LICENSE file in the root directory of this source tree.
87
+ */const Il=[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}]],Dl=re("hexagon",Il);/**
88
+ * @license lucide-react v0.513.0 - ISC
89
+ *
90
+ * This source code is licensed under the ISC license.
91
+ * See the LICENSE file in the root directory of this source tree.
92
+ */const Ml=[["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"}]],Ol=re("history",Ml);/**
93
+ * @license lucide-react v0.513.0 - ISC
94
+ *
95
+ * This source code is licensed under the ISC license.
96
+ * See the LICENSE file in the root directory of this source tree.
97
+ */const Pl=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]],Ul=re("house",Pl);/**
98
+ * @license lucide-react v0.513.0 - ISC
99
+ *
100
+ * This source code is licensed under the ISC license.
101
+ * See the LICENSE file in the root directory of this source tree.
102
+ */const Wl=[["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"}]],Bi=re("layout-grid",Wl);/**
103
+ * @license lucide-react v0.513.0 - ISC
104
+ *
105
+ * This source code is licensed under the ISC license.
106
+ * See the LICENSE file in the root directory of this source tree.
107
+ */const Bl=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Fi=re("loader-circle",Bl);/**
108
+ * @license lucide-react v0.513.0 - ISC
109
+ *
110
+ * This source code is licensed under the ISC license.
111
+ * See the LICENSE file in the root directory of this source tree.
112
+ */const Fl=[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]],$i=re("message-square",Fl);/**
113
+ * @license lucide-react v0.513.0 - ISC
114
+ *
115
+ * This source code is licensed under the ISC license.
116
+ * See the LICENSE file in the root directory of this source tree.
117
+ */const $l=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],zi=re("network",$l);/**
118
+ * @license lucide-react v0.513.0 - ISC
119
+ *
120
+ * This source code is licensed under the ISC license.
121
+ * See the LICENSE file in the root directory of this source tree.
122
+ */const zl=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],Vi=re("paperclip",zl);/**
123
+ * @license lucide-react v0.513.0 - ISC
124
+ *
125
+ * This source code is licensed under the ISC license.
126
+ * See the LICENSE file in the root directory of this source tree.
127
+ */const Vl=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Hl=re("pencil",Vl);/**
128
+ * @license lucide-react v0.513.0 - ISC
129
+ *
130
+ * This source code is licensed under the ISC license.
131
+ * See the LICENSE file in the root directory of this source tree.
132
+ */const ql=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Gl=re("plus",ql);/**
133
+ * @license lucide-react v0.513.0 - ISC
134
+ *
135
+ * This source code is licensed under the ISC license.
136
+ * See the LICENSE file in the root directory of this source tree.
137
+ */const Yl=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],Zr=re("power",Yl);/**
138
+ * @license lucide-react v0.513.0 - ISC
139
+ *
140
+ * This source code is licensed under the ISC license.
141
+ * See the LICENSE file in the root directory of this source tree.
142
+ */const Kl=[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]],Hi=re("radio",Kl);/**
143
+ * @license lucide-react v0.513.0 - ISC
144
+ *
145
+ * This source code is licensed under the ISC license.
146
+ * See the LICENSE file in the root directory of this source tree.
147
+ */const Jl=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],on=re("refresh-cw",Jl);/**
148
+ * @license lucide-react v0.513.0 - ISC
149
+ *
150
+ * This source code is licensed under the ISC license.
151
+ * See the LICENSE file in the root directory of this source tree.
152
+ */const Xl=[["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"}]],qi=re("rotate-ccw",Xl);/**
153
+ * @license lucide-react v0.513.0 - ISC
154
+ *
155
+ * This source code is licensed under the ISC license.
156
+ * See the LICENSE file in the root directory of this source tree.
157
+ */const Zl=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],an=re("save",Zl);/**
158
+ * @license lucide-react v0.513.0 - ISC
159
+ *
160
+ * This source code is licensed under the ISC license.
161
+ * See the LICENSE file in the root directory of this source tree.
162
+ */const Ql=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],ec=re("search",Ql);/**
163
+ * @license lucide-react v0.513.0 - ISC
164
+ *
165
+ * This source code is licensed under the ISC license.
166
+ * See the LICENSE file in the root directory of this source tree.
167
+ */const tc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Gi=re("send",tc);/**
168
+ * @license lucide-react v0.513.0 - ISC
169
+ *
170
+ * This source code is licensed under the ISC license.
171
+ * See the LICENSE file in the root directory of this source tree.
172
+ */const sc=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],gr=re("server",sc);/**
173
+ * @license lucide-react v0.513.0 - ISC
174
+ *
175
+ * This source code is licensed under the ISC license.
176
+ * See the LICENSE file in the root directory of this source tree.
177
+ */const nc=[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],mr=re("settings",nc);/**
178
+ * @license lucide-react v0.513.0 - ISC
179
+ *
180
+ * This source code is licensed under the ISC license.
181
+ * See the LICENSE file in the root directory of this source tree.
182
+ */const rc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],ic=re("shield-check",rc);/**
183
+ * @license lucide-react v0.513.0 - ISC
184
+ *
185
+ * This source code is licensed under the ISC license.
186
+ * See the LICENSE file in the root directory of this source tree.
187
+ */const oc=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Yi=re("terminal",oc);/**
188
+ * @license lucide-react v0.513.0 - ISC
189
+ *
190
+ * This source code is licensed under the ISC license.
191
+ * See the LICENSE file in the root directory of this source tree.
192
+ */const ac=[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]],Ki=re("test-tube",ac);/**
193
+ * @license lucide-react v0.513.0 - ISC
194
+ *
195
+ * This source code is licensed under the ISC license.
196
+ * See the LICENSE file in the root directory of this source tree.
197
+ */const lc=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],yr=re("users",lc);/**
198
+ * @license lucide-react v0.513.0 - ISC
199
+ *
200
+ * This source code is licensed under the ISC license.
201
+ * See the LICENSE file in the root directory of this source tree.
202
+ */const cc=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],dc=re("wifi-off",cc);/**
203
+ * @license lucide-react v0.513.0 - ISC
204
+ *
205
+ * This source code is licensed under the ISC license.
206
+ * See the LICENSE file in the root directory of this source tree.
207
+ */const uc=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]],wr=re("wrench",uc),Ue=()=>new Map,Gn=t=>{const e=Ue();return t.forEach((s,n)=>{e.set(n,s)}),e},$e=(t,e,s)=>{let n=t.get(e);return n===void 0&&t.set(e,n=s()),n},hc=(t,e)=>{const s=[];for(const[n,i]of t)s.push(e(i,n));return s},fc=(t,e)=>{for(const[s,n]of t)if(e(n,s))return!0;return!1},yt=()=>new Set,jn=t=>t[t.length-1],pc=(t,e)=>{for(let s=0;s<e.length;s++)t.push(e[s])},at=Array.from,br=(t,e)=>{for(let s=0;s<t.length;s++)if(!e(t[s],s,t))return!1;return!0},Ji=(t,e)=>{for(let s=0;s<t.length;s++)if(e(t[s],s,t))return!0;return!1},gc=(t,e)=>{const s=new Array(t);for(let n=0;n<t;n++)s[n]=e(n,s);return s},ln=Array.isArray;class Xi{constructor(){this._observers=Ue()}on(e,s){return $e(this._observers,e,yt).add(s),s}once(e,s){const n=(...i)=>{this.off(e,n),s(...i)};this.on(e,n)}off(e,s){const n=this._observers.get(e);n!==void 0&&(n.delete(s),n.size===0&&this._observers.delete(e))}emit(e,s){return at((this._observers.get(e)||Ue()).values()).forEach(n=>n(...s))}destroy(){this._observers=Ue()}}class xr{constructor(){this._observers=Ue()}on(e,s){$e(this._observers,e,yt).add(s)}once(e,s){const n=(...i)=>{this.off(e,n),s(...i)};this.on(e,n)}off(e,s){const n=this._observers.get(e);n!==void 0&&(n.delete(s),n.size===0&&this._observers.delete(e))}emit(e,s){return at((this._observers.get(e)||Ue()).values()).forEach(n=>n(...s))}destroy(){this._observers=Ue()}}const Ye=Math.floor,Ls=Math.abs,mc=Math.log10,vr=(t,e)=>t<e?t:e,Tt=(t,e)=>t>e?t:e,Zi=t=>t!==0?t<0:1/t<0,Qr=1,ei=2,Nn=4,Cn=8,ls=32,it=64,Fe=128,cn=31,Yn=63,vt=127,yc=2147483647,Us=Number.MAX_SAFE_INTEGER,ti=Number.MIN_SAFE_INTEGER,wc=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Ye(t)===t),Qi=String.fromCharCode,bc=t=>t.toLowerCase(),xc=/^\s*/g,vc=t=>t.replace(xc,""),_c=/([A-Z])/g,si=(t,e)=>vc(t.replace(_c,s=>`${e}${bc(s)}`)),kc=t=>{const e=unescape(encodeURIComponent(t)),s=e.length,n=new Uint8Array(s);for(let i=0;i<s;i++)n[i]=e.codePointAt(i);return n},cs=typeof TextEncoder<"u"?new TextEncoder:null,Ec=t=>cs.encode(t),Kn=cs?Ec:kc;let rs=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});rs&&rs.decode(new Uint8Array).length===1&&(rs=null);const Sc=(t,e)=>gc(e,()=>t).join("");class bs{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Ae=()=>new bs,jc=t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e},xe=t=>{const e=new Uint8Array(jc(t));let s=0;for(let n=0;n<t.bufs.length;n++){const i=t.bufs[n];e.set(i,s),s+=i.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},Nc=(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(Tt(s,e)*2),t.cpos=0)},Ce=(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},ds=Ce,Q=(t,e)=>{for(;e>vt;)Ce(t,Fe|vt&e),e=Ye(e/128);Ce(t,vt&e)},_r=(t,e)=>{const s=Zi(e);for(s&&(e=-e),Ce(t,(e>Yn?Fe:0)|(s?it:0)|Yn&e),e=Ye(e/64);e>0;)Ce(t,(e>vt?Fe:0)|vt&e),e=Ye(e/128)},Jn=new Uint8Array(3e4),Cc=Jn.length/3,Tc=(t,e)=>{if(e.length<Cc){const s=cs.encodeInto(e,Jn).written||0;Q(t,s);for(let n=0;n<s;n++)Ce(t,Jn[n])}else ve(t,Kn(e))},Ac=(t,e)=>{const s=unescape(encodeURIComponent(e)),n=s.length;Q(t,n);for(let i=0;i<n;i++)Ce(t,s.codePointAt(i))},Qe=cs&&cs.encodeInto?Tc:Ac,dn=(t,e)=>{const s=t.cbuf.length,n=t.cpos,i=vr(s-n,e.length),a=e.length-i;t.cbuf.set(e.subarray(0,i),n),t.cpos+=i,a>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(Tt(s*2,a)),t.cbuf.set(e.subarray(i)),t.cpos=a)},ve=(t,e)=>{Q(t,e.byteLength),dn(t,e)},kr=(t,e)=>{Nc(t,e);const s=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,s},Rc=(t,e)=>kr(t,4).setFloat32(0,e,!1),Lc=(t,e)=>kr(t,8).setFloat64(0,e,!1),Ic=(t,e)=>kr(t,8).setBigInt64(0,e,!1),ni=new DataView(new ArrayBuffer(4)),Dc=t=>(ni.setFloat32(0,t),ni.getFloat32(0)===t),$t=(t,e)=>{switch(typeof e){case"string":Ce(t,119),Qe(t,e);break;case"number":wc(e)&&Ls(e)<=yc?(Ce(t,125),_r(t,e)):Dc(e)?(Ce(t,124),Rc(t,e)):(Ce(t,123),Lc(t,e));break;case"bigint":Ce(t,122),Ic(t,e);break;case"object":if(e===null)Ce(t,126);else if(ln(e)){Ce(t,117),Q(t,e.length);for(let s=0;s<e.length;s++)$t(t,e[s])}else if(e instanceof Uint8Array)Ce(t,116),ve(t,e);else{Ce(t,118);const s=Object.keys(e);Q(t,s.length);for(let n=0;n<s.length;n++){const i=s[n];Qe(t,i),$t(t,e[i])}}break;case"boolean":Ce(t,e?120:121);break;default:Ce(t,127)}};class ri extends bs{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Q(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const ii=t=>{t.count>0&&(_r(t.encoder,t.count===1?t.s:-t.s),t.count>1&&Q(t.encoder,t.count-2))};class Is{constructor(){this.encoder=new bs,this.s=0,this.count=0}write(e){this.s===e?this.count++:(ii(this),this.count=1,this.s=e)}toUint8Array(){return ii(this),xe(this.encoder)}}const oi=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);_r(t.encoder,e),t.count>1&&Q(t.encoder,t.count-2)}};class Tn{constructor(){this.encoder=new bs,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(oi(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return oi(this),xe(this.encoder)}}class Mc{constructor(){this.sarr=[],this.s="",this.lensE=new Is}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 bs;return this.sarr.push(this.s),this.s="",Qe(e,this.sarr.join("")),dn(e,this.lensE.toUint8Array()),xe(e)}}const ze=t=>new Error(t),Je=()=>{throw ze("Method unimplemented")},Ke=()=>{throw ze("Unexpected case")},eo=ze("Unexpected end of array"),to=ze("Integer out of Range");class un{constructor(e){this.arr=e,this.pos=0}}const st=t=>new un(t),Oc=t=>t.pos!==t.arr.length,Pc=(t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s},Te=t=>Pc(t,ne(t)),kt=t=>t.arr[t.pos++],ne=t=>{let e=0,s=1;const n=t.arr.length;for(;t.pos<n;){const i=t.arr[t.pos++];if(e=e+(i&vt)*s,s*=128,i<Fe)return e;if(e>Us)throw to}throw eo},Er=t=>{let e=t.arr[t.pos++],s=e&Yn,n=64;const i=(e&it)>0?-1:1;if((e&Fe)===0)return i*s;const a=t.arr.length;for(;t.pos<a;){if(e=t.arr[t.pos++],s=s+(e&vt)*n,n*=128,e<Fe)return i*s;if(s>Us)throw to}throw eo},Uc=t=>{let e=ne(t);if(e===0)return"";{let s=String.fromCodePoint(kt(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(kt(t));else for(;e>0;){const n=e<1e4?e:1e4,i=t.arr.subarray(t.pos,t.pos+n);t.pos+=n,s+=String.fromCodePoint.apply(null,i),e-=n}return decodeURIComponent(escape(s))}},Wc=t=>rs.decode(Te(t)),ot=rs?Wc:Uc,Sr=(t,e)=>{const s=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,s},Bc=t=>Sr(t,4).getFloat32(0,!1),Fc=t=>Sr(t,8).getFloat64(0,!1),$c=t=>Sr(t,8).getBigInt64(0,!1),zc=[t=>{},t=>null,Er,Bc,Fc,$c,t=>!1,t=>!0,ot,t=>{const e=ne(t),s={};for(let n=0;n<e;n++){const i=ot(t);s[i]=zt(t)}return s},t=>{const e=ne(t),s=[];for(let n=0;n<e;n++)s.push(zt(t));return s},Te],zt=t=>zc[127-kt(t)](t);class ai extends un{constructor(e,s){super(e),this.reader=s,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Oc(this)?this.count=ne(this)+1:this.count=-1),this.count--,this.s}}class Ds extends un{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Er(this);const e=Zi(this.s);this.count=1,e&&(this.s=-this.s,this.count=ne(this)+2)}return this.count--,this.s}}class An extends un{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Er(this),s=e&1;this.diff=Ye(e/2),this.count=1,s&&(this.count=ne(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Vc{constructor(e){this.decoder=new Ds(e),this.str=ot(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),s=this.str.slice(this.spos,e);return this.spos=e,s}}const Hc=crypto.getRandomValues.bind(crypto),qc=Math.random,so=()=>Hc(new Uint32Array(1))[0],Gc="10000000-1000-4000-8000"+-1e11,no=()=>Gc.replace(/[018]/g,t=>(t^so()&15>>t/4).toString(16)),lt=Date.now,Vt=t=>new Promise(t);Promise.all.bind(Promise);const Yc=t=>Promise.reject(t),jr=t=>Promise.resolve(t),li=t=>t===void 0?null:t;class Kc{constructor(){this.map=new Map}setItem(e,s){this.map.set(e,s)}getItem(e){return this.map.get(e)}}let ro=new Kc,Nr=!0;try{typeof localStorage<"u"&&localStorage&&(ro=localStorage,Nr=!1)}catch{}const io=ro,Jc=t=>Nr||addEventListener("storage",t),Xc=t=>Nr||removeEventListener("storage",t),us=Symbol("Equality"),oo=(t,e)=>{var s;return t===e||!!((s=t==null?void 0:t[us])!=null&&s.call(t,e))||!1},Zc=t=>typeof t=="object",Qc=Object.assign,ed=Object.keys,td=(t,e)=>{for(const s in t)e(t[s],s)},Ws=t=>ed(t).length,sd=t=>{for(const e in t)return!1;return!0},xs=(t,e)=>{for(const s in t)if(!e(t[s],s))return!1;return!0},Cr=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),nd=(t,e)=>t===e||Ws(t)===Ws(e)&&xs(t,(s,n)=>(s!==void 0||Cr(e,n))&&oo(e[n],s)),rd=Object.freeze,ao=t=>{for(const e in t){const s=t[e];(typeof s=="object"||typeof s=="function")&&ao(t[e])}return rd(t)},Tr=(t,e,s=0)=>{try{for(;s<t.length;s++)t[s](...e)}finally{s<t.length&&Tr(t,e,s+1)}},id=()=>{},od=t=>t,Pt=(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[us]!=null)return t[us](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)||!Pt(t.get(s),e.get(s)))return!1;break}case void 0:case Object:if(Ws(t)!==Ws(e))return!1;for(const s in t)if(!Cr(t,s)||!Pt(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(!Pt(t[s],e[s]))return!1;break;default:return!1}return!0},ad=(t,e)=>e.includes(t);var lo={};const Ht=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",co=typeof window<"u"&&typeof document<"u"&&!Ht;let Ze;const ld=()=>{if(Ze===void 0)if(Ht){Ze=Ue();const t=process.argv;let e=null;for(let s=0;s<t.length;s++){const n=t[s];n[0]==="-"?(e!==null&&Ze.set(e,""),e=n):e!==null&&(Ze.set(e,n),e=null)}e!==null&&Ze.set(e,"")}else typeof location=="object"?(Ze=Ue(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,s]=t.split("=");Ze.set(`--${si(e,"-")}`,s),Ze.set(`-${si(e,"-")}`,s)}})):Ze=Ue();return Ze},Xn=t=>ld().has(t),hs=t=>li(Ht?lo[t.toUpperCase().replaceAll("-","_")]:io.getItem(t)),uo=t=>Xn("--"+t)||hs(t)!==null,cd=uo("production"),dd=Ht&&ad(lo.FORCE_COLOR,["true","1","2"]),ud=dd||!Xn("--no-colors")&&!uo("no-color")&&(!Ht||process.stdout.isTTY)&&(!Ht||Xn("--color")||hs("COLORTERM")!==null||(hs("TERM")||"").includes("color")),ho=t=>new Uint8Array(t),hd=(t,e,s)=>new Uint8Array(t,e,s),fd=t=>new Uint8Array(t),pd=t=>{let e="";for(let s=0;s<t.byteLength;s++)e+=Qi(t[s]);return btoa(e)},gd=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),md=t=>{const e=atob(t),s=ho(e.length);for(let n=0;n<e.length;n++)s[n]=e.charCodeAt(n);return s},yd=t=>{const e=Buffer.from(t,"base64");return hd(e.buffer,e.byteOffset,e.byteLength)},fo=co?pd:gd,po=co?md:yd,wd=t=>{const e=ho(t.byteLength);return e.set(t),e};class bd{constructor(e,s){this.left=e,this.right=s}}const nt=(t,e)=>new bd(t,e),ci=t=>t.next()>=.5,Rn=(t,e,s)=>Ye(t.next()*(s+1-e)+e),go=(t,e,s)=>Ye(t.next()*(s+1-e)+e),Ar=(t,e,s)=>go(t,e,s),xd=t=>Qi(Ar(t,97,122)),vd=(t,e=0,s=20)=>{const n=Ar(t,e,s);let i="";for(let a=0;a<n;a++)i+=xd(t);return i},Ln=(t,e)=>e[Ar(t,0,e.length-1)],_d=Symbol("0schema");class kd{constructor(){this._rerrs=[]}extend(e,s,n,i=null){this._rerrs.push({path:e,expected:s,has:n,message:i})}toString(){const e=[];for(let s=this._rerrs.length-1;s>0;s--){const n=this._rerrs[s];e.push(Sc(" ",(this._rerrs.length-s)*2)+`${n.path!=null?`[${n.path}] `:""}${n.has} doesn't match ${n.expected}. ${n.message}`)}return e.join(`
208
+ `)}}const Zn=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[us]?oo(t,e):ln(t)?br(t,s=>Ji(e,n=>Zn(s,n))):Zc(t)?xs(t,(s,n)=>Zn(s,e[n])):!1;class Oe{extends(e){let[s,n]=[this.shape,e.shape];return this.constructor._dilutes&&([n,s]=[s,n]),Zn(s,n)}equals(e){return this.constructor===e.constructor&&Pt(this.shape,e.shape)}[_d](){return!0}[us](e){return this.equals(e)}validate(e){return this.check(e)}check(e,s){Je()}get nullable(){return Xt(this,mn)}get optional(){return new wo(this)}cast(e){return di(e,this),e}expect(e){return di(e,this),e}}We(Oe,"_dilutes",!1);class Rr extends Oe{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s=void 0){const n=(e==null?void 0:e.constructor)===this.shape&&(this._c==null||this._c(e));return!n&&(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")),n}}const ke=(t,e=null)=>new Rr(t,e);ke(Rr);class Lr extends Oe{constructor(e){super(),this.shape=e}check(e,s){const n=this.shape(e);return!n&&(s==null||s.extend(null,"custom prop",e==null?void 0:e.constructor.name,"failed to check custom prop")),n}}const Le=t=>new Lr(t);ke(Lr);class hn extends Oe{constructor(e){super(),this.shape=e}check(e,s){const n=this.shape.some(i=>i===e);return!n&&(s==null||s.extend(null,this.shape.join(" | "),e.toString())),n}}const fn=(...t)=>new hn(t),mo=ke(hn),Ed=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),yo=t=>{if(qt.check(t))return[Ed(t)];if(mo.check(t))return t.shape.map(e=>e+"");if(No.check(t))return["[+-]?\\d+.?\\d*"];if(Co.check(t))return[".*"];if(Fs.check(t))return t.shape.map(yo).flat(1);Ke()};class Sd extends Oe{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(yo).map(s=>`(${s.join("|")})`).join("")+"$")}check(e,s){const n=this._r.exec(e)!=null;return!n&&(s==null||s.extend(null,this._r.toString(),e.toString(),"String doesn't match string template.")),n}}ke(Sd);const jd=Symbol("optional");class wo extends Oe{constructor(e){super(),this.shape=e}check(e,s){const n=e===void 0||this.shape.check(e);return!n&&(s==null||s.extend(null,"undefined (optional)","()")),n}get[jd](){return!0}}const Nd=ke(wo);class Cd extends Oe{check(e,s){return s==null||s.extend(null,"never",typeof e),!1}}ke(Cd);const sn=class sn extends Oe{constructor(e,s=!1){super(),this.shape=e,this._isPartial=s}get partial(){return new sn(this.shape,!0)}check(e,s){return e==null?(s==null||s.extend(null,"object","null"),!1):xs(this.shape,(n,i)=>{const a=this._isPartial&&!Cr(e,i)||n.check(e[i],s);return!a&&(s==null||s.extend(i.toString(),n.toString(),typeof e[i],"Object property does not match")),a})}};We(sn,"_dilutes",!0);let Bs=sn;const Td=t=>new Bs(t),Ad=ke(Bs),Rd=Le(t=>t!=null&&(t.constructor===Object||t.constructor==null));class bo extends Oe{constructor(e,s){super(),this.shape={keys:e,values:s}}check(e,s){return e!=null&&xs(e,(n,i)=>{const a=this.shape.keys.check(i,s);return!a&&(s==null||s.extend(i+"","Record",typeof e,a?"Key doesn't match schema":"Value doesn't match value")),a&&this.shape.values.check(n,s)})}}const xo=(t,e)=>new bo(t,e),Ld=ke(bo);class vo extends Oe{constructor(e){super(),this.shape=e}check(e,s){return e!=null&&xs(this.shape,(n,i)=>{const a=n.check(e[i],s);return!a&&(s==null||s.extend(i.toString(),"Tuple",typeof n)),a})}}const Id=(...t)=>new vo(t);ke(vo);class _o extends Oe{constructor(e){super(),this.shape=e.length===1?e[0]:new pn(e)}check(e,s){const n=ln(e)&&br(e,i=>this.shape.check(i));return!n&&(s==null||s.extend(null,"Array","")),n}}const ko=(...t)=>new _o(t),Dd=ke(_o),Md=Le(t=>ln(t));class Eo extends Oe{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s){const n=e instanceof this.shape&&(this._c==null||this._c(e));return!n&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name)),n}}const Od=(t,e=null)=>new Eo(t,e);ke(Eo);const Pd=Od(Oe);class Ud extends Oe{constructor(e){super(),this.len=e.length-1,this.args=Id(...e.slice(-1)),this.res=e[this.len]}check(e,s){const n=e.constructor===Function&&e.length<=this.len;return!n&&(s==null||s.extend(null,"function",typeof e)),n}}const Wd=ke(Ud),Bd=Le(t=>typeof t=="function");class Fd extends Oe{constructor(e){super(),this.shape=e}check(e,s){const n=br(this.shape,i=>i.check(e,s));return!n&&(s==null||s.extend(null,"Intersectinon",typeof e)),n}}ke(Fd,t=>t.shape.length>0);class pn extends Oe{constructor(e){super(),this.shape=e}check(e,s){const n=Ji(this.shape,i=>i.check(e,s));return s==null||s.extend(null,"Union",typeof e),n}}We(pn,"_dilutes",!0);const Xt=(...t)=>t.findIndex(e=>Fs.check(e))>=0?Xt(...t.map(e=>fs(e)).map(e=>Fs.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new pn(t),Fs=ke(pn),So=()=>!0,$s=Le(So),$d=ke(Lr,t=>t.shape===So),Ir=Le(t=>typeof t=="bigint"),zd=Le(t=>t===Ir),jo=Le(t=>typeof t=="symbol");Le(t=>t===jo);const Ut=Le(t=>typeof t=="number"),No=Le(t=>t===Ut),qt=Le(t=>typeof t=="string"),Co=Le(t=>t===qt),gn=Le(t=>typeof t=="boolean"),Vd=Le(t=>t===gn),To=fn(void 0);ke(hn,t=>t.shape.length===1&&t.shape[0]===void 0);fn(void 0);const mn=fn(null),Hd=ke(hn,t=>t.shape.length===1&&t.shape[0]===null);ke(Uint8Array);ke(Rr,t=>t.shape===Uint8Array);const qd=Xt(Ut,qt,mn,To,Ir,gn,jo);(()=>{const t=ko($s),e=xo(qt,$s),s=Xt(Ut,qt,mn,gn,t,e);return t.shape=s,e.shape.values=s,s})();const fs=t=>{if(Pd.check(t))return t;if(Rd.check(t)){const e={};for(const s in t)e[s]=fs(t[s]);return Td(e)}else{if(Md.check(t))return Xt(...t.map(fs));if(qd.check(t))return fn(t);if(Bd.check(t))return ke(t)}Ke()},di=cd?()=>{}:(t,e)=>{const s=new kd;if(!e.check(t,s))throw ze(`Expected value to be of type ${e.constructor.name}.
209
+ ${s.toString()}`)};class Gd{constructor(e){this.patterns=[],this.$state=e}if(e,s){return this.patterns.push({if:fs(e),h:s}),this}else(e){return this.if($s,e)}done(){return(e,s)=>{for(let n=0;n<this.patterns.length;n++){const i=this.patterns[n];if(i.if.check(e))return i.h(e,s)}throw ze("Unhandled pattern")}}}const Yd=t=>new Gd(t),Ao=Yd($s).if(No,(t,e)=>Rn(e,ti,Us)).if(Co,(t,e)=>vd(e)).if(Vd,(t,e)=>ci(e)).if(zd,(t,e)=>BigInt(Rn(e,ti,Us))).if(Fs,(t,e)=>Mt(e,Ln(e,t.shape))).if(Ad,(t,e)=>{const s={};for(const n in t.shape){let i=t.shape[n];if(Nd.check(i)){if(ci(e))continue;i=i.shape}s[n]=Ao(i,e)}return s}).if(Dd,(t,e)=>{const s=[],n=go(e,0,42);for(let i=0;i<n;i++)s.push(Mt(e,t.shape));return s}).if(mo,(t,e)=>Ln(e,t.shape)).if(Hd,(t,e)=>null).if(Wd,(t,e)=>{const s=Mt(e,t.res);return()=>s}).if($d,(t,e)=>Mt(e,Ln(e,[Ut,qt,mn,To,Ir,gn,ko(Ut),xo(Xt("a","b","c"),Ut)]))).if(Ld,(t,e)=>{const s={},n=Rn(e,0,3);for(let i=0;i<n;i++){const a=Mt(e,t.shape.keys),c=Mt(e,t.shape.values);s[a]=c}return s}).done(),Mt=(t,e)=>Ao(fs(e),t),yn=typeof document<"u"?document:{};Le(t=>t.nodeType===Qd);typeof DOMParser<"u"&&new DOMParser;Le(t=>t.nodeType===Jd);Le(t=>t.nodeType===Xd);const Kd=t=>hc(t,(e,s)=>`${s}:${e};`).join(""),Jd=yn.ELEMENT_NODE,Xd=yn.TEXT_NODE,Zd=yn.DOCUMENT_NODE,Qd=yn.DOCUMENT_FRAGMENT_NODE;Le(t=>t.nodeType===Zd);const eu=JSON.stringify,dt=Symbol,Ge=dt(),Et=dt(),Ro=dt(),Dr=dt(),Lo=dt(),Io=dt(),Do=dt(),wn=dt(),bn=dt(),tu=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],s=[];let n=0;for(;n<t.length;n++){const a=t[n];if(a===void 0)break;if(a.constructor===String||a.constructor===Number)e.push(a);else if(a.constructor===Object)break}for(n>0&&s.push(e.join(""));n<t.length;n++){const a=t[n];a instanceof Symbol||s.push(a)}return s},ui=[Lo,Do,wn,Ro];let In=0,hi=lt();const su=(t,e)=>{const s=ui[In],n=hs("log"),i=n!==null&&(n==="*"||n==="true"||new RegExp(n,"gi").test(e));return In=(In+1)%ui.length,e+=": ",i?(...a)=>{var d;a.length===1&&((d=a[0])==null?void 0:d.constructor)===Function&&(a=a[0]());const c=lt(),l=c-hi;hi=c,t(s,e,bn,...a.map(p=>{switch(p!=null&&p.constructor===Uint8Array&&(p=Array.from(p)),typeof p){case"string":case"symbol":return p;default:return eu(p)}}),s," +"+l+"ms")}:id},nu={[Ge]:nt("font-weight","bold"),[Et]:nt("font-weight","normal"),[Ro]:nt("color","blue"),[Lo]:nt("color","green"),[Dr]:nt("color","grey"),[Io]:nt("color","red"),[Do]:nt("color","purple"),[wn]:nt("color","orange"),[bn]:nt("color","black")},ru=t=>{var c;t.length===1&&((c=t[0])==null?void 0:c.constructor)===Function&&(t=t[0]());const e=[],s=[],n=Ue();let i=[],a=0;for(;a<t.length;a++){const l=t[a],d=nu[l];if(d!==void 0)n.set(d.left,d.right);else{if(l===void 0)break;if(l.constructor===String||l.constructor===Number){const p=Kd(n);a>0||p.length>0?(e.push("%c"+l),s.push(p)):e.push(l)}else break}}for(a>0&&(i=s,i.unshift(e.join("")));a<t.length;a++){const l=t[a];l instanceof Symbol||i.push(l)}return i},Mo=ud?ru:tu,Oo=(...t)=>{console.log(...Mo(t)),Po.forEach(e=>e.print(t))},iu=(...t)=>{console.warn(...Mo(t)),t.unshift(wn),Po.forEach(e=>e.print(t))},Po=yt(),ou=t=>su(Oo,t),Uo=t=>({[Symbol.iterator](){return this},next:t}),au=(t,e)=>Uo(()=>{let s;do s=t.next();while(!s.done&&!e(s.value));return s}),Dn=(t,e)=>Uo(()=>{const{done:s,value:n}=t.next();return{done:s,value:s?void 0:e(n)}});class xn{constructor(e,s){this.clock=e,this.len=s}}class vs{constructor(){this.clients=new Map}}const Wo=(t,e,s)=>e.clients.forEach((n,i)=>{const a=t.doc.store.clients.get(i);if(a!=null){const c=a[a.length-1],l=c.id.clock+c.length;for(let d=0,p=n[d];d<n.length&&p.clock<l;p=n[++d])Qo(t,a,p.clock,p.len,s)}}),lu=(t,e)=>{let s=0,n=t.length-1;for(;s<=n;){const i=Ye((s+n)/2),a=t[i],c=a.clock;if(c<=e){if(e<c+a.len)return i;s=i+1}else n=i-1}return null},Bo=(t,e)=>{const s=t.clients.get(e.client);return s!==void 0&&lu(s,e.clock)!==null},Mr=t=>{t.clients.forEach(e=>{e.sort((i,a)=>i.clock-a.clock);let s,n;for(s=1,n=1;s<e.length;s++){const i=e[n-1],a=e[s];i.clock+i.len>=a.clock?e[n-1]=new xn(i.clock,Tt(i.len,a.clock+a.len-i.clock)):(n<s&&(e[n]=a),n++)}e.length=n})},cu=t=>{const e=new vs;for(let s=0;s<t.length;s++)t[s].clients.forEach((n,i)=>{if(!e.clients.has(i)){const a=n.slice();for(let c=s+1;c<t.length;c++)pc(a,t[c].clients.get(i)||[]);e.clients.set(i,a)}});return Mr(e),e},zs=(t,e,s,n)=>{$e(t.clients,e,()=>[]).push(new xn(s,n))},du=()=>new vs,uu=t=>{const e=du();return t.clients.forEach((s,n)=>{const i=[];for(let a=0;a<s.length;a++){const c=s[a];if(c.deleted){const l=c.id.clock;let d=c.length;if(a+1<s.length)for(let p=s[a+1];a+1<s.length&&p.deleted;p=s[++a+1])d+=p.length;i.push(new xn(l,d))}}i.length>0&&e.clients.set(n,i)}),e},Zt=(t,e)=>{Q(t.restEncoder,e.clients.size),at(e.clients.entries()).sort((s,n)=>n[0]-s[0]).forEach(([s,n])=>{t.resetDsCurVal(),Q(t.restEncoder,s);const i=n.length;Q(t.restEncoder,i);for(let a=0;a<i;a++){const c=n[a];t.writeDsClock(c.clock),t.writeDsLen(c.len)}})},Or=t=>{const e=new vs,s=ne(t.restDecoder);for(let n=0;n<s;n++){t.resetDsCurVal();const i=ne(t.restDecoder),a=ne(t.restDecoder);if(a>0){const c=$e(e.clients,i,()=>[]);for(let l=0;l<a;l++)c.push(new xn(t.readDsClock(),t.readDsLen()))}}return e},fi=(t,e,s)=>{const n=new vs,i=ne(t.restDecoder);for(let a=0;a<i;a++){t.resetDsCurVal();const c=ne(t.restDecoder),l=ne(t.restDecoder),d=s.clients.get(c)||[],p=Re(s,c);for(let w=0;w<l;w++){const u=t.readDsClock(),f=u+t.readDsLen();if(u<p){p<f&&zs(n,c,p,f-p);let g=et(d,u),y=d[g];for(!y.deleted&&y.id.clock<u&&(d.splice(g+1,0,Js(e,y,u-y.id.clock)),g++);g<d.length&&(y=d[g++],y.id.clock<f);)y.deleted||(f<y.id.clock+y.length&&d.splice(g,0,Js(e,y,f-y.id.clock)),y.delete(e))}else zs(n,c,u,f-u)}}if(n.clients.size>0){const a=new St;return Q(a.restEncoder,0),Zt(a,n),a.toUint8Array()}return null},Fo=so;class Qt extends Xi{constructor({guid:e=no(),collectionid:s=null,gc:n=!0,gcFilter:i=()=>!0,meta:a=null,autoLoad:c=!1,shouldLoad:l=!0}={}){super(),this.gc=n,this.gcFilter=i,this.clientID=Fo(),this.guid=e,this.collectionid=s,this.share=new Map,this.store=new Xo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=l,this.autoLoad=c,this.meta=a,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Vt(p=>{this.on("load",()=>{this.isLoaded=!0,p(this)})});const d=()=>Vt(p=>{const w=u=>{(u===void 0||u===!0)&&(this.off("sync",w),p())};this.on("sync",w)});this.on("sync",p=>{p===!1&&this.isSynced&&(this.whenSynced=d()),this.isSynced=p===void 0||p===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=d()}load(){const e=this._item;e!==null&&!this.shouldLoad&&me(e.parent.doc,s=>{s.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(at(this.subdocs).map(e=>e.guid))}transact(e,s=null){return me(this,e,s)}get(e,s=De){const n=$e(this.share,e,()=>{const a=new s;return a._integrate(this,null),a}),i=n.constructor;if(s!==De&&i!==s)if(i===De){const a=new s;a._map=n._map,n._map.forEach(c=>{for(;c!==null;c=c.left)c.parent=a}),a._start=n._start;for(let c=a._start;c!==null;c=c.right)c.parent=a;return a._length=n._length,this.share.set(e,a),a._integrate(this,null),a}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=""){return this.get(e,Bt)}getText(e=""){return this.get(e,Yt)}getMap(e=""){return this.get(e,jt)}getXmlElement(e=""){return this.get(e,Kt)}getXmlFragment(e=""){return this.get(e,Nt)}toJSON(){const e={};return this.share.forEach((s,n)=>{e[n]=s.toJSON()}),e}destroy(){this.isDestroyed=!0,at(this.subdocs).forEach(s=>s.destroy());const e=this._item;if(e!==null){this._item=null;const s=e.content;s.doc=new Qt({guid:this.guid,...s.opts,shouldLoad:!1}),s.doc._item=e,me(e.parent.doc,n=>{const i=s.doc;e.deleted||n.subdocsAdded.add(i),n.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class $o{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return ne(this.restDecoder)}readDsLen(){return ne(this.restDecoder)}}class zo extends $o{readLeftID(){return pe(ne(this.restDecoder),ne(this.restDecoder))}readRightID(){return pe(ne(this.restDecoder),ne(this.restDecoder))}readClient(){return ne(this.restDecoder)}readInfo(){return kt(this.restDecoder)}readString(){return ot(this.restDecoder)}readParentInfo(){return ne(this.restDecoder)===1}readTypeRef(){return ne(this.restDecoder)}readLen(){return ne(this.restDecoder)}readAny(){return zt(this.restDecoder)}readBuf(){return wd(Te(this.restDecoder))}readJSON(){return JSON.parse(ot(this.restDecoder))}readKey(){return ot(this.restDecoder)}}class hu{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=ne(this.restDecoder),this.dsCurrVal}readDsLen(){const e=ne(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Gt extends hu{constructor(e){super(e),this.keys=[],ne(e),this.keyClockDecoder=new An(Te(e)),this.clientDecoder=new Ds(Te(e)),this.leftClockDecoder=new An(Te(e)),this.rightClockDecoder=new An(Te(e)),this.infoDecoder=new ai(Te(e),kt),this.stringDecoder=new Vc(Te(e)),this.parentInfoDecoder=new ai(Te(e),kt),this.typeRefDecoder=new Ds(Te(e)),this.lenDecoder=new Ds(Te(e))}readLeftID(){return new Wt(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Wt(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 zt(this.restDecoder)}readBuf(){return Te(this.restDecoder)}readJSON(){return zt(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const s=this.stringDecoder.read();return this.keys.push(s),s}}}class Vo{constructor(){this.restEncoder=Ae()}toUint8Array(){return xe(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Q(this.restEncoder,e)}writeDsLen(e){Q(this.restEncoder,e)}}class _s extends Vo{writeLeftID(e){Q(this.restEncoder,e.client),Q(this.restEncoder,e.clock)}writeRightID(e){Q(this.restEncoder,e.client),Q(this.restEncoder,e.clock)}writeClient(e){Q(this.restEncoder,e)}writeInfo(e){ds(this.restEncoder,e)}writeString(e){Qe(this.restEncoder,e)}writeParentInfo(e){Q(this.restEncoder,e?1:0)}writeTypeRef(e){Q(this.restEncoder,e)}writeLen(e){Q(this.restEncoder,e)}writeAny(e){$t(this.restEncoder,e)}writeBuf(e){ve(this.restEncoder,e)}writeJSON(e){Qe(this.restEncoder,JSON.stringify(e))}writeKey(e){Qe(this.restEncoder,e)}}class Ho{constructor(){this.restEncoder=Ae(),this.dsCurrVal=0}toUint8Array(){return xe(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const s=e-this.dsCurrVal;this.dsCurrVal=e,Q(this.restEncoder,s)}writeDsLen(e){e===0&&Ke(),Q(this.restEncoder,e-1),this.dsCurrVal+=e}}class St extends Ho{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Tn,this.clientEncoder=new Is,this.leftClockEncoder=new Tn,this.rightClockEncoder=new Tn,this.infoEncoder=new ri(ds),this.stringEncoder=new Mc,this.parentInfoEncoder=new ri(ds),this.typeRefEncoder=new Is,this.lenEncoder=new Is}toUint8Array(){const e=Ae();return Q(e,0),ve(e,this.keyClockEncoder.toUint8Array()),ve(e,this.clientEncoder.toUint8Array()),ve(e,this.leftClockEncoder.toUint8Array()),ve(e,this.rightClockEncoder.toUint8Array()),ve(e,xe(this.infoEncoder)),ve(e,this.stringEncoder.toUint8Array()),ve(e,xe(this.parentInfoEncoder)),ve(e,this.typeRefEncoder.toUint8Array()),ve(e,this.lenEncoder.toUint8Array()),dn(e,xe(this.restEncoder)),xe(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){$t(this.restEncoder,e)}writeBuf(e){ve(this.restEncoder,e)}writeJSON(e){$t(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 fu=(t,e,s,n)=>{n=Tt(n,e[0].id.clock);const i=et(e,n);Q(t.restEncoder,e.length-i),t.writeClient(s),Q(t.restEncoder,n);const a=e[i];a.write(t,n-a.id.clock);for(let c=i+1;c<e.length;c++)e[c].write(t,0)},Pr=(t,e,s)=>{const n=new Map;s.forEach((i,a)=>{Re(e,a)>i&&n.set(a,i)}),vn(e).forEach((i,a)=>{s.has(a)||n.set(a,0)}),Q(t.restEncoder,n.size),at(n.entries()).sort((i,a)=>a[0]-i[0]).forEach(([i,a])=>{fu(t,e.clients.get(i),i,a)})},pu=(t,e)=>{const s=Ue(),n=ne(t.restDecoder);for(let i=0;i<n;i++){const a=ne(t.restDecoder),c=new Array(a),l=t.readClient();let d=ne(t.restDecoder);s.set(l,{i:0,refs:c});for(let p=0;p<a;p++){const w=t.readInfo();switch(cn&w){case 0:{const u=t.readLen();c[p]=new He(pe(l,d),u),d+=u;break}case 10:{const u=ne(t.restDecoder);c[p]=new qe(pe(l,d),u),d+=u;break}default:{const u=(w&(it|Fe))===0,f=new je(pe(l,d),null,(w&Fe)===Fe?t.readLeftID():null,null,(w&it)===it?t.readRightID():null,u?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,u&&(w&ls)===ls?t.readString():null,wa(t,w));c[p]=f,d+=f.length}}}}return s},gu=(t,e,s)=>{const n=[];let i=at(s.keys()).sort((g,y)=>g-y);if(i.length===0)return null;const a=()=>{if(i.length===0)return null;let g=s.get(i[i.length-1]);for(;g.refs.length===g.i;)if(i.pop(),i.length>0)g=s.get(i[i.length-1]);else return null;return g};let c=a();if(c===null)return null;const l=new Xo,d=new Map,p=(g,y)=>{const v=d.get(g);(v==null||v>y)&&d.set(g,y)};let w=c.refs[c.i++];const u=new Map,f=()=>{for(const g of n){const y=g.id.client,v=s.get(y);v?(v.i--,l.clients.set(y,v.refs.slice(v.i)),s.delete(y),v.i=0,v.refs=[]):l.clients.set(y,[g]),i=i.filter(A=>A!==y)}n.length=0};for(;;){if(w.constructor!==qe){const y=$e(u,w.id.client,()=>Re(e,w.id.client))-w.id.clock;if(y<0)n.push(w),p(w.id.client,w.id.clock-1),f();else{const v=w.getMissing(t,e);if(v!==null){n.push(w);const A=s.get(v)||{refs:[],i:0};if(A.refs.length===A.i)p(v,Re(e,v)),f();else{w=A.refs[A.i++];continue}}else(y===0||y<w.length)&&(w.integrate(t,y),u.set(w.id.client,w.id.clock+w.length))}}if(n.length>0)w=n.pop();else if(c!==null&&c.i<c.refs.length)w=c.refs[c.i++];else{if(c=a(),c===null)break;w=c.refs[c.i++]}}if(l.clients.size>0){const g=new St;return Pr(g,l,new Map),Q(g.restEncoder,0),{missing:d,update:g.toUint8Array()}}return null},mu=(t,e)=>Pr(t,e.doc.store,e.beforeState),yu=(t,e,s,n=new Gt(t))=>me(e,i=>{i.local=!1;let a=!1;const c=i.doc,l=c.store,d=pu(n,c),p=gu(i,l,d),w=l.pendingStructs;if(w){for(const[f,g]of w.missing)if(g<Re(l,f)){a=!0;break}if(p){for(const[f,g]of p.missing){const y=w.missing.get(f);(y==null||y>g)&&w.missing.set(f,g)}w.update=Vs([w.update,p.update])}}else l.pendingStructs=p;const u=fi(n,i,l);if(l.pendingDs){const f=new Gt(st(l.pendingDs));ne(f.restDecoder);const g=fi(f,i,l);u&&g?l.pendingDs=Vs([u,g]):l.pendingDs=u||g}else l.pendingDs=u;if(a){const f=l.pendingStructs.update;l.pendingStructs=null,qo(i.doc,f)}},s,!1),qo=(t,e,s,n=Gt)=>{const i=st(e);yu(i,t,s,new n(i))},Go=(t,e,s)=>qo(t,e,s,zo),wu=(t,e,s=new Map)=>{Pr(t,e.store,s),Zt(t,uu(e.store))},bu=(t,e=new Uint8Array([0]),s=new St)=>{const n=Yo(e);wu(s,t,n);const i=[s.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(Du(t.store.pendingStructs.update,e)),i.length>1){if(s.constructor===_s)return Lu(i.map((a,c)=>c===0?a:Ou(a)));if(s.constructor===St)return Vs(i)}return i[0]},Ur=(t,e)=>bu(t,e,new _s),xu=t=>{const e=new Map,s=ne(t.restDecoder);for(let n=0;n<s;n++){const i=ne(t.restDecoder),a=ne(t.restDecoder);e.set(i,a)}return e},Yo=t=>xu(new $o(st(t))),Ko=(t,e)=>(Q(t.restEncoder,e.size),at(e.entries()).sort((s,n)=>n[0]-s[0]).forEach(([s,n])=>{Q(t.restEncoder,s),Q(t.restEncoder,n)}),t),vu=(t,e)=>Ko(t,vn(e.store)),_u=(t,e=new Ho)=>(t instanceof Map?Ko(e,t):vu(e,t),e.toUint8Array()),ku=t=>_u(t,new Vo);class Eu{constructor(){this.l=[]}}const pi=()=>new Eu,gi=(t,e)=>t.l.push(e),mi=(t,e)=>{const s=t.l,n=s.length;t.l=s.filter(i=>e!==i),n===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},Jo=(t,e,s)=>Tr(t.l,[e,s]);class Wt{constructor(e,s){this.client=e,this.clock=s}}const Ss=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,pe=(t,e)=>new Wt(t,e),Su=t=>{for(const[e,s]of t.doc.share.entries())if(s===t)return e;throw Ke()},Ot=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Bo(e.ds,t.id),Qn=(t,e)=>{const s=$e(t.meta,Qn,yt),n=t.doc.store;s.has(e)||(e.sv.forEach((i,a)=>{i<Re(n,a)&&wt(t,pe(a,i))}),Wo(t,e.ds,i=>{}),s.add(e))};class Xo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const vn=t=>{const e=new Map;return t.clients.forEach((s,n)=>{const i=s[s.length-1];e.set(n,i.id.clock+i.length)}),e},Re=(t,e)=>{const s=t.clients.get(e);if(s===void 0)return 0;const n=s[s.length-1];return n.id.clock+n.length},Zo=(t,e)=>{let s=t.clients.get(e.id.client);if(s===void 0)s=[],t.clients.set(e.id.client,s);else{const n=s[s.length-1];if(n.id.clock+n.length!==e.id.clock)throw Ke()}s.push(e)},et=(t,e)=>{let s=0,n=t.length-1,i=t[n],a=i.id.clock;if(a===e)return n;let c=Ye(e/(a+i.length-1)*n);for(;s<=n;){if(i=t[c],a=i.id.clock,a<=e){if(e<a+i.length)return c;s=c+1}else n=c-1;c=Ye((s+n)/2)}throw Ke()},ju=(t,e)=>{const s=t.clients.get(e.client);return s[et(s,e.clock)]},Mn=ju,er=(t,e,s)=>{const n=et(e,s),i=e[n];return i.id.clock<s&&i instanceof je?(e.splice(n+1,0,Js(t,i,s-i.id.clock)),n+1):n},wt=(t,e)=>{const s=t.doc.store.clients.get(e.client);return s[er(t,s,e.clock)]},yi=(t,e,s)=>{const n=e.clients.get(s.client),i=et(n,s.clock),a=n[i];return s.clock!==a.id.clock+a.length-1&&a.constructor!==He&&n.splice(i+1,0,Js(t,a,s.clock-a.id.clock+1)),a},Nu=(t,e,s)=>{const n=t.clients.get(e.id.client);n[et(n,e.id.clock)]=s},Qo=(t,e,s,n,i)=>{if(n===0)return;const a=s+n;let c=er(t,e,s),l;do l=e[c++],a<l.id.clock+l.length&&er(t,e,a),i(l);while(c<e.length&&e[c].id.clock<a)};class Cu{constructor(e,s,n){this.doc=e,this.deleteSet=new vs,this.beforeState=vn(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=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const wi=(t,e)=>e.deleteSet.clients.size===0&&!fc(e.afterState,(s,n)=>e.beforeState.get(n)!==s)?!1:(Mr(e.deleteSet),mu(t,e),Zt(t,e.deleteSet),!0),bi=(t,e,s)=>{const n=e._item;(n===null||n.id.clock<(t.beforeState.get(n.id.client)||0)&&!n.deleted)&&$e(t.changed,e,yt).add(s)},Ms=(t,e)=>{let s=t[e],n=t[e-1],i=e;for(;i>0;s=n,n=t[--i-1]){if(n.deleted===s.deleted&&n.constructor===s.constructor&&n.mergeWith(s)){s instanceof je&&s.parentSub!==null&&s.parent._map.get(s.parentSub)===s&&s.parent._map.set(s.parentSub,n);continue}break}const a=e-i;return a&&t.splice(e+1-a,a),a},Tu=(t,e,s)=>{for(const[n,i]of t.clients.entries()){const a=e.clients.get(n);for(let c=i.length-1;c>=0;c--){const l=i[c],d=l.clock+l.len;for(let p=et(a,l.clock),w=a[p];p<a.length&&w.id.clock<d;w=a[++p]){const u=a[p];if(l.clock+l.len<=u.id.clock)break;u instanceof je&&u.deleted&&!u.keep&&s(u)&&u.gc(e,!1)}}}},Au=(t,e)=>{t.clients.forEach((s,n)=>{const i=e.clients.get(n);for(let a=s.length-1;a>=0;a--){const c=s[a],l=vr(i.length-1,1+et(i,c.clock+c.len-1));for(let d=l,p=i[d];d>0&&p.id.clock>=c.clock;p=i[d])d-=1+Ms(i,d)}})},ea=(t,e)=>{if(e<t.length){const s=t[e],n=s.doc,i=n.store,a=s.deleteSet,c=s._mergeStructs;try{Mr(a),s.afterState=vn(s.doc.store),n.emit("beforeObserverCalls",[s,n]);const l=[];s.changed.forEach((d,p)=>l.push(()=>{(p._item===null||!p._item.deleted)&&p._callObserver(s,d)})),l.push(()=>{s.changedParentTypes.forEach((d,p)=>{p._dEH.l.length>0&&(p._item===null||!p._item.deleted)&&(d=d.filter(w=>w.target._item===null||!w.target._item.deleted),d.forEach(w=>{w.currentTarget=p,w._path=null}),d.sort((w,u)=>w.path.length-u.path.length),l.push(()=>{Jo(p._dEH,d,s)}))}),l.push(()=>n.emit("afterTransaction",[s,n])),l.push(()=>{s._needFormattingCleanup&&Ju(s)})}),Tr(l,[])}finally{n.gc&&Tu(a,i,n.gcFilter),Au(a,i),s.afterState.forEach((w,u)=>{const f=s.beforeState.get(u)||0;if(f!==w){const g=i.clients.get(u),y=Tt(et(g,f),1);for(let v=g.length-1;v>=y;)v-=1+Ms(g,v)}});for(let w=c.length-1;w>=0;w--){const{client:u,clock:f}=c[w].id,g=i.clients.get(u),y=et(g,f);y+1<g.length&&Ms(g,y+1)>1||y>0&&Ms(g,y)}if(!s.local&&s.afterState.get(n.clientID)!==s.beforeState.get(n.clientID)&&(Oo(wn,Ge,"[yjs] ",Et,Io,"Changed the client-id because another client seems to be using it."),n.clientID=Fo()),n.emit("afterTransactionCleanup",[s,n]),n._observers.has("update")){const w=new _s;wi(w,s)&&n.emit("update",[w.toUint8Array(),s.origin,n,s])}if(n._observers.has("updateV2")){const w=new St;wi(w,s)&&n.emit("updateV2",[w.toUint8Array(),s.origin,n,s])}const{subdocsAdded:l,subdocsLoaded:d,subdocsRemoved:p}=s;(l.size>0||p.size>0||d.size>0)&&(l.forEach(w=>{w.clientID=n.clientID,w.collectionid==null&&(w.collectionid=n.collectionid),n.subdocs.add(w)}),p.forEach(w=>n.subdocs.delete(w)),n.emit("subdocs",[{loaded:d,added:l,removed:p},n,s]),p.forEach(w=>w.destroy())),t.length<=e+1?(n._transactionCleanups=[],n.emit("afterAllTransactions",[n,t])):ea(t,e+1)}}},me=(t,e,s=null,n=!0)=>{const i=t._transactionCleanups;let a=!1,c=null;t._transaction===null&&(a=!0,t._transaction=new Cu(t,s,n),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{c=e(t._transaction)}finally{if(a){const l=t._transaction===i[0];t._transaction=null,l&&ea(i,0)}}return c};function*Ru(t){const e=ne(t.restDecoder);for(let s=0;s<e;s++){const n=ne(t.restDecoder),i=t.readClient();let a=ne(t.restDecoder);for(let c=0;c<n;c++){const l=t.readInfo();if(l===10){const d=ne(t.restDecoder);yield new qe(pe(i,a),d),a+=d}else if((cn&l)!==0){const d=(l&(it|Fe))===0,p=new je(pe(i,a),null,(l&Fe)===Fe?t.readLeftID():null,null,(l&it)===it?t.readRightID():null,d?t.readParentInfo()?t.readString():t.readLeftID():null,d&&(l&ls)===ls?t.readString():null,wa(t,l));yield p,a+=p.length}else{const d=t.readLen();yield new He(pe(i,a),d),a+=d}}}}class Wr{constructor(e,s){this.gen=Ru(e),this.curr=null,this.done=!1,this.filterSkips=s,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===qe);return this.curr}}class Br{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Lu=t=>Vs(t,zo,_s),Iu=(t,e)=>{if(t.constructor===He){const{client:s,clock:n}=t.id;return new He(pe(s,n+e),t.length-e)}else if(t.constructor===qe){const{client:s,clock:n}=t.id;return new qe(pe(s,n+e),t.length-e)}else{const s=t,{client:n,clock:i}=s.id;return new je(pe(n,i+e),null,pe(n,i+e-1),null,s.rightOrigin,s.parent,s.parentSub,s.content.splice(e))}},Vs=(t,e=Gt,s=St)=>{if(t.length===1)return t[0];const n=t.map(w=>new e(st(w)));let i=n.map(w=>new Wr(w,!0)),a=null;const c=new s,l=new Br(c);for(;i=i.filter(f=>f.curr!==null),i.sort((f,g)=>{if(f.curr.id.client===g.curr.id.client){const y=f.curr.id.clock-g.curr.id.clock;return y===0?f.curr.constructor===g.curr.constructor?0:f.curr.constructor===qe?1:-1:y}else return g.curr.id.client-f.curr.id.client}),i.length!==0;){const w=i[0],u=w.curr.id.client;if(a!==null){let f=w.curr,g=!1;for(;f!==null&&f.id.clock+f.length<=a.struct.id.clock+a.struct.length&&f.id.client>=a.struct.id.client;)f=w.next(),g=!0;if(f===null||f.id.client!==u||g&&f.id.clock>a.struct.id.clock+a.struct.length)continue;if(u!==a.struct.id.client)ft(l,a.struct,a.offset),a={struct:f,offset:0},w.next();else if(a.struct.id.clock+a.struct.length<f.id.clock)if(a.struct.constructor===qe)a.struct.length=f.id.clock+f.length-a.struct.id.clock;else{ft(l,a.struct,a.offset);const y=f.id.clock-a.struct.id.clock-a.struct.length;a={struct:new qe(pe(u,a.struct.id.clock+a.struct.length),y),offset:0}}else{const y=a.struct.id.clock+a.struct.length-f.id.clock;y>0&&(a.struct.constructor===qe?a.struct.length-=y:f=Iu(f,y)),a.struct.mergeWith(f)||(ft(l,a.struct,a.offset),a={struct:f,offset:0},w.next())}}else a={struct:w.curr,offset:0},w.next();for(let f=w.curr;f!==null&&f.id.client===u&&f.id.clock===a.struct.id.clock+a.struct.length&&f.constructor!==qe;f=w.next())ft(l,a.struct,a.offset),a={struct:f,offset:0}}a!==null&&(ft(l,a.struct,a.offset),a=null),Fr(l);const d=n.map(w=>Or(w)),p=cu(d);return Zt(c,p),c.toUint8Array()},Du=(t,e,s=Gt,n=St)=>{const i=Yo(e),a=new n,c=new Br(a),l=new s(st(t)),d=new Wr(l,!1);for(;d.curr;){const w=d.curr,u=w.id.client,f=i.get(u)||0;if(d.curr.constructor===qe){d.next();continue}if(w.id.clock+w.length>f)for(ft(c,w,Tt(f-w.id.clock,0)),d.next();d.curr&&d.curr.id.client===u;)ft(c,d.curr,0),d.next();else for(;d.curr&&d.curr.id.client===u&&d.curr.id.clock+d.curr.length<=f;)d.next()}Fr(c);const p=Or(l);return Zt(a,p),a.toUint8Array()},ta=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:xe(t.encoder.restEncoder)}),t.encoder.restEncoder=Ae(),t.written=0)},ft=(t,e,s)=>{t.written>0&&t.currClient!==e.id.client&&ta(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),Q(t.encoder.restEncoder,e.id.clock+s)),e.write(t.encoder,s),t.written++},Fr=t=>{ta(t);const e=t.encoder.restEncoder;Q(e,t.clientStructs.length);for(let s=0;s<t.clientStructs.length;s++){const n=t.clientStructs[s];Q(e,n.written),dn(e,n.restEncoder)}},Mu=(t,e,s,n)=>{const i=new s(st(t)),a=new Wr(i,!1),c=new n,l=new Br(c);for(let p=a.curr;p!==null;p=a.next())ft(l,e(p),0);Fr(l);const d=Or(i);return Zt(c,d),c.toUint8Array()},Ou=t=>Mu(t,od,Gt,_s),xi="You must not compute changes after the event-handler fired.";class _n{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=Pu(this.currentTarget,this.target))}deletes(e){return Bo(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw ze(xi);const e=new Map,s=this.target;this.transaction.changed.get(s).forEach(i=>{if(i!==null){const a=s._map.get(i);let c,l;if(this.adds(a)){let d=a.left;for(;d!==null&&this.adds(d);)d=d.left;if(this.deletes(a))if(d!==null&&this.deletes(d))c="delete",l=jn(d.content.getContent());else return;else d!==null&&this.deletes(d)?(c="update",l=jn(d.content.getContent())):(c="add",l=void 0)}else if(this.deletes(a))c="delete",l=jn(a.content.getContent());else return;e.set(i,{action:c,oldValue:l})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw ze(xi);const s=this.target,n=yt(),i=yt(),a=[];if(e={added:n,deleted:i,delta:a,keys:this.keys},this.transaction.changed.get(s).has(null)){let l=null;const d=()=>{l&&a.push(l)};for(let p=s._start;p!==null;p=p.right)p.deleted?this.deletes(p)&&!this.adds(p)&&((l===null||l.delete===void 0)&&(d(),l={delete:0}),l.delete+=p.length,i.add(p)):this.adds(p)?((l===null||l.insert===void 0)&&(d(),l={insert:[]}),l.insert=l.insert.concat(p.content.getContent()),n.add(p)):((l===null||l.retain===void 0)&&(d(),l={retain:0}),l.retain+=p.length);l!==null&&l.retain===void 0&&d()}this._changes=e}return e}}const Pu=(t,e)=>{const s=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)s.unshift(e._item.parentSub);else{let n=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(n+=i.length),i=i.right;s.unshift(n)}e=e._item.parent}return s},Me=()=>{iu("Invalid access: Add Yjs type to a document before reading data.")},sa=80;let $r=0;class Uu{constructor(e,s){e.marker=!0,this.p=e,this.index=s,this.timestamp=$r++}}const Wu=t=>{t.timestamp=$r++},na=(t,e,s)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=s,t.timestamp=$r++},Bu=(t,e,s)=>{if(t.length>=sa){const n=t.reduce((i,a)=>i.timestamp<a.timestamp?i:a);return na(n,e,s),n}else{const n=new Uu(e,s);return t.push(n),n}},kn=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const s=t._searchMarker.length===0?null:t._searchMarker.reduce((a,c)=>Ls(e-a.index)<Ls(e-c.index)?a:c);let n=t._start,i=0;for(s!==null&&(n=s.p,i=s.index,Wu(s));n.right!==null&&i<e;){if(!n.deleted&&n.countable){if(e<i+n.length)break;i+=n.length}n=n.right}for(;n.left!==null&&i>e;)n=n.left,!n.deleted&&n.countable&&(i-=n.length);for(;n.left!==null&&n.left.id.client===n.id.client&&n.left.id.clock+n.left.length===n.id.clock;)n=n.left,!n.deleted&&n.countable&&(i-=n.length);return s!==null&&Ls(s.index-i)<n.parent.length/sa?(na(s,n,i),s):Bu(t._searchMarker,n,i)},ps=(t,e,s)=>{for(let n=t.length-1;n>=0;n--){const i=t[n];if(s>0){let a=i.p;for(a.marker=!1;a&&(a.deleted||!a.countable);)a=a.left,a&&!a.deleted&&a.countable&&(i.index-=a.length);if(a===null||a.marker===!0){t.splice(n,1);continue}i.p=a,a.marker=!0}(e<i.index||s>0&&e===i.index)&&(i.index=Tt(e,i.index+s))}},En=(t,e,s)=>{const n=t,i=e.changedParentTypes;for(;$e(i,t,()=>[]).push(s),t._item!==null;)t=t._item.parent;Jo(n._eH,s,e)};class De{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=pi(),this._dEH=pi(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,s){this.doc=e,this._item=s}_copy(){throw Je()}clone(){throw Je()}_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){gi(this._eH,e)}observeDeep(e){gi(this._dEH,e)}unobserve(e){mi(this._eH,e)}unobserveDeep(e){mi(this._dEH,e)}toJSON(){}}const ra=(t,e,s)=>{t.doc??Me(),e<0&&(e=t._length+e),s<0&&(s=t._length+s);let n=s-e;const i=[];let a=t._start;for(;a!==null&&n>0;){if(a.countable&&!a.deleted){const c=a.content.getContent();if(c.length<=e)e-=c.length;else{for(let l=e;l<c.length&&n>0;l++)i.push(c[l]),n--;e=0}}a=a.right}return i},ia=t=>{t.doc??Me();const e=[];let s=t._start;for(;s!==null;){if(s.countable&&!s.deleted){const n=s.content.getContent();for(let i=0;i<n.length;i++)e.push(n[i])}s=s.right}return e},gs=(t,e)=>{let s=0,n=t._start;for(t.doc??Me();n!==null;){if(n.countable&&!n.deleted){const i=n.content.getContent();for(let a=0;a<i.length;a++)e(i[a],s++,t)}n=n.right}},oa=(t,e)=>{const s=[];return gs(t,(n,i)=>{s.push(e(n,i,t))}),s},Fu=t=>{let e=t._start,s=null,n=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(),n=0,e=e.right}const i=s[n++];return s.length<=n&&(s=null),{done:!1,value:i}}}},aa=(t,e)=>{t.doc??Me();const s=kn(t,e);let n=t._start;for(s!==null&&(n=s.p,e-=s.index);n!==null;n=n.right)if(!n.deleted&&n.countable){if(e<n.length)return n.content.getContent()[e];e-=n.length}},Hs=(t,e,s,n)=>{let i=s;const a=t.doc,c=a.clientID,l=a.store,d=s===null?e._start:s.right;let p=[];const w=()=>{p.length>0&&(i=new je(pe(c,Re(l,c)),i,i&&i.lastId,d,d&&d.id,e,null,new Ct(p)),i.integrate(t,0),p=[])};n.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(w(),u.constructor){case Uint8Array:case ArrayBuffer:i=new je(pe(c,Re(l,c)),i,i&&i.lastId,d,d&&d.id,e,null,new ks(new Uint8Array(u))),i.integrate(t,0);break;case Qt:i=new je(pe(c,Re(l,c)),i,i&&i.lastId,d,d&&d.id,e,null,new Es(u)),i.integrate(t,0);break;default:if(u instanceof De)i=new je(pe(c,Re(l,c)),i,i&&i.lastId,d,d&&d.id,e,null,new ut(u)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),w()},la=()=>ze("Length exceeded!"),ca=(t,e,s,n)=>{if(s>e._length)throw la();if(s===0)return e._searchMarker&&ps(e._searchMarker,s,n.length),Hs(t,e,null,n);const i=s,a=kn(e,s);let c=e._start;for(a!==null&&(c=a.p,s-=a.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&&wt(t,pe(c.id.client,c.id.clock+s));break}s-=c.length}return e._searchMarker&&ps(e._searchMarker,i,n.length),Hs(t,e,c,n)},$u=(t,e,s)=>{let i=(e._searchMarker||[]).reduce((a,c)=>c.index>a.index?c:a,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return Hs(t,e,i,s)},da=(t,e,s,n)=>{if(n===0)return;const i=s,a=n,c=kn(e,s);let l=e._start;for(c!==null&&(l=c.p,s-=c.index);l!==null&&s>0;l=l.right)!l.deleted&&l.countable&&(s<l.length&&wt(t,pe(l.id.client,l.id.clock+s)),s-=l.length);for(;n>0&&l!==null;)l.deleted||(n<l.length&&wt(t,pe(l.id.client,l.id.clock+n)),l.delete(t),n-=l.length),l=l.right;if(n>0)throw la();e._searchMarker&&ps(e._searchMarker,i,-a+n)},qs=(t,e,s)=>{const n=e._map.get(s);n!==void 0&&n.delete(t)},zr=(t,e,s,n)=>{const i=e._map.get(s)||null,a=t.doc,c=a.clientID;let l;if(n==null)l=new Ct([n]);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Ct([n]);break;case Uint8Array:l=new ks(n);break;case Qt:l=new Es(n);break;default:if(n instanceof De)l=new ut(n);else throw new Error("Unexpected content type")}new je(pe(c,Re(a.store,c)),i,i&&i.lastId,null,null,e,s,l).integrate(t,0)},Vr=(t,e)=>{t.doc??Me();const s=t._map.get(e);return s!==void 0&&!s.deleted?s.content.getContent()[s.length-1]:void 0},ua=t=>{const e={};return t.doc??Me(),t._map.forEach((s,n)=>{s.deleted||(e[n]=s.content.getContent()[s.length-1])}),e},ha=(t,e)=>{t.doc??Me();const s=t._map.get(e);return s!==void 0&&!s.deleted},zu=(t,e)=>{const s={};return t._map.forEach((n,i)=>{let a=n;for(;a!==null&&(!e.sv.has(a.id.client)||a.id.clock>=(e.sv.get(a.id.client)||0));)a=a.left;a!==null&&Ot(a,e)&&(s[i]=a.content.getContent()[a.length-1])}),s},js=t=>(t.doc??Me(),au(t._map.entries(),e=>!e[1].deleted));class Vu extends _n{}class Bt extends De{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const s=new Bt;return s.push(e),s}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Bt}clone(){const e=new Bt;return e.insert(0,this.toArray().map(s=>s instanceof De?s.clone():s)),e}get length(){return this.doc??Me(),this._length}_callObserver(e,s){super._callObserver(e,s),En(this,e,new Vu(this,e))}insert(e,s){this.doc!==null?me(this.doc,n=>{ca(n,this,e,s)}):this._prelimContent.splice(e,0,...s)}push(e){this.doc!==null?me(this.doc,s=>{$u(s,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,s=1){this.doc!==null?me(this.doc,n=>{da(n,this,e,s)}):this._prelimContent.splice(e,s)}get(e){return aa(this,e)}toArray(){return ia(this)}slice(e=0,s=this.length){return ra(this,e,s)}toJSON(){return this.map(e=>e instanceof De?e.toJSON():e)}map(e){return oa(this,e)}forEach(e){gs(this,e)}[Symbol.iterator](){return Fu(this)}_write(e){e.writeTypeRef(gh)}}const Hu=t=>new Bt;class qu extends _n{constructor(e,s,n){super(e,s),this.keysChanged=n}}class jt extends De{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((n,i)=>{this.set(i,n)}),this._prelimContent=null}_copy(){return new jt}clone(){const e=new jt;return this.forEach((s,n)=>{e.set(n,s instanceof De?s.clone():s)}),e}_callObserver(e,s){En(this,e,new qu(this,e,s))}toJSON(){this.doc??Me();const e={};return this._map.forEach((s,n)=>{if(!s.deleted){const i=s.content.getContent()[s.length-1];e[n]=i instanceof De?i.toJSON():i}}),e}get size(){return[...js(this)].length}keys(){return Dn(js(this),e=>e[0])}values(){return Dn(js(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Dn(js(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Me(),this._map.forEach((s,n)=>{s.deleted||e(s.content.getContent()[s.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?me(this.doc,s=>{qs(s,this,e)}):this._prelimContent.delete(e)}set(e,s){return this.doc!==null?me(this.doc,n=>{zr(n,this,e,s)}):this._prelimContent.set(e,s),s}get(e){return Vr(this,e)}has(e){return ha(this,e)}clear(){this.doc!==null?me(this.doc,e=>{this.forEach(function(s,n,i){qs(e,i,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(mh)}}const Gu=t=>new jt,pt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&nd(t,e);class tr{constructor(e,s,n,i){this.left=e,this.right=s,this.index=n,this.currentAttributes=i}forward(){switch(this.right===null&&Ke(),this.right.content.constructor){case Ne:this.right.deleted||es(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const vi=(t,e,s)=>{for(;e.right!==null&&s>0;){switch(e.right.content.constructor){case Ne:e.right.deleted||es(e.currentAttributes,e.right.content);break;default:e.right.deleted||(s<e.right.length&&wt(t,pe(e.right.id.client,e.right.id.clock+s)),e.index+=e.right.length,s-=e.right.length);break}e.left=e.right,e.right=e.right.right}return e},Ns=(t,e,s,n)=>{const i=new Map,a=n?kn(e,s):null;if(a){const c=new tr(a.p.left,a.p,a.index,i);return vi(t,c,s-a.index)}else{const c=new tr(null,e._start,0,i);return vi(t,c,s)}},fa=(t,e,s,n)=>{for(;s.right!==null&&(s.right.deleted===!0||s.right.content.constructor===Ne&&pt(n.get(s.right.content.key),s.right.content.value));)s.right.deleted||n.delete(s.right.content.key),s.forward();const i=t.doc,a=i.clientID;n.forEach((c,l)=>{const d=s.left,p=s.right,w=new je(pe(a,Re(i.store,a)),d,d&&d.lastId,p,p&&p.id,e,null,new Ne(l,c));w.integrate(t,0),s.right=w,s.forward()})},es=(t,e)=>{const{key:s,value:n}=e;n===null?t.delete(s):t.set(s,n)},pa=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Ne&&pt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},ga=(t,e,s,n)=>{const i=t.doc,a=i.clientID,c=new Map;for(const l in n){const d=n[l],p=s.currentAttributes.get(l)??null;if(!pt(p,d)){c.set(l,p);const{left:w,right:u}=s;s.right=new je(pe(a,Re(i.store,a)),w,w&&w.lastId,u,u&&u.id,e,null,new Ne(l,d)),s.right.integrate(t,0),s.forward()}}return c},On=(t,e,s,n,i)=>{s.currentAttributes.forEach((f,g)=>{i[g]===void 0&&(i[g]=null)});const a=t.doc,c=a.clientID;pa(s,i);const l=ga(t,e,s,i),d=n.constructor===String?new tt(n):n instanceof De?new ut(n):new At(n);let{left:p,right:w,index:u}=s;e._searchMarker&&ps(e._searchMarker,s.index,d.getLength()),w=new je(pe(c,Re(a.store,c)),p,p&&p.lastId,w,w&&w.id,e,null,d),w.integrate(t,0),s.right=w,s.index=u,s.forward(),fa(t,e,s,l)},_i=(t,e,s,n,i)=>{const a=t.doc,c=a.clientID;pa(s,i);const l=ga(t,e,s,i);e:for(;s.right!==null&&(n>0||l.size>0&&(s.right.deleted||s.right.content.constructor===Ne));){if(!s.right.deleted)switch(s.right.content.constructor){case Ne:{const{key:d,value:p}=s.right.content,w=i[d];if(w!==void 0){if(pt(w,p))l.delete(d);else{if(n===0)break e;l.set(d,p)}s.right.delete(t)}else s.currentAttributes.set(d,p);break}default:n<s.right.length&&wt(t,pe(s.right.id.client,s.right.id.clock+n)),n-=s.right.length;break}s.forward()}if(n>0){let d="";for(;n>0;n--)d+=`
210
+ `;s.right=new je(pe(c,Re(a.store,c)),s.left,s.left&&s.left.lastId,s.right,s.right&&s.right.id,e,null,new tt(d)),s.right.integrate(t,0),s.forward()}fa(t,e,s,l)},ma=(t,e,s,n,i)=>{let a=e;const c=Ue();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===Ne){const p=a.content;c.set(p.key,p)}a=a.right}let l=0,d=!1;for(;e!==a;){if(s===e&&(d=!0),!e.deleted){const p=e.content;switch(p.constructor){case Ne:{const{key:w,value:u}=p,f=n.get(w)??null;(c.get(w)!==p||f===u)&&(e.delete(t),l++,!d&&(i.get(w)??null)===u&&f!==u&&(f===null?i.delete(w):i.set(w,f))),!d&&!e.deleted&&es(i,p);break}}}e=e.right}return l},Yu=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const s=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Ne){const n=e.content.key;s.has(n)?e.delete(t):s.add(n)}e=e.left}},Ku=t=>{let e=0;return me(t.doc,s=>{let n=t._start,i=t._start,a=Ue();const c=Gn(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Ne:es(c,i.content);break;default:e+=ma(s,n,i,a,c),a=Gn(c),n=i;break}i=i.right}}),e},Ju=t=>{const e=new Set,s=t.doc;for(const[n,i]of t.afterState.entries()){const a=t.beforeState.get(n)||0;i!==a&&Qo(t,s.store.clients.get(n),a,i,c=>{!c.deleted&&c.content.constructor===Ne&&c.constructor!==He&&e.add(c.parent)})}me(s,n=>{Wo(t,t.deleteSet,i=>{if(i instanceof He||!i.parent._hasFormatting||e.has(i.parent))return;const a=i.parent;i.content.constructor===Ne?e.add(a):Yu(n,i)});for(const i of e)Ku(i)})},ki=(t,e,s)=>{const n=s,i=Gn(e.currentAttributes),a=e.right;for(;s>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case ut:case At:case tt:s<e.right.length&&wt(t,pe(e.right.id.client,e.right.id.clock+s)),s-=e.right.length,e.right.delete(t);break}e.forward()}a&&ma(t,a,e.right,i,e.currentAttributes);const c=(e.left||e.right).parent;return c._searchMarker&&ps(c._searchMarker,e.index,-n+s),e};class Xu extends _n{constructor(e,s,n){super(e,s),this.childListChanged=!1,this.keysChanged=new Set,n.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=[];me(e,n=>{const i=new Map,a=new Map;let c=this.target._start,l=null;const d={};let p="",w=0,u=0;const f=()=>{if(l!==null){let g=null;switch(l){case"delete":u>0&&(g={delete:u}),u=0;break;case"insert":(typeof p=="object"||p.length>0)&&(g={insert:p},i.size>0&&(g.attributes={},i.forEach((y,v)=>{y!==null&&(g.attributes[v]=y)}))),p="";break;case"retain":w>0&&(g={retain:w},sd(d)||(g.attributes=Qc({},d))),w=0;break}g&&s.push(g),l=null}};for(;c!==null;){switch(c.content.constructor){case ut:case At:this.adds(c)?this.deletes(c)||(f(),l="insert",p=c.content.getContent()[0],f()):this.deletes(c)?(l!=="delete"&&(f(),l="delete"),u+=1):c.deleted||(l!=="retain"&&(f(),l="retain"),w+=1);break;case tt:this.adds(c)?this.deletes(c)||(l!=="insert"&&(f(),l="insert"),p+=c.content.str):this.deletes(c)?(l!=="delete"&&(f(),l="delete"),u+=c.length):c.deleted||(l!=="retain"&&(f(),l="retain"),w+=c.length);break;case Ne:{const{key:g,value:y}=c.content;if(this.adds(c)){if(!this.deletes(c)){const v=i.get(g)??null;pt(v,y)?y!==null&&c.delete(n):(l==="retain"&&f(),pt(y,a.get(g)??null)?delete d[g]:d[g]=y)}}else if(this.deletes(c)){a.set(g,y);const v=i.get(g)??null;pt(v,y)||(l==="retain"&&f(),d[g]=v)}else if(!c.deleted){a.set(g,y);const v=d[g];v!==void 0&&(pt(v,y)?v!==null&&c.delete(n):(l==="retain"&&f(),y===null?delete d[g]:d[g]=y))}c.deleted||(l==="insert"&&f(),es(i,c.content));break}}c=c.right}for(f();s.length>0;){const g=s[s.length-1];if(g.retain!==void 0&&g.attributes===void 0)s.pop();else break}}),this._delta=s}return this._delta}}class Yt extends De{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Me(),this._length}_integrate(e,s){super._integrate(e,s);try{this._pending.forEach(n=>n())}catch(n){console.error(n)}this._pending=null}_copy(){return new Yt}clone(){const e=new Yt;return e.applyDelta(this.toDelta()),e}_callObserver(e,s){super._callObserver(e,s);const n=new Xu(this,e,s);En(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Me();let e="",s=this._start;for(;s!==null;)!s.deleted&&s.countable&&s.content.constructor===tt&&(e+=s.content.str),s=s.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:s=!0}={}){this.doc!==null?me(this.doc,n=>{const i=new tr(null,this._start,0,new Map);for(let a=0;a<e.length;a++){const c=e[a];if(c.insert!==void 0){const l=!s&&typeof c.insert=="string"&&a===e.length-1&&i.right===null&&c.insert.slice(-1)===`
211
+ `?c.insert.slice(0,-1):c.insert;(typeof l!="string"||l.length>0)&&On(n,this,i,l,c.attributes||{})}else c.retain!==void 0?_i(n,this,i,c.retain,c.attributes||{}):c.delete!==void 0&&ki(n,i,c.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,s,n){this.doc??Me();const i=[],a=new Map,c=this.doc;let l="",d=this._start;function p(){if(l.length>0){const u={};let f=!1;a.forEach((y,v)=>{f=!0,u[v]=y});const g={insert:l};f&&(g.attributes=u),i.push(g),l=""}}const w=()=>{for(;d!==null;){if(Ot(d,e)||s!==void 0&&Ot(d,s))switch(d.content.constructor){case tt:{const u=a.get("ychange");e!==void 0&&!Ot(d,e)?(u===void 0||u.user!==d.id.client||u.type!=="removed")&&(p(),a.set("ychange",n?n("removed",d.id):{type:"removed"})):s!==void 0&&!Ot(d,s)?(u===void 0||u.user!==d.id.client||u.type!=="added")&&(p(),a.set("ychange",n?n("added",d.id):{type:"added"})):u!==void 0&&(p(),a.delete("ychange")),l+=d.content.str;break}case ut:case At:{p();const u={insert:d.content.getContent()[0]};if(a.size>0){const f={};u.attributes=f,a.forEach((g,y)=>{f[y]=g})}i.push(u);break}case Ne:Ot(d,e)&&(p(),es(a,d.content));break}d=d.right}p()};return e||s?me(c,u=>{e&&Qn(u,e),s&&Qn(u,s),w()},"cleanup"):w(),i}insert(e,s,n){if(s.length<=0)return;const i=this.doc;i!==null?me(i,a=>{const c=Ns(a,this,e,!n);n||(n={},c.currentAttributes.forEach((l,d)=>{n[d]=l})),On(a,this,c,s,n)}):this._pending.push(()=>this.insert(e,s,n))}insertEmbed(e,s,n){const i=this.doc;i!==null?me(i,a=>{const c=Ns(a,this,e,!n);On(a,this,c,s,n||{})}):this._pending.push(()=>this.insertEmbed(e,s,n||{}))}delete(e,s){if(s===0)return;const n=this.doc;n!==null?me(n,i=>{ki(i,Ns(i,this,e,!0),s)}):this._pending.push(()=>this.delete(e,s))}format(e,s,n){if(s===0)return;const i=this.doc;i!==null?me(i,a=>{const c=Ns(a,this,e,!1);c.right!==null&&_i(a,this,c,s,n)}):this._pending.push(()=>this.format(e,s,n))}removeAttribute(e){this.doc!==null?me(this.doc,s=>{qs(s,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,s){this.doc!==null?me(this.doc,n=>{zr(n,this,e,s)}):this._pending.push(()=>this.setAttribute(e,s))}getAttribute(e){return Vr(this,e)}getAttributes(){return ua(this)}_write(e){e.writeTypeRef(yh)}}const Zu=t=>new Yt;class Pn{constructor(e,s=()=>!0){this._filter=s,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Me()}[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===Kt||s.constructor===Nt)&&s._start!==null)e=s._start;else for(;e!==null;){const n=e.next;if(n!==null){e=n;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 Nt extends De{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 Nt}clone(){const e=new Nt;return e.insert(0,this.toArray().map(s=>s instanceof De?s.clone():s)),e}get length(){return this.doc??Me(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Pn(this,e)}querySelector(e){e=e.toUpperCase();const n=new Pn(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return n.done?null:n.value}querySelectorAll(e){return e=e.toUpperCase(),at(new Pn(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e))}_callObserver(e,s){En(this,e,new th(this,s,e))}toString(){return oa(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,s={},n){const i=e.createDocumentFragment();return n!==void 0&&n._createAssociation(i,this),gs(this,a=>{i.insertBefore(a.toDOM(e,s,n),null)}),i}insert(e,s){this.doc!==null?me(this.doc,n=>{ca(n,this,e,s)}):this._prelimContent.splice(e,0,...s)}insertAfter(e,s){if(this.doc!==null)me(this.doc,n=>{const i=e&&e instanceof De?e._item:e;Hs(n,this,i,s)});else{const n=this._prelimContent,i=e===null?0:n.findIndex(a=>a===e)+1;if(i===0&&e!==null)throw ze("Reference item not found");n.splice(i,0,...s)}}delete(e,s=1){this.doc!==null?me(this.doc,n=>{da(n,this,e,s)}):this._prelimContent.splice(e,s)}toArray(){return ia(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return aa(this,e)}slice(e=0,s=this.length){return ra(this,e,s)}forEach(e){gs(this,e)}_write(e){e.writeTypeRef(bh)}}const Qu=t=>new Nt;class Kt extends Nt{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((n,i)=>{this.setAttribute(i,n)}),this._prelimAttrs=null}_copy(){return new Kt(this.nodeName)}clone(){const e=new Kt(this.nodeName),s=this.getAttributes();return td(s,(n,i)=>{e.setAttribute(i,n)}),e.insert(0,this.toArray().map(n=>n instanceof De?n.clone():n)),e}toString(){const e=this.getAttributes(),s=[],n=[];for(const l in e)n.push(l);n.sort();const i=n.length;for(let l=0;l<i;l++){const d=n[l];s.push(d+'="'+e[d]+'"')}const a=this.nodeName.toLocaleLowerCase(),c=s.length>0?" "+s.join(" "):"";return`<${a}${c}>${super.toString()}</${a}>`}removeAttribute(e){this.doc!==null?me(this.doc,s=>{qs(s,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,s){this.doc!==null?me(this.doc,n=>{zr(n,this,e,s)}):this._prelimAttrs.set(e,s)}getAttribute(e){return Vr(this,e)}hasAttribute(e){return ha(this,e)}getAttributes(e){return e?zu(this,e):ua(this)}toDOM(e=document,s={},n){const i=e.createElement(this.nodeName),a=this.getAttributes();for(const c in a){const l=a[c];typeof l=="string"&&i.setAttribute(c,l)}return gs(this,c=>{i.appendChild(c.toDOM(e,s,n))}),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(wh),e.writeKey(this.nodeName)}}const eh=t=>new Kt(t.readKey());class th extends _n{constructor(e,s,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,s.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class Gs extends jt{constructor(e){super(),this.hookName=e}_copy(){return new Gs(this.hookName)}clone(){const e=new Gs(this.hookName);return this.forEach((s,n)=>{e.set(n,s)}),e}toDOM(e=document,s={},n){const i=s[this.hookName];let a;return i!==void 0?a=i.createDom(this):a=document.createElement(this.hookName),a.setAttribute("data-yjs-hook",this.hookName),n!==void 0&&n._createAssociation(a,this),a}_write(e){e.writeTypeRef(xh),e.writeKey(this.hookName)}}const sh=t=>new Gs(t.readKey());class Ys extends Yt{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 Ys}clone(){const e=new Ys;return e.applyDelta(this.toDelta()),e}toDOM(e=document,s,n){const i=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const s=[];for(const i in e.attributes){const a=[];for(const c in e.attributes[i])a.push({key:c,value:e.attributes[i][c]});a.sort((c,l)=>c.key<l.key?-1:1),s.push({nodeName:i,attrs:a})}s.sort((i,a)=>i.nodeName<a.nodeName?-1:1);let n="";for(let i=0;i<s.length;i++){const a=s[i];n+=`<${a.nodeName}`;for(let c=0;c<a.attrs.length;c++){const l=a.attrs[c];n+=` ${l.key}="${l.value}"`}n+=">"}n+=e.insert;for(let i=s.length-1;i>=0;i--)n+=`</${s[i].nodeName}>`;return n}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(vh)}}const nh=t=>new Ys;class Hr{constructor(e,s){this.id=e,this.length=s}get deleted(){throw Je()}mergeWith(e){return!1}write(e,s,n){throw Je()}integrate(e,s){throw Je()}}const rh=0;class He extends Hr{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),Zo(e.doc.store,this)}write(e,s){e.writeInfo(rh),e.writeLen(this.length-s)}getMissing(e,s){return null}}class ks{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ks(this.content)}splice(e){throw Je()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeBuf(this.content)}getRef(){return 3}}const ih=t=>new ks(t.readBuf());class ms{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new ms(this.len)}splice(e){const s=new ms(this.len-e);return this.len=e,s}mergeWith(e){return this.len+=e.len,!0}integrate(e,s){zs(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 oh=t=>new ms(t.readLen()),ya=(t,e)=>new Qt({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Es{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 Es(ya(this.doc.guid,this.opts))}splice(e){throw Je()}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 ah=t=>new Es(ya(t.readString(),t.readAny()));class At{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new At(this.embed)}splice(e){throw Je()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeJSON(this.embed)}getRef(){return 5}}const lh=t=>new At(t.readJSON());class Ne{constructor(e,s){this.key=e,this.value=s}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Ne(this.key,this.value)}splice(e){throw Je()}mergeWith(e){return!1}integrate(e,s){const n=s.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,s){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const ch=t=>new Ne(t.readKey(),t.readJSON());class Ks{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Ks(this.arr)}splice(e){const s=new Ks(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 n=this.arr.length;e.writeLen(n-s);for(let i=s;i<n;i++){const a=this.arr[i];e.writeString(a===void 0?"undefined":JSON.stringify(a))}}getRef(){return 2}}const dh=t=>{const e=t.readLen(),s=[];for(let n=0;n<e;n++){const i=t.readString();i==="undefined"?s.push(void 0):s.push(JSON.parse(i))}return new Ks(s)},uh=hs("node_env")==="development";class Ct{constructor(e){this.arr=e,uh&&ao(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Ct(this.arr)}splice(e){const s=new Ct(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 n=this.arr.length;e.writeLen(n-s);for(let i=s;i<n;i++){const a=this.arr[i];e.writeAny(a)}}getRef(){return 8}}const hh=t=>{const e=t.readLen(),s=[];for(let n=0;n<e;n++)s.push(t.readAny());return new Ct(s)};class tt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new tt(this.str)}splice(e){const s=new tt(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=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 fh=t=>new tt(t.readString()),ph=[Hu,Gu,Zu,eh,Qu,sh,nh],gh=0,mh=1,yh=2,wh=3,bh=4,xh=5,vh=6;class ut{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new ut(this.type._copy())}splice(e){throw Je()}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(n=>{n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.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(n=>{for(;n!==null;)n.gc(e,!0),n=n.left}),this.type._map=new Map}write(e,s){this.type._write(e)}getRef(){return 7}}const _h=t=>new ut(ph[t.readTypeRef()](t)),Js=(t,e,s)=>{const{client:n,clock:i}=e.id,a=new je(pe(n,i+s),e,pe(n,i+s-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(s));return e.deleted&&a.markDeleted(),e.keep&&(a.keep=!0),e.redone!==null&&(a.redone=pe(e.redone.client,e.redone.clock+s)),e.right=a,a.right!==null&&(a.right.left=a),t._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),e.length=s,a};class je extends Hr{constructor(e,s,n,i,a,c,l,d){super(e,d.getLength()),this.origin=n,this.left=s,this.right=i,this.rightOrigin=a,this.parent=c,this.parentSub=l,this.redone=null,this.content=d,this.info=this.content.isCountable()?ei:0}set marker(e){(this.info&Cn)>0!==e&&(this.info^=Cn)}get marker(){return(this.info&Cn)>0}get keep(){return(this.info&Qr)>0}set keep(e){this.keep!==e&&(this.info^=Qr)}get countable(){return(this.info&ei)>0}get deleted(){return(this.info&Nn)>0}set deleted(e){this.deleted!==e&&(this.info^=Nn)}markDeleted(){this.info|=Nn}getMissing(e,s){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Re(s,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Re(s,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Wt&&this.id.client!==this.parent.client&&this.parent.clock>=Re(s,this.parent.client))return this.parent.client;if(this.origin&&(this.left=yi(e,s,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=wt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===He||this.right&&this.right.constructor===He)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===je?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===je&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Wt){const n=Mn(s,this.parent);n.constructor===He?this.parent=null:this.parent=n.content.type}return null}integrate(e,s){if(s>0&&(this.id.clock+=s,this.left=yi(e,e.doc.store,pe(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(s),this.length-=s),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let n=this.left,i;if(n!==null)i=n.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const a=new Set,c=new Set;for(;i!==null&&i!==this.right;){if(c.add(i),a.add(i),Ss(this.origin,i.origin)){if(i.id.client<this.id.client)n=i,a.clear();else if(Ss(this.rightOrigin,i.rightOrigin))break}else if(i.origin!==null&&c.has(Mn(e.doc.store,i.origin)))a.has(Mn(e.doc.store,i.origin))||(n=i,a.clear());else break;i=i.right}this.left=n}if(this.left!==null){const n=this.left.right;this.right=n,this.left.right=this}else{let n;if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start,this.parent._start=this;this.right=n}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),Zo(e.doc.store,this),this.content.integrate(e,this),bi(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new He(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:pe(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ss(e.origin,this.lastId)&&this.right===e&&Ss(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(n=>{n.p===e&&(n.p=this,!this.deleted&&this.countable&&(n.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(),zs(e.deleteSet,this.id.client,this.id.clock,this.length),bi(e,s,this.parentSub),this.content.delete(e)}}gc(e,s){if(!this.deleted)throw Ke();this.content.gc(e),s?Nu(e,this,new He(this.id,this.length)):this.content=new ms(this.length)}write(e,s){const n=s>0?pe(this.id.client,this.id.clock+s-1):this.origin,i=this.rightOrigin,a=this.parentSub,c=this.content.getRef()&cn|(n===null?0:Fe)|(i===null?0:it)|(a===null?0:ls);if(e.writeInfo(c),n!==null&&e.writeLeftID(n),i!==null&&e.writeRightID(i),n===null&&i===null){const l=this.parent;if(l._item!==void 0){const d=l._item;if(d===null){const p=Su(l);e.writeParentInfo(!0),e.writeString(p)}else e.writeParentInfo(!1),e.writeLeftID(d.id)}else l.constructor===String?(e.writeParentInfo(!0),e.writeString(l)):l.constructor===Wt?(e.writeParentInfo(!1),e.writeLeftID(l)):Ke();a!==null&&e.writeString(a)}this.content.write(e,s)}}const wa=(t,e)=>kh[e&cn](t),kh=[()=>{Ke()},oh,dh,ih,fh,lh,ch,_h,hh,ah,()=>{Ke()}],Eh=10;class qe extends Hr{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,s){Ke()}write(e,s){e.writeInfo(Eh),Q(e.restEncoder,this.length-s)}getMissing(e,s){return null}}const ba=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},xa="__ $YJS$ __";ba[xa]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");ba[xa]=!0;const Rt=t=>Vt((e,s)=>{t.onerror=n=>s(new Error(n.target.error)),t.onsuccess=n=>e(n.target.result)}),Sh=(t,e)=>Vt((s,n)=>{const i=indexedDB.open(t);i.onupgradeneeded=a=>e(a.target.result),i.onerror=a=>n(ze(a.target.error)),i.onsuccess=a=>{const c=a.target.result;c.onversionchange=()=>{c.close()},s(c)}}),jh=t=>Rt(indexedDB.deleteDatabase(t)),Nh=(t,e)=>e.forEach(s=>t.createObjectStore.apply(t,s)),ss=(t,e,s="readwrite")=>{const n=t.transaction(e,s);return e.map(i=>Mh(n,i))},va=(t,e)=>Rt(t.count(e)),Ch=(t,e)=>Rt(t.get(e)),_a=(t,e)=>Rt(t.delete(e)),Th=(t,e,s)=>Rt(t.put(e,s)),sr=(t,e)=>Rt(t.add(e)),Ah=(t,e,s)=>Rt(t.getAll(e,s)),Rh=(t,e,s)=>{let n=null;return Dh(t,e,i=>(n=i,!1),s).then(()=>n)},Lh=(t,e=null)=>Rh(t,e,"prev"),Ih=(t,e)=>Vt((s,n)=>{t.onerror=n,t.onsuccess=async i=>{const a=i.target.result;if(a===null||await e(a)===!1)return s();a.continue()}}),Dh=(t,e,s,n="next")=>Ih(t.openKeyCursor(e,n),i=>s(i.key)),Mh=(t,e)=>t.objectStore(e),Oh=(t,e)=>IDBKeyRange.upperBound(t,e),Ph=(t,e)=>IDBKeyRange.lowerBound(t,e),Un="custom",ka="updates",Ea=500,Sa=(t,e=()=>{},s=()=>{})=>{const[n]=ss(t.db,[ka]);return Ah(n,Ph(t._dbref,!1)).then(i=>{t._destroyed||(e(n),me(t.doc,()=>{i.forEach(a=>Go(t.doc,a))},t,!1),s(n))}).then(()=>Lh(n).then(i=>{t._dbref=i+1})).then(()=>va(n).then(i=>{t._dbsize=i})).then(()=>n)},Uh=(t,e=!0)=>Sa(t).then(s=>{(e||t._dbsize>=Ea)&&sr(s,Ur(t.doc)).then(()=>_a(s,Oh(t._dbref,!0))).then(()=>va(s).then(n=>{t._dbsize=n}))});class Wh extends xr{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=Sh(e,n=>Nh(n,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Vt(n=>this.on("synced",()=>n(this))),this._db.then(n=>{this.db=n,Sa(this,c=>sr(c,Ur(s)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(n,i)=>{if(this.db&&i!==this){const[a]=ss(this.db,[ka]);sr(a,n),++this._dbsize>=Ea&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Uh(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(()=>{jh(this.name)})}get(e){return this._db.then(s=>{const[n]=ss(s,[Un],"readonly");return Ch(n,e)})}set(e,s){return this._db.then(n=>{const[i]=ss(n,[Un]);return Th(i,s,e)})}del(e){return this._db.then(s=>{const[n]=ss(s,[Un]);return _a(n,e)})}}const Bh=1200,Fh=2500,Xs=3e4,nr=t=>{if(t.shouldConnect&&t.ws===null){const e=new WebSocket(t.url),s=t.binaryType;let n=null;s&&(e.binaryType=s),t.ws=e,t.connecting=!0,t.connected=!1,e.onmessage=c=>{t.lastMessageReceived=lt();const l=c.data,d=typeof l=="string"?JSON.parse(l):l;d&&d.type==="pong"&&(clearTimeout(n),n=setTimeout(a,Xs/2)),t.emit("message",[d,t])};const i=c=>{t.ws!==null&&(t.ws=null,t.connecting=!1,t.connected?(t.connected=!1,t.emit("disconnect",[{type:"disconnect",error:c},t])):t.unsuccessfulReconnects++,setTimeout(nr,vr(mc(t.unsuccessfulReconnects+1)*Bh,Fh),t)),clearTimeout(n)},a=()=>{t.ws===e&&t.send({type:"ping"})};e.onclose=()=>i(null),e.onerror=c=>i(c),e.onopen=()=>{t.lastMessageReceived=lt(),t.connecting=!1,t.connected=!0,t.unsuccessfulReconnects=0,t.emit("connect",[{type:"connect"},t]),n=setTimeout(a,Xs/2)}}};class $h extends xr{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&&Xs<lt()-this.lastMessageReceived&&this.ws.close()},Xs/2),nr(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&&nr(this)}}const ja=new Map;class zh{constructor(e){this.room=e,this.onmessage=null,this._onChange=s=>s.key===e&&this.onmessage!==null&&this.onmessage({data:po(s.newValue||"")}),Jc(this._onChange)}postMessage(e){io.setItem(this.room,fo(fd(e)))}close(){Xc(this._onChange)}}const Vh=typeof BroadcastChannel>"u"?zh:BroadcastChannel,qr=t=>$e(ja,t,()=>{const e=yt(),s=new Vh(t);return s.onmessage=n=>e.forEach(i=>i(n.data,"broadcastchannel")),{bc:s,subs:e}}),Hh=(t,e)=>(qr(t).subs.add(e),e),qh=(t,e)=>{const s=qr(t),n=s.subs.delete(e);return n&&s.subs.size===0&&(s.bc.close(),ja.delete(t)),n},Gh=(t,e,s=null)=>{const n=qr(t);n.bc.postMessage(e),n.subs.forEach(i=>i(e,s))},Yh=()=>{let t=!0;return(e,s)=>{if(t){t=!1;try{e()}finally{t=!0}}else s!==void 0&&s()}};function Cs(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 Wn={exports:{}},Ei;function Kh(){return Ei||(Ei=1,(function(t,e){(function(s){t.exports=s()})(function(){var s=Math.floor,n=Math.abs,i=Math.pow;return(function(){function a(c,l,d){function p(f,g){if(!l[f]){if(!c[f]){var y=typeof Cs=="function"&&Cs;if(!g&&y)return y(f,!0);if(w)return w(f,!0);var v=new Error("Cannot find module '"+f+"'");throw v.code="MODULE_NOT_FOUND",v}var A=l[f]={exports:{}};c[f][0].call(A.exports,function(C){var M=c[f][1][C];return p(M||C)},A,A.exports,a,c,l,d)}return l[f].exports}for(var w=typeof Cs=="function"&&Cs,u=0;u<d.length;u++)p(d[u]);return p}return a})()({1:[function(a,c,l){function d(x){var E=x.length;if(0<E%4)throw new Error("Invalid string. Length must be a multiple of 4");var j=x.indexOf("=");j===-1&&(j=E);var k=j===E?0:4-j%4;return[j,k]}function p(x,E,j){return 3*(E+j)/4-j}function w(x){var E,j,k=d(x),R=k[0],O=k[1],N=new A(p(x,R,O)),L=0,W=0<O?R-4:R;for(j=0;j<W;j+=4)E=v[x.charCodeAt(j)]<<18|v[x.charCodeAt(j+1)]<<12|v[x.charCodeAt(j+2)]<<6|v[x.charCodeAt(j+3)],N[L++]=255&E>>16,N[L++]=255&E>>8,N[L++]=255&E;return O===2&&(E=v[x.charCodeAt(j)]<<2|v[x.charCodeAt(j+1)]>>4,N[L++]=255&E),O===1&&(E=v[x.charCodeAt(j)]<<10|v[x.charCodeAt(j+1)]<<4|v[x.charCodeAt(j+2)]>>2,N[L++]=255&E>>8,N[L++]=255&E),N}function u(x){return y[63&x>>18]+y[63&x>>12]+y[63&x>>6]+y[63&x]}function f(x,E,j){for(var k,R=[],O=E;O<j;O+=3)k=(16711680&x[O]<<16)+(65280&x[O+1]<<8)+(255&x[O+2]),R.push(u(k));return R.join("")}function g(x){for(var E,j=x.length,k=j%3,R=[],O=16383,N=0,L=j-k;N<L;N+=O)R.push(f(x,N,N+O>L?L:N+O));return k===1?(E=x[j-1],R.push(y[E>>2]+y[63&E<<4]+"==")):k===2&&(E=(x[j-2]<<8)+x[j-1],R.push(y[E>>10]+y[63&E>>4]+y[63&E<<2]+"=")),R.join("")}l.byteLength=function(x){var E=d(x),j=E[0],k=E[1];return 3*(j+k)/4-k},l.toByteArray=w,l.fromByteArray=g;for(var y=[],v=[],A=typeof Uint8Array>"u"?Array:Uint8Array,C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",M=0,b=C.length;M<b;++M)y[M]=C[M],v[C.charCodeAt(M)]=M;v[45]=62,v[95]=63},{}],2:[function(){},{}],3:[function(a,c,l){(function(){(function(){var d=String.fromCharCode,p=Math.min;function w(o){if(2147483647<o)throw new RangeError('The value "'+o+'" is invalid for option "size"');var h=new Uint8Array(o);return h.__proto__=u.prototype,h}function u(o,h,m){if(typeof o=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return v(o)}return f(o,h,m)}function f(o,h,m){if(typeof o=="string")return A(o,h);if(ArrayBuffer.isView(o))return C(o);if(o==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof o);if(I(o,ArrayBuffer)||o&&I(o.buffer,ArrayBuffer))return M(o,h,m);if(typeof o=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var T=o.valueOf&&o.valueOf();if(T!=null&&T!==o)return u.from(T,h,m);var D=b(o);if(D)return D;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof o[Symbol.toPrimitive]=="function")return u.from(o[Symbol.toPrimitive]("string"),h,m);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof o)}function g(o){if(typeof o!="number")throw new TypeError('"size" argument must be of type number');if(0>o)throw new RangeError('The value "'+o+'" is invalid for option "size"')}function y(o,h,m){return g(o),0>=o||h===void 0?w(o):typeof m=="string"?w(o).fill(h,m):w(o).fill(h)}function v(o){return g(o),w(0>o?0:0|x(o))}function A(o,h){if((typeof h!="string"||h==="")&&(h="utf8"),!u.isEncoding(h))throw new TypeError("Unknown encoding: "+h);var m=0|E(o,h),T=w(m),D=T.write(o,h);return D!==m&&(T=T.slice(0,D)),T}function C(o){for(var h=0>o.length?0:0|x(o.length),m=w(h),T=0;T<h;T+=1)m[T]=255&o[T];return m}function M(o,h,m){if(0>h||o.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(o.byteLength<h+(m||0))throw new RangeError('"length" is outside of buffer bounds');var T;return T=h===void 0&&m===void 0?new Uint8Array(o):m===void 0?new Uint8Array(o,h):new Uint8Array(o,h,m),T.__proto__=u.prototype,T}function b(o){if(u.isBuffer(o)){var h=0|x(o.length),m=w(h);return m.length===0||o.copy(m,0,0,h),m}return o.length===void 0?o.type==="Buffer"&&Array.isArray(o.data)?C(o.data):void 0:typeof o.length!="number"||P(o.length)?w(0):C(o)}function x(o){if(o>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|o}function E(o,h){if(u.isBuffer(o))return o.length;if(ArrayBuffer.isView(o)||I(o,ArrayBuffer))return o.byteLength;if(typeof o!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof o);var m=o.length,T=2<arguments.length&&arguments[2]===!0;if(!T&&m===0)return 0;for(var D=!1;;)switch(h){case"ascii":case"latin1":case"binary":return m;case"utf8":case"utf-8":return Se(o).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*m;case"hex":return m>>>1;case"base64":return K(o).length;default:if(D)return T?-1:Se(o).length;h=(""+h).toLowerCase(),D=!0}}function j(o,h,m){var T=!1;if((h===void 0||0>h)&&(h=0),h>this.length||((m===void 0||m>this.length)&&(m=this.length),0>=m)||(m>>>=0,h>>>=0,m<=h))return"";for(o||(o="utf8");;)switch(o){case"hex":return fe(this,h,m);case"utf8":case"utf-8":return B(this,h,m);case"ascii":return $(this,h,m);case"latin1":case"binary":return ge(this,h,m);case"base64":return Z(this,h,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return be(this,h,m);default:if(T)throw new TypeError("Unknown encoding: "+o);o=(o+"").toLowerCase(),T=!0}}function k(o,h,m){var T=o[h];o[h]=o[m],o[m]=T}function R(o,h,m,T,D){if(o.length===0)return-1;if(typeof m=="string"?(T=m,m=0):2147483647<m?m=2147483647:-2147483648>m&&(m=-2147483648),m=+m,P(m)&&(m=D?0:o.length-1),0>m&&(m=o.length+m),m>=o.length){if(D)return-1;m=o.length-1}else if(0>m)if(D)m=0;else return-1;if(typeof h=="string"&&(h=u.from(h,T)),u.isBuffer(h))return h.length===0?-1:O(o,h,m,T,D);if(typeof h=="number")return h&=255,typeof Uint8Array.prototype.indexOf=="function"?D?Uint8Array.prototype.indexOf.call(o,h,m):Uint8Array.prototype.lastIndexOf.call(o,h,m):O(o,[h],m,T,D);throw new TypeError("val must be string, number or Buffer")}function O(o,h,m,T,D){function U(Lt,ts){return X===1?Lt[ts]:Lt.readUInt16BE(ts*X)}var X=1,ue=o.length,we=h.length;if(T!==void 0&&(T=(T+"").toLowerCase(),T==="ucs2"||T==="ucs-2"||T==="utf16le"||T==="utf-16le")){if(2>o.length||2>h.length)return-1;X=2,ue/=2,we/=2,m/=2}var he;if(D){var le=-1;for(he=m;he<ue;he++)if(U(o,he)!==U(h,le===-1?0:he-le))le!==-1&&(he-=he-le),le=-1;else if(le===-1&&(le=he),he-le+1===we)return le*X}else for(m+we>ue&&(m=ue-we),he=m;0<=he;he--){for(var Ie=!0,xt=0;xt<we;xt++)if(U(o,he+xt)!==U(h,xt)){Ie=!1;break}if(Ie)return he}return-1}function N(o,h,m,T){m=+m||0;var D=o.length-m;T?(T=+T,T>D&&(T=D)):T=D;var U=h.length;T>U/2&&(T=U/2);for(var X,ue=0;ue<T;++ue){if(X=parseInt(h.substr(2*ue,2),16),P(X))return ue;o[m+ue]=X}return ue}function L(o,h,m,T){return ae(Se(h,o.length-m),o,m,T)}function W(o,h,m,T){return ae(q(h),o,m,T)}function F(o,h,m,T){return W(o,h,m,T)}function V(o,h,m,T){return ae(K(h),o,m,T)}function G(o,h,m,T){return ae(Y(h,o.length-m),o,m,T)}function Z(o,h,m){return h===0&&m===o.length?z.fromByteArray(o):z.fromByteArray(o.slice(h,m))}function B(o,h,m){m=p(o.length,m);for(var T=[],D=h;D<m;){var U=o[D],X=null,ue=239<U?4:223<U?3:191<U?2:1;if(D+ue<=m){var we,he,le,Ie;ue===1?128>U&&(X=U):ue===2?(we=o[D+1],(192&we)==128&&(Ie=(31&U)<<6|63&we,127<Ie&&(X=Ie))):ue===3?(we=o[D+1],he=o[D+2],(192&we)==128&&(192&he)==128&&(Ie=(15&U)<<12|(63&we)<<6|63&he,2047<Ie&&(55296>Ie||57343<Ie)&&(X=Ie))):ue===4&&(we=o[D+1],he=o[D+2],le=o[D+3],(192&we)==128&&(192&he)==128&&(192&le)==128&&(Ie=(15&U)<<18|(63&we)<<12|(63&he)<<6|63&le,65535<Ie&&1114112>Ie&&(X=Ie)))}X===null?(X=65533,ue=1):65535<X&&(X-=65536,T.push(55296|1023&X>>>10),X=56320|1023&X),T.push(X),D+=ue}return H(T)}function H(o){var h=o.length;if(h<=4096)return d.apply(String,o);for(var m="",T=0;T<h;)m+=d.apply(String,o.slice(T,T+=4096));return m}function $(o,h,m){var T="";m=p(o.length,m);for(var D=h;D<m;++D)T+=d(127&o[D]);return T}function ge(o,h,m){var T="";m=p(o.length,m);for(var D=h;D<m;++D)T+=d(o[D]);return T}function fe(o,h,m){var T=o.length;(!h||0>h)&&(h=0),(!m||0>m||m>T)&&(m=T);for(var D="",U=h;U<m;++U)D+=ye(o[U]);return D}function be(o,h,m){for(var T=o.slice(h,m),D="",U=0;U<T.length;U+=2)D+=d(T[U]+256*T[U+1]);return D}function ce(o,h,m){if(o%1!=0||0>o)throw new RangeError("offset is not uint");if(o+h>m)throw new RangeError("Trying to access beyond buffer length")}function ee(o,h,m,T,D,U){if(!u.isBuffer(o))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>D||h<U)throw new RangeError('"value" argument is out of bounds');if(m+T>o.length)throw new RangeError("Index out of range")}function Ee(o,h,m,T){if(m+T>o.length)throw new RangeError("Index out of range");if(0>m)throw new RangeError("Index out of range")}function Ve(o,h,m,T,D){return h=+h,m>>>=0,D||Ee(o,h,m,4),J.write(o,h,m,T,23,4),m+4}function ie(o,h,m,T,D){return h=+h,m>>>=0,D||Ee(o,h,m,8),J.write(o,h,m,T,52,8),m+8}function de(o){if(o=o.split("=")[0],o=o.trim().replace(_,""),2>o.length)return"";for(;o.length%4!=0;)o+="=";return o}function ye(o){return 16>o?"0"+o.toString(16):o.toString(16)}function Se(o,h){h=h||1/0;for(var m,T=o.length,D=null,U=[],X=0;X<T;++X){if(m=o.charCodeAt(X),55295<m&&57344>m){if(!D){if(56319<m){-1<(h-=3)&&U.push(239,191,189);continue}else if(X+1===T){-1<(h-=3)&&U.push(239,191,189);continue}D=m;continue}if(56320>m){-1<(h-=3)&&U.push(239,191,189),D=m;continue}m=(D-55296<<10|m-56320)+65536}else D&&-1<(h-=3)&&U.push(239,191,189);if(D=null,128>m){if(0>(h-=1))break;U.push(m)}else if(2048>m){if(0>(h-=2))break;U.push(192|m>>6,128|63&m)}else if(65536>m){if(0>(h-=3))break;U.push(224|m>>12,128|63&m>>6,128|63&m)}else if(1114112>m){if(0>(h-=4))break;U.push(240|m>>18,128|63&m>>12,128|63&m>>6,128|63&m)}else throw new Error("Invalid code point")}return U}function q(o){for(var h=[],m=0;m<o.length;++m)h.push(255&o.charCodeAt(m));return h}function Y(o,h){for(var m,T,D,U=[],X=0;X<o.length&&!(0>(h-=2));++X)m=o.charCodeAt(X),T=m>>8,D=m%256,U.push(D),U.push(T);return U}function K(o){return z.toByteArray(de(o))}function ae(o,h,m,T){for(var D=0;D<T&&!(D+m>=h.length||D>=o.length);++D)h[D+m]=o[D];return D}function I(o,h){return o instanceof h||o!=null&&o.constructor!=null&&o.constructor.name!=null&&o.constructor.name===h.name}function P(o){return o!==o}var z=a("base64-js"),J=a("ieee754");l.Buffer=u,l.SlowBuffer=function(o){return+o!=o&&(o=0),u.alloc(+o)},l.INSPECT_MAX_BYTES=50,l.kMaxLength=2147483647,u.TYPED_ARRAY_SUPPORT=(function(){try{var o=new Uint8Array(1);return o.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},o.foo()===42}catch{return!1}})(),u.TYPED_ARRAY_SUPPORT||typeof console>"u"||typeof console.error!="function"||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){return u.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){return u.isBuffer(this)?this.byteOffset:void 0}}),typeof Symbol<"u"&&Symbol.species!=null&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),u.poolSize=8192,u.from=function(o,h,m){return f(o,h,m)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(o,h,m){return y(o,h,m)},u.allocUnsafe=function(o){return v(o)},u.allocUnsafeSlow=function(o){return v(o)},u.isBuffer=function(o){return o!=null&&o._isBuffer===!0&&o!==u.prototype},u.compare=function(o,h){if(I(o,Uint8Array)&&(o=u.from(o,o.offset,o.byteLength)),I(h,Uint8Array)&&(h=u.from(h,h.offset,h.byteLength)),!u.isBuffer(o)||!u.isBuffer(h))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(o===h)return 0;for(var m=o.length,T=h.length,D=0,U=p(m,T);D<U;++D)if(o[D]!==h[D]){m=o[D],T=h[D];break}return m<T?-1:T<m?1:0},u.isEncoding=function(o){switch((o+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(o,h){if(!Array.isArray(o))throw new TypeError('"list" argument must be an Array of Buffers');if(o.length===0)return u.alloc(0);var m;if(h===void 0)for(h=0,m=0;m<o.length;++m)h+=o[m].length;var T=u.allocUnsafe(h),D=0;for(m=0;m<o.length;++m){var U=o[m];if(I(U,Uint8Array)&&(U=u.from(U)),!u.isBuffer(U))throw new TypeError('"list" argument must be an Array of Buffers');U.copy(T,D),D+=U.length}return T},u.byteLength=E,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var o=this.length;if(o%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var h=0;h<o;h+=2)k(this,h,h+1);return this},u.prototype.swap32=function(){var o=this.length;if(o%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var h=0;h<o;h+=4)k(this,h,h+3),k(this,h+1,h+2);return this},u.prototype.swap64=function(){var o=this.length;if(o%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var h=0;h<o;h+=8)k(this,h,h+7),k(this,h+1,h+6),k(this,h+2,h+5),k(this,h+3,h+4);return this},u.prototype.toString=function(){var o=this.length;return o===0?"":arguments.length===0?B(this,0,o):j.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(o){if(!u.isBuffer(o))throw new TypeError("Argument must be a Buffer");return this===o||u.compare(this,o)===0},u.prototype.inspect=function(){var o="",h=l.INSPECT_MAX_BYTES;return o=this.toString("hex",0,h).replace(/(.{2})/g,"$1 ").trim(),this.length>h&&(o+=" ... "),"<Buffer "+o+">"},u.prototype.compare=function(o,h,m,T,D){if(I(o,Uint8Array)&&(o=u.from(o,o.offset,o.byteLength)),!u.isBuffer(o))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof o);if(h===void 0&&(h=0),m===void 0&&(m=o?o.length:0),T===void 0&&(T=0),D===void 0&&(D=this.length),0>h||m>o.length||0>T||D>this.length)throw new RangeError("out of range index");if(T>=D&&h>=m)return 0;if(T>=D)return-1;if(h>=m)return 1;if(h>>>=0,m>>>=0,T>>>=0,D>>>=0,this===o)return 0;for(var U=D-T,X=m-h,ue=p(U,X),we=this.slice(T,D),he=o.slice(h,m),le=0;le<ue;++le)if(we[le]!==he[le]){U=we[le],X=he[le];break}return U<X?-1:X<U?1:0},u.prototype.includes=function(o,h,m){return this.indexOf(o,h,m)!==-1},u.prototype.indexOf=function(o,h,m){return R(this,o,h,m,!0)},u.prototype.lastIndexOf=function(o,h,m){return R(this,o,h,m,!1)},u.prototype.write=function(o,h,m,T){if(h===void 0)T="utf8",m=this.length,h=0;else if(m===void 0&&typeof h=="string")T=h,m=this.length,h=0;else if(isFinite(h))h>>>=0,isFinite(m)?(m>>>=0,T===void 0&&(T="utf8")):(T=m,m=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var D=this.length-h;if((m===void 0||m>D)&&(m=D),0<o.length&&(0>m||0>h)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");T||(T="utf8");for(var U=!1;;)switch(T){case"hex":return N(this,o,h,m);case"utf8":case"utf-8":return L(this,o,h,m);case"ascii":return W(this,o,h,m);case"latin1":case"binary":return F(this,o,h,m);case"base64":return V(this,o,h,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,o,h,m);default:if(U)throw new TypeError("Unknown encoding: "+T);T=(""+T).toLowerCase(),U=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},u.prototype.slice=function(o,h){var m=this.length;o=~~o,h=h===void 0?m:~~h,0>o?(o+=m,0>o&&(o=0)):o>m&&(o=m),0>h?(h+=m,0>h&&(h=0)):h>m&&(h=m),h<o&&(h=o);var T=this.subarray(o,h);return T.__proto__=u.prototype,T},u.prototype.readUIntLE=function(o,h,m){o>>>=0,h>>>=0,m||ce(o,h,this.length);for(var T=this[o],D=1,U=0;++U<h&&(D*=256);)T+=this[o+U]*D;return T},u.prototype.readUIntBE=function(o,h,m){o>>>=0,h>>>=0,m||ce(o,h,this.length);for(var T=this[o+--h],D=1;0<h&&(D*=256);)T+=this[o+--h]*D;return T},u.prototype.readUInt8=function(o,h){return o>>>=0,h||ce(o,1,this.length),this[o]},u.prototype.readUInt16LE=function(o,h){return o>>>=0,h||ce(o,2,this.length),this[o]|this[o+1]<<8},u.prototype.readUInt16BE=function(o,h){return o>>>=0,h||ce(o,2,this.length),this[o]<<8|this[o+1]},u.prototype.readUInt32LE=function(o,h){return o>>>=0,h||ce(o,4,this.length),(this[o]|this[o+1]<<8|this[o+2]<<16)+16777216*this[o+3]},u.prototype.readUInt32BE=function(o,h){return o>>>=0,h||ce(o,4,this.length),16777216*this[o]+(this[o+1]<<16|this[o+2]<<8|this[o+3])},u.prototype.readIntLE=function(o,h,m){o>>>=0,h>>>=0,m||ce(o,h,this.length);for(var T=this[o],D=1,U=0;++U<h&&(D*=256);)T+=this[o+U]*D;return D*=128,T>=D&&(T-=i(2,8*h)),T},u.prototype.readIntBE=function(o,h,m){o>>>=0,h>>>=0,m||ce(o,h,this.length);for(var T=h,D=1,U=this[o+--T];0<T&&(D*=256);)U+=this[o+--T]*D;return D*=128,U>=D&&(U-=i(2,8*h)),U},u.prototype.readInt8=function(o,h){return o>>>=0,h||ce(o,1,this.length),128&this[o]?-1*(255-this[o]+1):this[o]},u.prototype.readInt16LE=function(o,h){o>>>=0,h||ce(o,2,this.length);var m=this[o]|this[o+1]<<8;return 32768&m?4294901760|m:m},u.prototype.readInt16BE=function(o,h){o>>>=0,h||ce(o,2,this.length);var m=this[o+1]|this[o]<<8;return 32768&m?4294901760|m:m},u.prototype.readInt32LE=function(o,h){return o>>>=0,h||ce(o,4,this.length),this[o]|this[o+1]<<8|this[o+2]<<16|this[o+3]<<24},u.prototype.readInt32BE=function(o,h){return o>>>=0,h||ce(o,4,this.length),this[o]<<24|this[o+1]<<16|this[o+2]<<8|this[o+3]},u.prototype.readFloatLE=function(o,h){return o>>>=0,h||ce(o,4,this.length),J.read(this,o,!0,23,4)},u.prototype.readFloatBE=function(o,h){return o>>>=0,h||ce(o,4,this.length),J.read(this,o,!1,23,4)},u.prototype.readDoubleLE=function(o,h){return o>>>=0,h||ce(o,8,this.length),J.read(this,o,!0,52,8)},u.prototype.readDoubleBE=function(o,h){return o>>>=0,h||ce(o,8,this.length),J.read(this,o,!1,52,8)},u.prototype.writeUIntLE=function(o,h,m,T){if(o=+o,h>>>=0,m>>>=0,!T){var D=i(2,8*m)-1;ee(this,o,h,m,D,0)}var U=1,X=0;for(this[h]=255&o;++X<m&&(U*=256);)this[h+X]=255&o/U;return h+m},u.prototype.writeUIntBE=function(o,h,m,T){if(o=+o,h>>>=0,m>>>=0,!T){var D=i(2,8*m)-1;ee(this,o,h,m,D,0)}var U=m-1,X=1;for(this[h+U]=255&o;0<=--U&&(X*=256);)this[h+U]=255&o/X;return h+m},u.prototype.writeUInt8=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,1,255,0),this[h]=255&o,h+1},u.prototype.writeUInt16LE=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,2,65535,0),this[h]=255&o,this[h+1]=o>>>8,h+2},u.prototype.writeUInt16BE=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,2,65535,0),this[h]=o>>>8,this[h+1]=255&o,h+2},u.prototype.writeUInt32LE=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,4,4294967295,0),this[h+3]=o>>>24,this[h+2]=o>>>16,this[h+1]=o>>>8,this[h]=255&o,h+4},u.prototype.writeUInt32BE=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,4,4294967295,0),this[h]=o>>>24,this[h+1]=o>>>16,this[h+2]=o>>>8,this[h+3]=255&o,h+4},u.prototype.writeIntLE=function(o,h,m,T){if(o=+o,h>>>=0,!T){var D=i(2,8*m-1);ee(this,o,h,m,D-1,-D)}var U=0,X=1,ue=0;for(this[h]=255&o;++U<m&&(X*=256);)0>o&&ue===0&&this[h+U-1]!==0&&(ue=1),this[h+U]=255&(o/X>>0)-ue;return h+m},u.prototype.writeIntBE=function(o,h,m,T){if(o=+o,h>>>=0,!T){var D=i(2,8*m-1);ee(this,o,h,m,D-1,-D)}var U=m-1,X=1,ue=0;for(this[h+U]=255&o;0<=--U&&(X*=256);)0>o&&ue===0&&this[h+U+1]!==0&&(ue=1),this[h+U]=255&(o/X>>0)-ue;return h+m},u.prototype.writeInt8=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,1,127,-128),0>o&&(o=255+o+1),this[h]=255&o,h+1},u.prototype.writeInt16LE=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,2,32767,-32768),this[h]=255&o,this[h+1]=o>>>8,h+2},u.prototype.writeInt16BE=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,2,32767,-32768),this[h]=o>>>8,this[h+1]=255&o,h+2},u.prototype.writeInt32LE=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,4,2147483647,-2147483648),this[h]=255&o,this[h+1]=o>>>8,this[h+2]=o>>>16,this[h+3]=o>>>24,h+4},u.prototype.writeInt32BE=function(o,h,m){return o=+o,h>>>=0,m||ee(this,o,h,4,2147483647,-2147483648),0>o&&(o=4294967295+o+1),this[h]=o>>>24,this[h+1]=o>>>16,this[h+2]=o>>>8,this[h+3]=255&o,h+4},u.prototype.writeFloatLE=function(o,h,m){return Ve(this,o,h,!0,m)},u.prototype.writeFloatBE=function(o,h,m){return Ve(this,o,h,!1,m)},u.prototype.writeDoubleLE=function(o,h,m){return ie(this,o,h,!0,m)},u.prototype.writeDoubleBE=function(o,h,m){return ie(this,o,h,!1,m)},u.prototype.copy=function(o,h,m,T){if(!u.isBuffer(o))throw new TypeError("argument should be a Buffer");if(m||(m=0),T||T===0||(T=this.length),h>=o.length&&(h=o.length),h||(h=0),0<T&&T<m&&(T=m),T===m||o.length===0||this.length===0)return 0;if(0>h)throw new RangeError("targetStart out of bounds");if(0>m||m>=this.length)throw new RangeError("Index out of range");if(0>T)throw new RangeError("sourceEnd out of bounds");T>this.length&&(T=this.length),o.length-h<T-m&&(T=o.length-h+m);var D=T-m;if(this===o&&typeof Uint8Array.prototype.copyWithin=="function")this.copyWithin(h,m,T);else if(this===o&&m<h&&h<T)for(var U=D-1;0<=U;--U)o[U+h]=this[U+m];else Uint8Array.prototype.set.call(o,this.subarray(m,T),h);return D},u.prototype.fill=function(o,h,m,T){if(typeof o=="string"){if(typeof h=="string"?(T=h,h=0,m=this.length):typeof m=="string"&&(T=m,m=this.length),T!==void 0&&typeof T!="string")throw new TypeError("encoding must be a string");if(typeof T=="string"&&!u.isEncoding(T))throw new TypeError("Unknown encoding: "+T);if(o.length===1){var D=o.charCodeAt(0);(T==="utf8"&&128>D||T==="latin1")&&(o=D)}}else typeof o=="number"&&(o&=255);if(0>h||this.length<h||this.length<m)throw new RangeError("Out of range index");if(m<=h)return this;h>>>=0,m=m===void 0?this.length:m>>>0,o||(o=0);var U;if(typeof o=="number")for(U=h;U<m;++U)this[U]=o;else{var X=u.isBuffer(o)?o:u.from(o,T),ue=X.length;if(ue===0)throw new TypeError('The value "'+o+'" is invalid for argument "value"');for(U=0;U<m-h;++U)this[U+h]=X[U%ue]}return this};var _=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,a("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(a,c,l){(function(d){(function(){function p(){let u;try{u=l.storage.getItem("debug")}catch{}return!u&&typeof d<"u"&&"env"in d&&(u=d.env.DEBUG),u}l.formatArgs=function(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+c.exports.humanize(this.diff),!this.useColors)return;const f="color: "+this.color;u.splice(1,0,f,"color: inherit");let g=0,y=0;u[0].replace(/%[a-zA-Z%]/g,v=>{v==="%%"||(g++,v==="%c"&&(y=g))}),u.splice(y,0,f)},l.save=function(u){try{u?l.storage.setItem("debug",u):l.storage.removeItem("debug")}catch{}},l.load=p,l.useColors=function(){return!!(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))||!(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},l.storage=(function(){try{return localStorage}catch{}})(),l.destroy=(()=>{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),l.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],l.log=console.debug||console.log||(()=>{}),c.exports=a("./common")(l);const{formatters:w}=c.exports;w.j=function(u){try{return JSON.stringify(u)}catch(f){return"[UnexpectedJSONParseError]: "+f.message}}}).call(this)}).call(this,a("_process"))},{"./common":5,_process:12}],5:[function(a,c){c.exports=function(l){function d(u){function f(...v){if(!f.enabled)return;const A=f,C=+new Date,M=C-(g||C);A.diff=M,A.prev=g,A.curr=C,g=C,v[0]=d.coerce(v[0]),typeof v[0]!="string"&&v.unshift("%O");let b=0;v[0]=v[0].replace(/%([a-zA-Z%])/g,(E,j)=>{if(E==="%%")return"%";b++;const k=d.formatters[j];if(typeof k=="function"){const R=v[b];E=k.call(A,R),v.splice(b,1),b--}return E}),d.formatArgs.call(A,v),(A.log||d.log).apply(A,v)}let g,y=null;return f.namespace=u,f.useColors=d.useColors(),f.color=d.selectColor(u),f.extend=p,f.destroy=d.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>y===null?d.enabled(u):y,set:v=>{y=v}}),typeof d.init=="function"&&d.init(f),f}function p(u,f){const g=d(this.namespace+(typeof f>"u"?":":f)+u);return g.log=this.log,g}function w(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}return d.debug=d,d.default=d,d.coerce=function(u){return u instanceof Error?u.stack||u.message:u},d.disable=function(){const u=[...d.names.map(w),...d.skips.map(w).map(f=>"-"+f)].join(",");return d.enable(""),u},d.enable=function(u){d.save(u),d.names=[],d.skips=[];let f;const g=(typeof u=="string"?u:"").split(/[\s,]+/),y=g.length;for(f=0;f<y;f++)g[f]&&(u=g[f].replace(/\*/g,".*?"),u[0]==="-"?d.skips.push(new RegExp("^"+u.substr(1)+"$")):d.names.push(new RegExp("^"+u+"$")))},d.enabled=function(u){if(u[u.length-1]==="*")return!0;let f,g;for(f=0,g=d.skips.length;f<g;f++)if(d.skips[f].test(u))return!1;for(f=0,g=d.names.length;f<g;f++)if(d.names[f].test(u))return!0;return!1},d.humanize=a("ms"),d.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(l).forEach(u=>{d[u]=l[u]}),d.names=[],d.skips=[],d.formatters={},d.selectColor=function(u){let f=0;for(let g=0;g<u.length;g++)f=(f<<5)-f+u.charCodeAt(g),f|=0;return d.colors[n(f)%d.colors.length]},d.enable(d.load()),d}},{ms:11}],6:[function(a,c){function l(d,p){for(const w in p)Object.defineProperty(d,w,{value:p[w],enumerable:!0,configurable:!0});return d}c.exports=function(d,p,w){if(!d||typeof d=="string")throw new TypeError("Please pass an Error to err-code");w||(w={}),typeof p=="object"&&(w=p,p=""),p&&(w.code=p);try{return l(d,w)}catch{w.message=d.message,w.stack=d.stack;const f=function(){};return f.prototype=Object.create(Object.getPrototypeOf(d)),l(new f,w)}}},{}],7:[function(a,c){function l(N){console&&console.warn&&console.warn(N)}function d(){d.init.call(this)}function p(N){if(typeof N!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof N)}function w(N){return N._maxListeners===void 0?d.defaultMaxListeners:N._maxListeners}function u(N,L,W,F){var V,G,Z;if(p(W),G=N._events,G===void 0?(G=N._events=Object.create(null),N._eventsCount=0):(G.newListener!==void 0&&(N.emit("newListener",L,W.listener?W.listener:W),G=N._events),Z=G[L]),Z===void 0)Z=G[L]=W,++N._eventsCount;else if(typeof Z=="function"?Z=G[L]=F?[W,Z]:[Z,W]:F?Z.unshift(W):Z.push(W),V=w(N),0<V&&Z.length>V&&!Z.warned){Z.warned=!0;var B=new Error("Possible EventEmitter memory leak detected. "+Z.length+" "+(L+" listeners added. Use emitter.setMaxListeners() to increase limit"));B.name="MaxListenersExceededWarning",B.emitter=N,B.type=L,B.count=Z.length,l(B)}return N}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 g(N,L,W){var F={fired:!1,wrapFn:void 0,target:N,type:L,listener:W},V=f.bind(F);return V.listener=W,F.wrapFn=V,V}function y(N,L,W){var F=N._events;if(F===void 0)return[];var V=F[L];return V===void 0?[]:typeof V=="function"?W?[V.listener||V]:[V]:W?M(V):A(V,V.length)}function v(N){var L=this._events;if(L!==void 0){var W=L[N];if(typeof W=="function")return 1;if(W!==void 0)return W.length}return 0}function A(N,L){for(var W=Array(L),F=0;F<L;++F)W[F]=N[F];return W}function C(N,L){for(;L+1<N.length;L++)N[L]=N[L+1];N.pop()}function M(N){for(var L=Array(N.length),W=0;W<L.length;++W)L[W]=N[W].listener||N[W];return L}function b(N,L,W){typeof N.on=="function"&&x(N,"error",L,W)}function x(N,L,W,F){if(typeof N.on=="function")F.once?N.once(L,W):N.on(L,W);else if(typeof N.addEventListener=="function")N.addEventListener(L,function V(G){F.once&&N.removeEventListener(L,V),W(G)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof N)}var E,j=typeof Reflect=="object"?Reflect:null,k=j&&typeof j.apply=="function"?j.apply:function(N,L,W){return Function.prototype.apply.call(N,L,W)};E=j&&typeof j.ownKeys=="function"?j.ownKeys:Object.getOwnPropertySymbols?function(N){return Object.getOwnPropertyNames(N).concat(Object.getOwnPropertySymbols(N))}:function(N){return Object.getOwnPropertyNames(N)};var R=Number.isNaN||function(N){return N!==N};c.exports=d,c.exports.once=function(N,L){return new Promise(function(W,F){function V(Z){N.removeListener(L,G),F(Z)}function G(){typeof N.removeListener=="function"&&N.removeListener("error",V),W([].slice.call(arguments))}x(N,L,G,{once:!0}),L!=="error"&&b(N,V,{once:!0})})},d.EventEmitter=d,d.prototype._events=void 0,d.prototype._eventsCount=0,d.prototype._maxListeners=void 0;var O=10;Object.defineProperty(d,"defaultMaxListeners",{enumerable:!0,get:function(){return O},set:function(N){if(typeof N!="number"||0>N||R(N))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+N+".");O=N}}),d.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},d.prototype.setMaxListeners=function(N){if(typeof N!="number"||0>N||R(N))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+N+".");return this._maxListeners=N,this},d.prototype.getMaxListeners=function(){return w(this)},d.prototype.emit=function(N){for(var L=[],W=1;W<arguments.length;W++)L.push(arguments[W]);var F=N==="error",V=this._events;if(V!==void 0)F=F&&V.error===void 0;else if(!F)return!1;if(F){var G;if(0<L.length&&(G=L[0]),G instanceof Error)throw G;var Z=new Error("Unhandled error."+(G?" ("+G.message+")":""));throw Z.context=G,Z}var B=V[N];if(B===void 0)return!1;if(typeof B=="function")k(B,this,L);else for(var H=B.length,$=A(B,H),W=0;W<H;++W)k($[W],this,L);return!0},d.prototype.addListener=function(N,L){return u(this,N,L,!1)},d.prototype.on=d.prototype.addListener,d.prototype.prependListener=function(N,L){return u(this,N,L,!0)},d.prototype.once=function(N,L){return p(L),this.on(N,g(this,N,L)),this},d.prototype.prependOnceListener=function(N,L){return p(L),this.prependListener(N,g(this,N,L)),this},d.prototype.removeListener=function(N,L){var W,F,V,G,Z;if(p(L),F=this._events,F===void 0)return this;if(W=F[N],W===void 0)return this;if(W===L||W.listener===L)--this._eventsCount==0?this._events=Object.create(null):(delete F[N],F.removeListener&&this.emit("removeListener",N,W.listener||L));else if(typeof W!="function"){for(V=-1,G=W.length-1;0<=G;G--)if(W[G]===L||W[G].listener===L){Z=W[G].listener,V=G;break}if(0>V)return this;V===0?W.shift():C(W,V),W.length===1&&(F[N]=W[0]),F.removeListener!==void 0&&this.emit("removeListener",N,Z||L)}return this},d.prototype.off=d.prototype.removeListener,d.prototype.removeAllListeners=function(N){var L,W,F;if(W=this._events,W===void 0)return this;if(W.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):W[N]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete W[N]),this;if(arguments.length===0){var V,G=Object.keys(W);for(F=0;F<G.length;++F)V=G[F],V!=="removeListener"&&this.removeAllListeners(V);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(L=W[N],typeof L=="function")this.removeListener(N,L);else if(L!==void 0)for(F=L.length-1;0<=F;F--)this.removeListener(N,L[F]);return this},d.prototype.listeners=function(N){return y(this,N,!0)},d.prototype.rawListeners=function(N){return y(this,N,!1)},d.listenerCount=function(N,L){return typeof N.listenerCount=="function"?N.listenerCount(L):v.call(N,L)},d.prototype.listenerCount=v,d.prototype.eventNames=function(){return 0<this._eventsCount?E(this._events):[]}},{}],8:[function(a,c){c.exports=function(){if(typeof globalThis>"u")return null;var l={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return l.RTCPeerConnection?l:null}},{}],9:[function(a,c,l){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */l.read=function(d,p,w,u,f){var g,y,v=8*f-u-1,A=(1<<v)-1,C=A>>1,M=-7,b=w?f-1:0,x=w?-1:1,E=d[p+b];for(b+=x,g=E&(1<<-M)-1,E>>=-M,M+=v;0<M;g=256*g+d[p+b],b+=x,M-=8);for(y=g&(1<<-M)-1,g>>=-M,M+=u;0<M;y=256*y+d[p+b],b+=x,M-=8);if(g===0)g=1-C;else{if(g===A)return y?NaN:(E?-1:1)*(1/0);y+=i(2,u),g-=C}return(E?-1:1)*y*i(2,g-u)},l.write=function(d,p,w,u,f,g){var y,v,A,C=Math.LN2,M=Math.log,b=8*g-f-1,x=(1<<b)-1,E=x>>1,j=f===23?i(2,-24)-i(2,-77):0,k=u?0:g-1,R=u?1:-1,O=0>p||p===0&&0>1/p?1:0;for(p=n(p),isNaN(p)||p===1/0?(v=isNaN(p)?1:0,y=x):(y=s(M(p)/C),1>p*(A=i(2,-y))&&(y--,A*=2),p+=1<=y+E?j/A:j*i(2,1-E),2<=p*A&&(y++,A/=2),y+E>=x?(v=0,y=x):1<=y+E?(v=(p*A-1)*i(2,f),y+=E):(v=p*i(2,E-1)*i(2,f),y=0));8<=f;d[w+k]=255&v,k+=R,v/=256,f-=8);for(y=y<<f|v,b+=f;0<b;d[w+k]=255&y,k+=R,y/=256,b-=8);d[w+k-R]|=128*O}},{}],10:[function(a,c){c.exports=typeof Object.create=="function"?function(l,d){d&&(l.super_=d,l.prototype=Object.create(d.prototype,{constructor:{value:l,enumerable:!1,writable:!0,configurable:!0}}))}:function(l,d){if(d){l.super_=d;var p=function(){};p.prototype=d.prototype,l.prototype=new p,l.prototype.constructor=l}}},{}],11:[function(a,c){var l=Math.round;function d(f){if(f+="",!(100<f.length)){var g=/^(-?(?:\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(g){var y=parseFloat(g[1]),v=(g[2]||"ms").toLowerCase();return v==="years"||v==="year"||v==="yrs"||v==="yr"||v==="y"?315576e5*y:v==="weeks"||v==="week"||v==="w"?6048e5*y:v==="days"||v==="day"||v==="d"?864e5*y:v==="hours"||v==="hour"||v==="hrs"||v==="hr"||v==="h"?36e5*y:v==="minutes"||v==="minute"||v==="mins"||v==="min"||v==="m"?6e4*y:v==="seconds"||v==="second"||v==="secs"||v==="sec"||v==="s"?1e3*y:v==="milliseconds"||v==="millisecond"||v==="msecs"||v==="msec"||v==="ms"?y:void 0}}}function p(f){var g=n(f);return 864e5<=g?l(f/864e5)+"d":36e5<=g?l(f/36e5)+"h":6e4<=g?l(f/6e4)+"m":1e3<=g?l(f/1e3)+"s":f+"ms"}function w(f){var g=n(f);return 864e5<=g?u(f,g,864e5,"day"):36e5<=g?u(f,g,36e5,"hour"):6e4<=g?u(f,g,6e4,"minute"):1e3<=g?u(f,g,1e3,"second"):f+" ms"}function u(f,g,y,v){return l(f/y)+" "+v+(g>=1.5*y?"s":"")}c.exports=function(f,g){g=g||{};var y=typeof f;if(y=="string"&&0<f.length)return d(f);if(y==="number"&&isFinite(f))return g.long?w(f):p(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))}},{}],12:[function(a,c){function l(){throw new Error("setTimeout has not been defined")}function d(){throw new Error("clearTimeout has not been defined")}function p(j){if(v===setTimeout)return setTimeout(j,0);if((v===l||!v)&&setTimeout)return v=setTimeout,setTimeout(j,0);try{return v(j,0)}catch{try{return v.call(null,j,0)}catch{return v.call(this,j,0)}}}function w(j){if(A===clearTimeout)return clearTimeout(j);if((A===d||!A)&&clearTimeout)return A=clearTimeout,clearTimeout(j);try{return A(j)}catch{try{return A.call(null,j)}catch{return A.call(this,j)}}}function u(){x&&M&&(x=!1,M.length?b=M.concat(b):E=-1,b.length&&f())}function f(){if(!x){var j=p(u);x=!0;for(var k=b.length;k;){for(M=b,b=[];++E<k;)M&&M[E].run();E=-1,k=b.length}M=null,x=!1,w(j)}}function g(j,k){this.fun=j,this.array=k}function y(){}var v,A,C=c.exports={};(function(){try{v=typeof setTimeout=="function"?setTimeout:l}catch{v=l}try{A=typeof clearTimeout=="function"?clearTimeout:d}catch{A=d}})();var M,b=[],x=!1,E=-1;C.nextTick=function(j){var k=Array(arguments.length-1);if(1<arguments.length)for(var R=1;R<arguments.length;R++)k[R-1]=arguments[R];b.push(new g(j,k)),b.length!==1||x||p(f)},g.prototype.run=function(){this.fun.apply(null,this.array)},C.title="browser",C.browser=!0,C.env={},C.argv=[],C.version="",C.versions={},C.on=y,C.addListener=y,C.once=y,C.off=y,C.removeListener=y,C.removeAllListeners=y,C.emit=y,C.prependListener=y,C.prependOnceListener=y,C.listeners=function(){return[]},C.binding=function(){throw new Error("process.binding is not supported")},C.cwd=function(){return"/"},C.chdir=function(){throw new Error("process.chdir is not supported")},C.umask=function(){return 0}},{}],13:[function(a,c){(function(l){(function(){/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let d;c.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window>"u"?l:window):p=>(d||(d=Promise.resolve())).then(p).catch(w=>setTimeout(()=>{throw w},0))}).call(this)}).call(this,typeof Xe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Xe)},{}],14:[function(a,c){(function(l,d){(function(){var p=a("safe-buffer").Buffer,w=d.crypto||d.msCrypto;c.exports=w&&w.getRandomValues?function(u,f){if(u>4294967295)throw new RangeError("requested too many random bytes");var g=p.allocUnsafe(u);if(0<u)if(65536<u)for(var y=0;y<u;y+=65536)w.getRandomValues(g.slice(y,y+65536));else w.getRandomValues(g);return typeof f=="function"?l.nextTick(function(){f(null,g)}):g}:function(){throw new Error(`Secure random number generation is not supported by this browser.
212
+ Use Chrome, Firefox or Internet Explorer 11`)}}).call(this)}).call(this,a("_process"),typeof Xe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Xe)},{_process:12,"safe-buffer":30}],15:[function(a,c){function l(y,v){y.prototype=Object.create(v.prototype),y.prototype.constructor=y,y.__proto__=v}function d(y,v,A){function C(b,x,E){return typeof v=="string"?v:v(b,x,E)}A||(A=Error);var M=(function(b){function x(E,j,k){return b.call(this,C(E,j,k))||this}return l(x,b),x})(A);M.prototype.name=A.name,M.prototype.code=y,g[y]=M}function p(y,v){if(Array.isArray(y)){var A=y.length;return y=y.map(function(C){return C+""}),2<A?"one of ".concat(v," ").concat(y.slice(0,A-1).join(", "),", or ")+y[A-1]:A===2?"one of ".concat(v," ").concat(y[0]," or ").concat(y[1]):"of ".concat(v," ").concat(y[0])}return"of ".concat(v," ").concat(y+"")}function w(y,v,A){return y.substr(0,v.length)===v}function u(y,v,A){return(A===void 0||A>y.length)&&(A=y.length),y.substring(A-v.length,A)===v}function f(y,v,A){return typeof A!="number"&&(A=0),!(A+v.length>y.length)&&y.indexOf(v,A)!==-1}var g={};d("ERR_INVALID_OPT_VALUE",function(y,v){return'The value "'+v+'" is invalid for option "'+y+'"'},TypeError),d("ERR_INVALID_ARG_TYPE",function(y,v,A){var C;typeof v=="string"&&w(v,"not ")?(C="must not be",v=v.replace(/^not /,"")):C="must be";var M;if(u(y," argument"))M="The ".concat(y," ").concat(C," ").concat(p(v,"type"));else{var b=f(y,".")?"property":"argument";M='The "'.concat(y,'" ').concat(b," ").concat(C," ").concat(p(v,"type"))}return M+=". Received type ".concat(typeof A),M},TypeError),d("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),d("ERR_METHOD_NOT_IMPLEMENTED",function(y){return"The "+y+" method is not implemented"}),d("ERR_STREAM_PREMATURE_CLOSE","Premature close"),d("ERR_STREAM_DESTROYED",function(y){return"Cannot call "+y+" after a stream was destroyed"}),d("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),d("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),d("ERR_STREAM_WRITE_AFTER_END","write after end"),d("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),d("ERR_UNKNOWN_ENCODING",function(y){return"Unknown encoding: "+y},TypeError),d("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),c.exports.codes=g},{}],16:[function(a,c){(function(l){(function(){function d(C){return this instanceof d?(f.call(this,C),g.call(this,C),this.allowHalfOpen=!0,void(C&&(C.readable===!1&&(this.readable=!1),C.writable===!1&&(this.writable=!1),C.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",p))))):new d(C)}function p(){this._writableState.ended||l.nextTick(w,this)}function w(C){C.end()}var u=Object.keys||function(C){var M=[];for(var b in C)M.push(b);return M};c.exports=d;var f=a("./_stream_readable"),g=a("./_stream_writable");a("inherits")(d,f);for(var y,v=u(g.prototype),A=0;A<v.length;A++)y=v[A],d.prototype[y]||(d.prototype[y]=g.prototype[y]);Object.defineProperty(d.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(d.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(d.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(d.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._writableState!==void 0&&this._readableState.destroyed&&this._writableState.destroyed},set:function(C){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=C,this._writableState.destroyed=C)}})}).call(this)}).call(this,a("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(a,c){function l(p){return this instanceof l?void d.call(this,p):new l(p)}c.exports=l;var d=a("./_stream_transform");a("inherits")(l,d),l.prototype._transform=function(p,w,u){u(null,p)}},{"./_stream_transform":19,inherits:10}],18:[function(a,c){(function(l,d){(function(){function p(_){return be.from(_)}function w(_){return be.isBuffer(_)||_ instanceof ce}function u(_,o,h){return typeof _.prependListener=="function"?_.prependListener(o,h):void(_._events&&_._events[o]?Array.isArray(_._events[o])?_._events[o].unshift(h):_._events[o]=[h,_._events[o]]:_.on(o,h))}function f(_,o,h){H=H||a("./_stream_duplex"),_=_||{},typeof h!="boolean"&&(h=o instanceof H),this.objectMode=!!_.objectMode,h&&(this.objectMode=this.objectMode||!!_.readableObjectMode),this.highWaterMark=q(this,_,"readableHighWaterMark",h),this.buffer=new de,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=_.emitClose!==!1,this.autoDestroy=!!_.autoDestroy,this.destroyed=!1,this.defaultEncoding=_.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,_.encoding&&(!Ee&&(Ee=a("string_decoder/").StringDecoder),this.decoder=new Ee(_.encoding),this.encoding=_.encoding)}function g(_){if(H=H||a("./_stream_duplex"),!(this instanceof g))return new g(_);var o=this instanceof H;this._readableState=new f(_,this,o),this.readable=!0,_&&(typeof _.read=="function"&&(this._read=_.read),typeof _.destroy=="function"&&(this._destroy=_.destroy)),fe.call(this)}function y(_,o,h,m,T){$("readableAddChunk",o);var D=_._readableState;if(o===null)D.reading=!1,b(_,D);else{var U;if(T||(U=A(D,o)),U)z(_,U);else if(!(D.objectMode||o&&0<o.length))m||(D.reading=!1,j(_,D));else if(typeof o=="string"||D.objectMode||Object.getPrototypeOf(o)===be.prototype||(o=p(o)),m)D.endEmitted?z(_,new P):v(_,D,o,!0);else if(D.ended)z(_,new ae);else{if(D.destroyed)return!1;D.reading=!1,D.decoder&&!h?(o=D.decoder.write(o),D.objectMode||o.length!==0?v(_,D,o,!1):j(_,D)):v(_,D,o,!1)}}return!D.ended&&(D.length<D.highWaterMark||D.length===0)}function v(_,o,h,m){o.flowing&&o.length===0&&!o.sync?(o.awaitDrain=0,_.emit("data",h)):(o.length+=o.objectMode?1:h.length,m?o.buffer.unshift(h):o.buffer.push(h),o.needReadable&&x(_)),j(_,o)}function A(_,o){var h;return w(o)||typeof o=="string"||o===void 0||_.objectMode||(h=new K("chunk",["string","Buffer","Uint8Array"],o)),h}function C(_){return 1073741824<=_?_=1073741824:(_--,_|=_>>>1,_|=_>>>2,_|=_>>>4,_|=_>>>8,_|=_>>>16,_++),_}function M(_,o){return 0>=_||o.length===0&&o.ended?0:o.objectMode?1:_===_?(_>o.highWaterMark&&(o.highWaterMark=C(_)),_<=o.length?_:o.ended?o.length:(o.needReadable=!0,0)):o.flowing&&o.length?o.buffer.head.data.length:o.length}function b(_,o){if($("onEofChunk"),!o.ended){if(o.decoder){var h=o.decoder.end();h&&h.length&&(o.buffer.push(h),o.length+=o.objectMode?1:h.length)}o.ended=!0,o.sync?x(_):(o.needReadable=!1,!o.emittedReadable&&(o.emittedReadable=!0,E(_)))}}function x(_){var o=_._readableState;$("emitReadable",o.needReadable,o.emittedReadable),o.needReadable=!1,o.emittedReadable||($("emitReadable",o.flowing),o.emittedReadable=!0,l.nextTick(E,_))}function E(_){var o=_._readableState;$("emitReadable_",o.destroyed,o.length,o.ended),!o.destroyed&&(o.length||o.ended)&&(_.emit("readable"),o.emittedReadable=!1),o.needReadable=!o.flowing&&!o.ended&&o.length<=o.highWaterMark,F(_)}function j(_,o){o.readingMore||(o.readingMore=!0,l.nextTick(k,_,o))}function k(_,o){for(;!o.reading&&!o.ended&&(o.length<o.highWaterMark||o.flowing&&o.length===0);){var h=o.length;if($("maybeReadMore read 0"),_.read(0),h===o.length)break}o.readingMore=!1}function R(_){return function(){var o=_._readableState;$("pipeOnDrain",o.awaitDrain),o.awaitDrain&&o.awaitDrain--,o.awaitDrain===0&&ge(_,"data")&&(o.flowing=!0,F(_))}}function O(_){var o=_._readableState;o.readableListening=0<_.listenerCount("readable"),o.resumeScheduled&&!o.paused?o.flowing=!0:0<_.listenerCount("data")&&_.resume()}function N(_){$("readable nexttick read 0"),_.read(0)}function L(_,o){o.resumeScheduled||(o.resumeScheduled=!0,l.nextTick(W,_,o))}function W(_,o){$("resume",o.reading),o.reading||_.read(0),o.resumeScheduled=!1,_.emit("resume"),F(_),o.flowing&&!o.reading&&_.read(0)}function F(_){var o=_._readableState;for($("flow",o.flowing);o.flowing&&_.read()!==null;);}function V(_,o){if(o.length===0)return null;var h;return o.objectMode?h=o.buffer.shift():!_||_>=o.length?(h=o.decoder?o.buffer.join(""):o.buffer.length===1?o.buffer.first():o.buffer.concat(o.length),o.buffer.clear()):h=o.buffer.consume(_,o.decoder),h}function G(_){var o=_._readableState;$("endReadable",o.endEmitted),o.endEmitted||(o.ended=!0,l.nextTick(Z,o,_))}function Z(_,o){if($("endReadableNT",_.endEmitted,_.length),!_.endEmitted&&_.length===0&&(_.endEmitted=!0,o.readable=!1,o.emit("end"),_.autoDestroy)){var h=o._writableState;(!h||h.autoDestroy&&h.finished)&&o.destroy()}}function B(_,o){for(var h=0,m=_.length;h<m;h++)if(_[h]===o)return h;return-1}c.exports=g;var H;g.ReadableState=f;var $;a("events").EventEmitter;var ge=function(_,o){return _.listeners(o).length},fe=a("./internal/streams/stream"),be=a("buffer").Buffer,ce=d.Uint8Array||function(){},ee=a("util");$=ee&&ee.debuglog?ee.debuglog("stream"):function(){};var Ee,Ve,ie,de=a("./internal/streams/buffer_list"),ye=a("./internal/streams/destroy"),Se=a("./internal/streams/state"),q=Se.getHighWaterMark,Y=a("../errors").codes,K=Y.ERR_INVALID_ARG_TYPE,ae=Y.ERR_STREAM_PUSH_AFTER_EOF,I=Y.ERR_METHOD_NOT_IMPLEMENTED,P=Y.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;a("inherits")(g,fe);var z=ye.errorOrDestroy,J=["error","close","destroy","pause","resume"];Object.defineProperty(g.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(_){this._readableState&&(this._readableState.destroyed=_)}}),g.prototype.destroy=ye.destroy,g.prototype._undestroy=ye.undestroy,g.prototype._destroy=function(_,o){o(_)},g.prototype.push=function(_,o){var h,m=this._readableState;return m.objectMode?h=!0:typeof _=="string"&&(o=o||m.defaultEncoding,o!==m.encoding&&(_=be.from(_,o),o=""),h=!0),y(this,_,o,!1,h)},g.prototype.unshift=function(_){return y(this,_,null,!0,!1)},g.prototype.isPaused=function(){return this._readableState.flowing===!1},g.prototype.setEncoding=function(_){Ee||(Ee=a("string_decoder/").StringDecoder);var o=new Ee(_);this._readableState.decoder=o,this._readableState.encoding=this._readableState.decoder.encoding;for(var h=this._readableState.buffer.head,m="";h!==null;)m+=o.write(h.data),h=h.next;return this._readableState.buffer.clear(),m!==""&&this._readableState.buffer.push(m),this._readableState.length=m.length,this},g.prototype.read=function(_){$("read",_),_=parseInt(_,10);var o=this._readableState,h=_;if(_!==0&&(o.emittedReadable=!1),_===0&&o.needReadable&&((o.highWaterMark===0?0<o.length:o.length>=o.highWaterMark)||o.ended))return $("read: emitReadable",o.length,o.ended),o.length===0&&o.ended?G(this):x(this),null;if(_=M(_,o),_===0&&o.ended)return o.length===0&&G(this),null;var m=o.needReadable;$("need readable",m),(o.length===0||o.length-_<o.highWaterMark)&&(m=!0,$("length less than watermark",m)),o.ended||o.reading?(m=!1,$("reading or ended",m)):m&&($("do read"),o.reading=!0,o.sync=!0,o.length===0&&(o.needReadable=!0),this._read(o.highWaterMark),o.sync=!1,!o.reading&&(_=M(h,o)));var T;return T=0<_?V(_,o):null,T===null?(o.needReadable=o.length<=o.highWaterMark,_=0):(o.length-=_,o.awaitDrain=0),o.length===0&&(!o.ended&&(o.needReadable=!0),h!==_&&o.ended&&G(this)),T!==null&&this.emit("data",T),T},g.prototype._read=function(){z(this,new I("_read()"))},g.prototype.pipe=function(_,o){function h(It,Dt){$("onunpipe"),It===he&&Dt&&Dt.hasUnpiped===!1&&(Dt.hasUnpiped=!0,T())}function m(){$("onend"),_.end()}function T(){$("cleanup"),_.removeListener("close",X),_.removeListener("finish",ue),_.removeListener("drain",Lt),_.removeListener("error",U),_.removeListener("unpipe",h),he.removeListener("end",m),he.removeListener("end",we),he.removeListener("data",D),ts=!0,le.awaitDrain&&(!_._writableState||_._writableState.needDrain)&&Lt()}function D(It){$("ondata");var Dt=_.write(It);$("dest.write",Dt),Dt===!1&&((le.pipesCount===1&&le.pipes===_||1<le.pipesCount&&B(le.pipes,_)!==-1)&&!ts&&($("false write response, pause",le.awaitDrain),le.awaitDrain++),he.pause())}function U(It){$("onerror",It),we(),_.removeListener("error",U),ge(_,"error")===0&&z(_,It)}function X(){_.removeListener("finish",ue),we()}function ue(){$("onfinish"),_.removeListener("close",X),we()}function we(){$("unpipe"),he.unpipe(_)}var he=this,le=this._readableState;switch(le.pipesCount){case 0:le.pipes=_;break;case 1:le.pipes=[le.pipes,_];break;default:le.pipes.push(_)}le.pipesCount+=1,$("pipe count=%d opts=%j",le.pipesCount,o);var Ie=(!o||o.end!==!1)&&_!==l.stdout&&_!==l.stderr,xt=Ie?m:we;le.endEmitted?l.nextTick(xt):he.once("end",xt),_.on("unpipe",h);var Lt=R(he);_.on("drain",Lt);var ts=!1;return he.on("data",D),u(_,"error",U),_.once("close",X),_.once("finish",ue),_.emit("pipe",he),le.flowing||($("pipe resume"),he.resume()),_},g.prototype.unpipe=function(_){var o=this._readableState,h={hasUnpiped:!1};if(o.pipesCount===0)return this;if(o.pipesCount===1)return _&&_!==o.pipes?this:(_||(_=o.pipes),o.pipes=null,o.pipesCount=0,o.flowing=!1,_&&_.emit("unpipe",this,h),this);if(!_){var m=o.pipes,T=o.pipesCount;o.pipes=null,o.pipesCount=0,o.flowing=!1;for(var D=0;D<T;D++)m[D].emit("unpipe",this,{hasUnpiped:!1});return this}var U=B(o.pipes,_);return U===-1?this:(o.pipes.splice(U,1),o.pipesCount-=1,o.pipesCount===1&&(o.pipes=o.pipes[0]),_.emit("unpipe",this,h),this)},g.prototype.on=function(_,o){var h=fe.prototype.on.call(this,_,o),m=this._readableState;return _==="data"?(m.readableListening=0<this.listenerCount("readable"),m.flowing!==!1&&this.resume()):_=="readable"&&!m.endEmitted&&!m.readableListening&&(m.readableListening=m.needReadable=!0,m.flowing=!1,m.emittedReadable=!1,$("on readable",m.length,m.reading),m.length?x(this):!m.reading&&l.nextTick(N,this)),h},g.prototype.addListener=g.prototype.on,g.prototype.removeListener=function(_,o){var h=fe.prototype.removeListener.call(this,_,o);return _==="readable"&&l.nextTick(O,this),h},g.prototype.removeAllListeners=function(_){var o=fe.prototype.removeAllListeners.apply(this,arguments);return(_==="readable"||_===void 0)&&l.nextTick(O,this),o},g.prototype.resume=function(){var _=this._readableState;return _.flowing||($("resume"),_.flowing=!_.readableListening,L(this,_)),_.paused=!1,this},g.prototype.pause=function(){return $("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&($("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},g.prototype.wrap=function(_){var o=this,h=this._readableState,m=!1;for(var T in _.on("end",function(){if($("wrapped end"),h.decoder&&!h.ended){var U=h.decoder.end();U&&U.length&&o.push(U)}o.push(null)}),_.on("data",function(U){if($("wrapped data"),h.decoder&&(U=h.decoder.write(U)),!(h.objectMode&&U==null)&&(h.objectMode||U&&U.length)){var X=o.push(U);X||(m=!0,_.pause())}}),_)this[T]===void 0&&typeof _[T]=="function"&&(this[T]=(function(U){return function(){return _[U].apply(_,arguments)}})(T));for(var D=0;D<J.length;D++)_.on(J[D],this.emit.bind(this,J[D]));return this._read=function(U){$("wrapped _read",U),m&&(m=!1,_.resume())},this},typeof Symbol=="function"&&(g.prototype[Symbol.asyncIterator]=function(){return Ve===void 0&&(Ve=a("./internal/streams/async_iterator")),Ve(this)}),Object.defineProperty(g.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(g.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(g.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(_){this._readableState&&(this._readableState.flowing=_)}}),g._fromList=V,Object.defineProperty(g.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),typeof Symbol=="function"&&(g.from=function(_,o){return ie===void 0&&(ie=a("./internal/streams/from")),ie(g,_,o)})}).call(this)}).call(this,a("_process"),typeof Xe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Xe)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/async_iterator":21,"./internal/streams/buffer_list":22,"./internal/streams/destroy":23,"./internal/streams/from":25,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,events:7,inherits:10,"string_decoder/":31,util:2}],19:[function(a,c){function l(C,M){var b=this._transformState;b.transforming=!1;var x=b.writecb;if(x===null)return this.emit("error",new g);b.writechunk=null,b.writecb=null,M!=null&&this.push(M),x(C);var E=this._readableState;E.reading=!1,(E.needReadable||E.length<E.highWaterMark)&&this._read(E.highWaterMark)}function d(C){return this instanceof d?(A.call(this,C),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,C&&(typeof C.transform=="function"&&(this._transform=C.transform),typeof C.flush=="function"&&(this._flush=C.flush)),void this.on("prefinish",p)):new d(C)}function p(){var C=this;typeof this._flush!="function"||this._readableState.destroyed?w(this,null,null):this._flush(function(M,b){w(C,M,b)})}function w(C,M,b){if(M)return C.emit("error",M);if(b!=null&&C.push(b),C._writableState.length)throw new v;if(C._transformState.transforming)throw new y;return C.push(null)}c.exports=d;var u=a("../errors").codes,f=u.ERR_METHOD_NOT_IMPLEMENTED,g=u.ERR_MULTIPLE_CALLBACK,y=u.ERR_TRANSFORM_ALREADY_TRANSFORMING,v=u.ERR_TRANSFORM_WITH_LENGTH_0,A=a("./_stream_duplex");a("inherits")(d,A),d.prototype.push=function(C,M){return this._transformState.needTransform=!1,A.prototype.push.call(this,C,M)},d.prototype._transform=function(C,M,b){b(new f("_transform()"))},d.prototype._write=function(C,M,b){var x=this._transformState;if(x.writecb=b,x.writechunk=C,x.writeencoding=M,!x.transforming){var E=this._readableState;(x.needTransform||E.needReadable||E.length<E.highWaterMark)&&this._read(E.highWaterMark)}},d.prototype._read=function(){var C=this._transformState;C.writechunk===null||C.transforming?C.needTransform=!0:(C.transforming=!0,this._transform(C.writechunk,C.writeencoding,C.afterTransform))},d.prototype._destroy=function(C,M){A.prototype._destroy.call(this,C,function(b){M(b)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(a,c){(function(l,d){(function(){function p(I){var P=this;this.next=null,this.entry=null,this.finish=function(){G(P,I)}}function w(I){return $.from(I)}function u(I){return $.isBuffer(I)||I instanceof ge}function f(){}function g(I,P,z){Z=Z||a("./_stream_duplex"),I=I||{},typeof z!="boolean"&&(z=P instanceof Z),this.objectMode=!!I.objectMode,z&&(this.objectMode=this.objectMode||!!I.writableObjectMode),this.highWaterMark=ce(this,I,"writableHighWaterMark",z),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var J=I.decodeStrings===!1;this.decodeStrings=!J,this.defaultEncoding=I.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(_){j(P,_)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=I.emitClose!==!1,this.autoDestroy=!!I.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new p(this)}function y(I){Z=Z||a("./_stream_duplex");var P=this instanceof Z;return P||ae.call(y,this)?(this._writableState=new g(I,this,P),this.writable=!0,I&&(typeof I.write=="function"&&(this._write=I.write),typeof I.writev=="function"&&(this._writev=I.writev),typeof I.destroy=="function"&&(this._destroy=I.destroy),typeof I.final=="function"&&(this._final=I.final)),void H.call(this)):new y(I)}function v(I,P){var z=new q;K(I,z),l.nextTick(P,z)}function A(I,P,z,J){var _;return z===null?_=new Se:typeof z!="string"&&!P.objectMode&&(_=new Ee("chunk",["string","Buffer"],z)),!_||(K(I,_),l.nextTick(J,_),!1)}function C(I,P,z){return I.objectMode||I.decodeStrings===!1||typeof P!="string"||(P=$.from(P,z)),P}function M(I,P,z,J,_,o){if(!z){var h=C(P,J,_);J!==h&&(z=!0,_="buffer",J=h)}var m=P.objectMode?1:J.length;P.length+=m;var T=P.length<P.highWaterMark;if(T||(P.needDrain=!0),P.writing||P.corked){var D=P.lastBufferedRequest;P.lastBufferedRequest={chunk:J,encoding:_,isBuf:z,callback:o,next:null},D?D.next=P.lastBufferedRequest:P.bufferedRequest=P.lastBufferedRequest,P.bufferedRequestCount+=1}else b(I,P,!1,m,J,_,o);return T}function b(I,P,z,J,_,o,h){P.writelen=J,P.writecb=h,P.writing=!0,P.sync=!0,P.destroyed?P.onwrite(new ye("write")):z?I._writev(_,P.onwrite):I._write(_,o,P.onwrite),P.sync=!1}function x(I,P,z,J,_){--P.pendingcb,z?(l.nextTick(_,J),l.nextTick(F,I,P),I._writableState.errorEmitted=!0,K(I,J)):(_(J),I._writableState.errorEmitted=!0,K(I,J),F(I,P))}function E(I){I.writing=!1,I.writecb=null,I.length-=I.writelen,I.writelen=0}function j(I,P){var z=I._writableState,J=z.sync,_=z.writecb;if(typeof _!="function")throw new ie;if(E(z),P)x(I,z,J,P,_);else{var o=N(z)||I.destroyed;o||z.corked||z.bufferProcessing||!z.bufferedRequest||O(I,z),J?l.nextTick(k,I,z,o,_):k(I,z,o,_)}}function k(I,P,z,J){z||R(I,P),P.pendingcb--,J(),F(I,P)}function R(I,P){P.length===0&&P.needDrain&&(P.needDrain=!1,I.emit("drain"))}function O(I,P){P.bufferProcessing=!0;var z=P.bufferedRequest;if(I._writev&&z&&z.next){var J=P.bufferedRequestCount,_=Array(J),o=P.corkedRequestsFree;o.entry=z;for(var h=0,m=!0;z;)_[h]=z,z.isBuf||(m=!1),z=z.next,h+=1;_.allBuffers=m,b(I,P,!0,P.length,_,"",o.finish),P.pendingcb++,P.lastBufferedRequest=null,o.next?(P.corkedRequestsFree=o.next,o.next=null):P.corkedRequestsFree=new p(P),P.bufferedRequestCount=0}else{for(;z;){var T=z.chunk,D=z.encoding,U=z.callback,X=P.objectMode?1:T.length;if(b(I,P,!1,X,T,D,U),z=z.next,P.bufferedRequestCount--,P.writing)break}z===null&&(P.lastBufferedRequest=null)}P.bufferedRequest=z,P.bufferProcessing=!1}function N(I){return I.ending&&I.length===0&&I.bufferedRequest===null&&!I.finished&&!I.writing}function L(I,P){I._final(function(z){P.pendingcb--,z&&K(I,z),P.prefinished=!0,I.emit("prefinish"),F(I,P)})}function W(I,P){P.prefinished||P.finalCalled||(typeof I._final!="function"||P.destroyed?(P.prefinished=!0,I.emit("prefinish")):(P.pendingcb++,P.finalCalled=!0,l.nextTick(L,I,P)))}function F(I,P){var z=N(P);if(z&&(W(I,P),P.pendingcb===0&&(P.finished=!0,I.emit("finish"),P.autoDestroy))){var J=I._readableState;(!J||J.autoDestroy&&J.endEmitted)&&I.destroy()}return z}function V(I,P,z){P.ending=!0,F(I,P),z&&(P.finished?l.nextTick(z):I.once("finish",z)),P.ended=!0,I.writable=!1}function G(I,P,z){var J=I.entry;for(I.entry=null;J;){var _=J.callback;P.pendingcb--,_(z),J=J.next}P.corkedRequestsFree.next=I}c.exports=y;var Z;y.WritableState=g;var B={deprecate:a("util-deprecate")},H=a("./internal/streams/stream"),$=a("buffer").Buffer,ge=d.Uint8Array||function(){},fe=a("./internal/streams/destroy"),be=a("./internal/streams/state"),ce=be.getHighWaterMark,ee=a("../errors").codes,Ee=ee.ERR_INVALID_ARG_TYPE,Ve=ee.ERR_METHOD_NOT_IMPLEMENTED,ie=ee.ERR_MULTIPLE_CALLBACK,de=ee.ERR_STREAM_CANNOT_PIPE,ye=ee.ERR_STREAM_DESTROYED,Se=ee.ERR_STREAM_NULL_VALUES,q=ee.ERR_STREAM_WRITE_AFTER_END,Y=ee.ERR_UNKNOWN_ENCODING,K=fe.errorOrDestroy;a("inherits")(y,H),g.prototype.getBuffer=function(){for(var I=this.bufferedRequest,P=[];I;)P.push(I),I=I.next;return P},(function(){try{Object.defineProperty(g.prototype,"buffer",{get:B.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(I){return!!ae.call(this,I)||this===y&&I&&I._writableState instanceof g}})):ae=function(I){return I instanceof this},y.prototype.pipe=function(){K(this,new de)},y.prototype.write=function(I,P,z){var J=this._writableState,_=!1,o=!J.objectMode&&u(I);return o&&!$.isBuffer(I)&&(I=w(I)),typeof P=="function"&&(z=P,P=null),o?P="buffer":!P&&(P=J.defaultEncoding),typeof z!="function"&&(z=f),J.ending?v(this,z):(o||A(this,J,I,z))&&(J.pendingcb++,_=M(this,J,o,I,P,z)),_},y.prototype.cork=function(){this._writableState.corked++},y.prototype.uncork=function(){var I=this._writableState;I.corked&&(I.corked--,!I.writing&&!I.corked&&!I.bufferProcessing&&I.bufferedRequest&&O(this,I))},y.prototype.setDefaultEncoding=function(I){if(typeof I=="string"&&(I=I.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((I+"").toLowerCase())))throw new Y(I);return this._writableState.defaultEncoding=I,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(I,P,z){z(new Ve("_write()"))},y.prototype._writev=null,y.prototype.end=function(I,P,z){var J=this._writableState;return typeof I=="function"?(z=I,I=null,P=null):typeof P=="function"&&(z=P,P=null),I!=null&&this.write(I,P),J.corked&&(J.corked=1,this.uncork()),J.ending||V(this,J,z),this},Object.defineProperty(y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(y.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(I){this._writableState&&(this._writableState.destroyed=I)}}),y.prototype.destroy=fe.destroy,y.prototype._undestroy=fe.undestroy,y.prototype._destroy=function(I,P){P(I)}}).call(this)}).call(this,a("_process"),typeof Xe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Xe)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/destroy":23,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,inherits:10,"util-deprecate":32}],21:[function(a,c){(function(l){(function(){function d(R,O,N){return O in R?Object.defineProperty(R,O,{value:N,enumerable:!0,configurable:!0,writable:!0}):R[O]=N,R}function p(R,O){return{value:R,done:O}}function w(R){var O=R[v];if(O!==null){var N=R[E].read();N!==null&&(R[b]=null,R[v]=null,R[A]=null,O(p(N,!1)))}}function u(R){l.nextTick(w,R)}function f(R,O){return function(N,L){R.then(function(){return O[M]?void N(p(void 0,!0)):void O[x](N,L)},L)}}var g,y=a("./end-of-stream"),v=Symbol("lastResolve"),A=Symbol("lastReject"),C=Symbol("error"),M=Symbol("ended"),b=Symbol("lastPromise"),x=Symbol("handlePromise"),E=Symbol("stream"),j=Object.getPrototypeOf(function(){}),k=Object.setPrototypeOf((g={get stream(){return this[E]},next:function(){var R=this,O=this[C];if(O!==null)return Promise.reject(O);if(this[M])return Promise.resolve(p(void 0,!0));if(this[E].destroyed)return new Promise(function(F,V){l.nextTick(function(){R[C]?V(R[C]):F(p(void 0,!0))})});var N,L=this[b];if(L)N=new Promise(f(L,this));else{var W=this[E].read();if(W!==null)return Promise.resolve(p(W,!1));N=new Promise(this[x])}return this[b]=N,N}},d(g,Symbol.asyncIterator,function(){return this}),d(g,"return",function(){var R=this;return new Promise(function(O,N){R[E].destroy(null,function(L){return L?void N(L):void O(p(void 0,!0))})})}),g),j);c.exports=function(R){var O,N=Object.create(k,(O={},d(O,E,{value:R,writable:!0}),d(O,v,{value:null,writable:!0}),d(O,A,{value:null,writable:!0}),d(O,C,{value:null,writable:!0}),d(O,M,{value:R._readableState.endEmitted,writable:!0}),d(O,x,{value:function(L,W){var F=N[E].read();F?(N[b]=null,N[v]=null,N[A]=null,L(p(F,!1))):(N[v]=L,N[A]=W)},writable:!0}),O));return N[b]=null,y(R,function(L){if(L&&L.code!=="ERR_STREAM_PREMATURE_CLOSE"){var W=N[A];return W!==null&&(N[b]=null,N[v]=null,N[A]=null,W(L)),void(N[C]=L)}var F=N[v];F!==null&&(N[b]=null,N[v]=null,N[A]=null,F(p(void 0,!0))),N[M]=!0}),R.on("readable",u.bind(null,N)),N}}).call(this)}).call(this,a("_process"))},{"./end-of-stream":24,_process:12}],22:[function(a,c){function l(b,x){var E=Object.keys(b);if(Object.getOwnPropertySymbols){var j=Object.getOwnPropertySymbols(b);x&&(j=j.filter(function(k){return Object.getOwnPropertyDescriptor(b,k).enumerable})),E.push.apply(E,j)}return E}function d(b){for(var x,E=1;E<arguments.length;E++)x=arguments[E]==null?{}:arguments[E],E%2?l(Object(x),!0).forEach(function(j){p(b,j,x[j])}):Object.getOwnPropertyDescriptors?Object.defineProperties(b,Object.getOwnPropertyDescriptors(x)):l(Object(x)).forEach(function(j){Object.defineProperty(b,j,Object.getOwnPropertyDescriptor(x,j))});return b}function p(b,x,E){return x in b?Object.defineProperty(b,x,{value:E,enumerable:!0,configurable:!0,writable:!0}):b[x]=E,b}function w(b,x){if(!(b instanceof x))throw new TypeError("Cannot call a class as a function")}function u(b,x){for(var E,j=0;j<x.length;j++)E=x[j],E.enumerable=E.enumerable||!1,E.configurable=!0,"value"in E&&(E.writable=!0),Object.defineProperty(b,E.key,E)}function f(b,x,E){return x&&u(b.prototype,x),b}function g(b,x,E){v.prototype.copy.call(b,x,E)}var y=a("buffer"),v=y.Buffer,A=a("util"),C=A.inspect,M=C&&C.custom||"inspect";c.exports=(function(){function b(){w(this,b),this.head=null,this.tail=null,this.length=0}return f(b,[{key:"push",value:function(x){var E={data:x,next:null};0<this.length?this.tail.next=E:this.head=E,this.tail=E,++this.length}},{key:"unshift",value:function(x){var E={data:x,next:this.head};this.length===0&&(this.tail=E),this.head=E,++this.length}},{key:"shift",value:function(){if(this.length!==0){var x=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,x}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(x){if(this.length===0)return"";for(var E=this.head,j=""+E.data;E=E.next;)j+=x+E.data;return j}},{key:"concat",value:function(x){if(this.length===0)return v.alloc(0);for(var E=v.allocUnsafe(x>>>0),j=this.head,k=0;j;)g(j.data,E,k),k+=j.data.length,j=j.next;return E}},{key:"consume",value:function(x,E){var j;return x<this.head.data.length?(j=this.head.data.slice(0,x),this.head.data=this.head.data.slice(x)):x===this.head.data.length?j=this.shift():j=E?this._getString(x):this._getBuffer(x),j}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(x){var E=this.head,j=1,k=E.data;for(x-=k.length;E=E.next;){var R=E.data,O=x>R.length?R.length:x;if(k+=O===R.length?R:R.slice(0,x),x-=O,x===0){O===R.length?(++j,this.head=E.next?E.next:this.tail=null):(this.head=E,E.data=R.slice(O));break}++j}return this.length-=j,k}},{key:"_getBuffer",value:function(x){var E=v.allocUnsafe(x),j=this.head,k=1;for(j.data.copy(E),x-=j.data.length;j=j.next;){var R=j.data,O=x>R.length?R.length:x;if(R.copy(E,E.length-x,0,O),x-=O,x===0){O===R.length?(++k,this.head=j.next?j.next:this.tail=null):(this.head=j,j.data=R.slice(O));break}++k}return this.length-=k,E}},{key:M,value:function(x,E){return C(this,d({},E,{depth:0,customInspect:!1}))}}]),b})()},{buffer:3,util:2}],23:[function(a,c){(function(l){(function(){function d(u,f){w(u,f),p(u)}function p(u){u._writableState&&!u._writableState.emitClose||u._readableState&&!u._readableState.emitClose||u.emit("close")}function w(u,f){u.emit("error",f)}c.exports={destroy:function(u,f){var g=this,y=this._readableState&&this._readableState.destroyed,v=this._writableState&&this._writableState.destroyed;return y||v?(f?f(u):u&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,l.nextTick(w,this,u)):l.nextTick(w,this,u)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(u||null,function(A){!f&&A?g._writableState?g._writableState.errorEmitted?l.nextTick(p,g):(g._writableState.errorEmitted=!0,l.nextTick(d,g,A)):l.nextTick(d,g,A):f?(l.nextTick(p,g),f(A)):l.nextTick(p,g)}),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 g=u._readableState,y=u._writableState;g&&g.autoDestroy||y&&y.autoDestroy?u.destroy(f):u.emit("error",f)}}}).call(this)}).call(this,a("_process"))},{_process:12}],24:[function(a,c){function l(f){var g=!1;return function(){if(!g){g=!0;for(var y=arguments.length,v=Array(y),A=0;A<y;A++)v[A]=arguments[A];f.apply(this,v)}}}function d(){}function p(f){return f.setHeader&&typeof f.abort=="function"}function w(f,g,y){if(typeof g=="function")return w(f,null,g);g||(g={}),y=l(y||d);var v=g.readable||g.readable!==!1&&f.readable,A=g.writable||g.writable!==!1&&f.writable,C=function(){f.writable||b()},M=f._writableState&&f._writableState.finished,b=function(){A=!1,M=!0,v||y.call(f)},x=f._readableState&&f._readableState.endEmitted,E=function(){v=!1,x=!0,A||y.call(f)},j=function(O){y.call(f,O)},k=function(){var O;return v&&!x?(f._readableState&&f._readableState.ended||(O=new u),y.call(f,O)):A&&!M?(f._writableState&&f._writableState.ended||(O=new u),y.call(f,O)):void 0},R=function(){f.req.on("finish",b)};return p(f)?(f.on("complete",b),f.on("abort",k),f.req?R():f.on("request",R)):A&&!f._writableState&&(f.on("end",C),f.on("close",C)),f.on("end",E),f.on("finish",b),g.error!==!1&&f.on("error",j),f.on("close",k),function(){f.removeListener("complete",b),f.removeListener("abort",k),f.removeListener("request",R),f.req&&f.req.removeListener("finish",b),f.removeListener("end",C),f.removeListener("close",C),f.removeListener("finish",b),f.removeListener("end",E),f.removeListener("error",j),f.removeListener("close",k)}}var u=a("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;c.exports=w},{"../../../errors":15}],25:[function(a,c){c.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(a,c){function l(M){var b=!1;return function(){b||(b=!0,M.apply(void 0,arguments))}}function d(M){if(M)throw M}function p(M){return M.setHeader&&typeof M.abort=="function"}function w(M,b,x,E){E=l(E);var j=!1;M.on("close",function(){j=!0}),y===void 0&&(y=a("./end-of-stream")),y(M,{readable:b,writable:x},function(R){return R?E(R):(j=!0,void E())});var k=!1;return function(R){if(!j)return k?void 0:(k=!0,p(M)?M.abort():typeof M.destroy=="function"?M.destroy():void E(R||new C("pipe")))}}function u(M){M()}function f(M,b){return M.pipe(b)}function g(M){return M.length&&typeof M[M.length-1]=="function"?M.pop():d}var y,v=a("../../../errors").codes,A=v.ERR_MISSING_ARGS,C=v.ERR_STREAM_DESTROYED;c.exports=function(){for(var M=arguments.length,b=Array(M),x=0;x<M;x++)b[x]=arguments[x];var E=g(b);if(Array.isArray(b[0])&&(b=b[0]),2>b.length)throw new A("streams");var j,k=b.map(function(R,O){var N=O<b.length-1;return w(R,N,0<O,function(L){j||(j=L),L&&k.forEach(u),N||(k.forEach(u),E(j))})});return b.reduce(f)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(a,c){function l(p,w,u){return p.highWaterMark==null?w?p[u]:null:p.highWaterMark}var d=a("../../../errors").codes.ERR_INVALID_OPT_VALUE;c.exports={getHighWaterMark:function(p,w,u,f){var g=l(w,f,u);if(g!=null){if(!(isFinite(g)&&s(g)===g)||0>g){var y=f?u:"highWaterMark";throw new d(y,g)}return s(g)}return p.objectMode?16:16384}}},{"../../../errors":15}],28:[function(a,c){c.exports=a("events").EventEmitter},{events:7}],29:[function(a,c,l){l=c.exports=a("./lib/_stream_readable.js"),l.Stream=l,l.Readable=l,l.Writable=a("./lib/_stream_writable.js"),l.Duplex=a("./lib/_stream_duplex.js"),l.Transform=a("./lib/_stream_transform.js"),l.PassThrough=a("./lib/_stream_passthrough.js"),l.finished=a("./lib/internal/streams/end-of-stream.js"),l.pipeline=a("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(a,c,l){function d(f,g){for(var y in f)g[y]=f[y]}function p(f,g,y){return u(f,g,y)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var w=a("buffer"),u=w.Buffer;u.from&&u.alloc&&u.allocUnsafe&&u.allocUnsafeSlow?c.exports=w:(d(w,l),l.Buffer=p),p.prototype=Object.create(u.prototype),d(u,p),p.from=function(f,g,y){if(typeof f=="number")throw new TypeError("Argument must not be a number");return u(f,g,y)},p.alloc=function(f,g,y){if(typeof f!="number")throw new TypeError("Argument must be a number");var v=u(f);return g===void 0?v.fill(0):typeof y=="string"?v.fill(g,y):v.fill(g),v},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 w.SlowBuffer(f)}},{buffer:3}],31:[function(a,c,l){function d(k){if(!k)return"utf8";for(var R;;)switch(k){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 k;default:if(R)return;k=(""+k).toLowerCase(),R=!0}}function p(k){var R=d(k);if(typeof R!="string"&&(E.isEncoding===j||!j(k)))throw new Error("Unknown encoding: "+k);return R||k}function w(k){this.encoding=p(k);var R;switch(this.encoding){case"utf16le":this.text=v,this.end=A,R=4;break;case"utf8":this.fillLast=y,R=4;break;case"base64":this.text=C,this.end=M,R=3;break;default:return this.write=b,void(this.end=x)}this.lastNeed=0,this.lastTotal=0,this.lastChar=E.allocUnsafe(R)}function u(k){return 127>=k?0:k>>5==6?2:k>>4==14?3:k>>3==30?4:k>>6==2?-1:-2}function f(k,R,O){var N=R.length-1;if(N<O)return 0;var L=u(R[N]);return 0<=L?(0<L&&(k.lastNeed=L-1),L):--N<O||L===-2?0:(L=u(R[N]),0<=L?(0<L&&(k.lastNeed=L-2),L):--N<O||L===-2?0:(L=u(R[N]),0<=L?(0<L&&(L===2?L=0:k.lastNeed=L-3),L):0))}function g(k,R){if((192&R[0])!=128)return k.lastNeed=0,"�";if(1<k.lastNeed&&1<R.length){if((192&R[1])!=128)return k.lastNeed=1,"�";if(2<k.lastNeed&&2<R.length&&(192&R[2])!=128)return k.lastNeed=2,"�"}}function y(k){var R=this.lastTotal-this.lastNeed,O=g(this,k);return O===void 0?this.lastNeed<=k.length?(k.copy(this.lastChar,R,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(k.copy(this.lastChar,R,0,k.length),void(this.lastNeed-=k.length)):O}function v(k,R){if((k.length-R)%2==0){var O=k.toString("utf16le",R);if(O){var N=O.charCodeAt(O.length-1);if(55296<=N&&56319>=N)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=k[k.length-2],this.lastChar[1]=k[k.length-1],O.slice(0,-1)}return O}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=k[k.length-1],k.toString("utf16le",R,k.length-1)}function A(k){var R=k&&k.length?this.write(k):"";if(this.lastNeed){var O=this.lastTotal-this.lastNeed;return R+this.lastChar.toString("utf16le",0,O)}return R}function C(k,R){var O=(k.length-R)%3;return O==0?k.toString("base64",R):(this.lastNeed=3-O,this.lastTotal=3,O==1?this.lastChar[0]=k[k.length-1]:(this.lastChar[0]=k[k.length-2],this.lastChar[1]=k[k.length-1]),k.toString("base64",R,k.length-O))}function M(k){var R=k&&k.length?this.write(k):"";return this.lastNeed?R+this.lastChar.toString("base64",0,3-this.lastNeed):R}function b(k){return k.toString(this.encoding)}function x(k){return k&&k.length?this.write(k):""}var E=a("safe-buffer").Buffer,j=E.isEncoding||function(k){switch(k=""+k,k&&k.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};l.StringDecoder=w,w.prototype.write=function(k){if(k.length===0)return"";var R,O;if(this.lastNeed){if(R=this.fillLast(k),R===void 0)return"";O=this.lastNeed,this.lastNeed=0}else O=0;return O<k.length?R?R+this.text(k,O):this.text(k,O):R||""},w.prototype.end=function(k){var R=k&&k.length?this.write(k):"";return this.lastNeed?R+"�":R},w.prototype.text=function(k,R){var O=f(this,k,R);if(!this.lastNeed)return k.toString("utf8",R);this.lastTotal=O;var N=k.length-(O-this.lastNeed);return k.copy(this.lastChar,0,N),k.toString("utf8",R,N)},w.prototype.fillLast=function(k){return this.lastNeed<=k.length?(k.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(k.copy(this.lastChar,this.lastTotal-this.lastNeed,0,k.length),void(this.lastNeed-=k.length))}},{"safe-buffer":30}],32:[function(a,c){(function(l){(function(){function d(p){try{if(!l.localStorage)return!1}catch{return!1}var w=l.localStorage[p];return w!=null&&(w+"").toLowerCase()==="true"}c.exports=function(p,w){function u(){if(!f){if(d("throwDeprecation"))throw new Error(w);d("traceDeprecation")?console.trace(w):console.warn(w),f=!0}return p.apply(this,arguments)}if(d("noDeprecation"))return p;var f=!1;return u}}).call(this)}).call(this,typeof Xe>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:Xe)},{}],"/":[function(a,c){function l(M){return M.replace(/a=ice-options:trickle\s\n/g,"")}function d(M){console.warn(M)}/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const p=a("debug")("simple-peer"),w=a("get-browser-rtc"),u=a("randombytes"),f=a("readable-stream"),g=a("queue-microtask"),y=a("err-code"),{Buffer:v}=a("buffer"),A=65536;class C extends f.Duplex{constructor(b){if(b=Object.assign({allowHalfOpen:!1},b),super(b),this._id=u(4).toString("hex").slice(0,7),this._debug("new peer %o",b),this.channelName=b.initiator?b.channelName||u(20).toString("hex"):null,this.initiator=b.initiator||!1,this.channelConfig=b.channelConfig||C.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},C.config,b.config),this.offerOptions=b.offerOptions||{},this.answerOptions=b.answerOptions||{},this.sdpTransform=b.sdpTransform||(x=>x),this.streams=b.streams||(b.stream?[b.stream]:[]),this.trickle=b.trickle===void 0||b.trickle,this.allowHalfTrickle=b.allowHalfTrickle!==void 0&&b.allowHalfTrickle,this.iceCompleteTimeout=b.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=b.wrtc&&typeof b.wrtc=="object"?b.wrtc:w(),!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(x){return void this.destroy(y(x,"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=x=>{this._onIceCandidate(x)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(x=>{this.destroy(y(x,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=x=>{this._setupData(x)},this.streams&&this.streams.forEach(x=>{this.addStream(x)}),this._pc.ontrack=x=>{this._onTrack(x)},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(b){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof b=="string")try{b=JSON.parse(b)}catch{b={}}this._debug("signal()"),b.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),b.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(b.transceiverRequest.kind,b.transceiverRequest.init)),b.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(b.candidate):this._pendingCandidates.push(b.candidate)),b.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(b)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(x=>{this._addIceCandidate(x)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(x=>{this.destroy(y(x,"ERR_SET_REMOTE_DESCRIPTION"))}),b.sdp||b.candidate||b.renegotiate||b.transceiverRequest||this.destroy(y(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(b){const x=new this._wrtc.RTCIceCandidate(b);this._pc.addIceCandidate(x).catch(E=>{!x.address||x.address.endsWith(".local")?d("Ignoring unsupported ICE candidate."):this.destroy(y(E,"ERR_ADD_ICE_CANDIDATE"))})}send(b){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(b)}}addTransceiver(b,x){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(b,x),this._needsNegotiation()}catch(E){this.destroy(y(E,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:b,init:x}})}}addStream(b){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),b.getTracks().forEach(x=>{this.addTrack(x,b)})}}addTrack(b,x){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const E=this._senderMap.get(b)||new Map;let j=E.get(x);if(!j)j=this._pc.addTrack(b,x),E.set(x,j),this._senderMap.set(b,E),this._needsNegotiation();else throw j.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(b,x,E){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const j=this._senderMap.get(b),k=j?j.get(E):null;if(!k)throw y(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");x&&this._senderMap.set(x,j),k.replaceTrack==null?this.destroy(y(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):k.replaceTrack(x)}removeTrack(b,x){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const E=this._senderMap.get(b),j=E?E.get(x):null;if(!j)throw y(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{j.removed=!0,this._pc.removeTrack(j)}catch(k){k.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(j):this.destroy(y(k,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(b){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),b.getTracks().forEach(x=>{this.removeTrack(x,b)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,g(()=>{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(b){this._destroy(b,()=>{})}_destroy(b,x){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",b&&(b.message||b)),g(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",b&&(b.message||b)),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,b&&this.emit("error",b),this.emit("close"),x()}))}_setupData(b){if(!b.channel)return this.destroy(y(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=b.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=A),this.channelName=this._channel.label,this._channel.onmessage=E=>{this._onChannelMessage(E)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=E=>{const j=E.error instanceof Error?E.error:new Error(`Datachannel error: ${E.message} ${E.filename}:${E.lineno}:${E.colno}`);this.destroy(y(j,"ERR_DATA_CHANNEL"))};let x=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(x&&this._onChannelClose(),x=!0):x=!1},5e3)}_read(){}_write(b,x,E){if(this.destroyed)return E(y(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(b)}catch(j){return this.destroy(y(j,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>A?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=E):E(null)}else this._debug("write before connect"),this._chunk=b,this._cb=E}_onFinish(){if(!this.destroyed){const b=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?b():this.once("connect",b)}}_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(b=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(b.sdp=l(b.sdp)),b.sdp=this.sdpTransform(b.sdp);const x=()=>{if(!this.destroyed){const E=this._pc.localDescription||b;this._debug("signal"),this.emit("signal",{type:E.type,sdp:E.sdp})}};this._pc.setLocalDescription(b).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?x():this.once("_iceComplete",x))}).catch(E=>{this.destroy(y(E,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(b=>{this.destroy(y(b,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(b=>{b.mid||!b.sender.track||b.requested||(b.requested=!0,this.addTransceiver(b.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(b=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(b.sdp=l(b.sdp)),b.sdp=this.sdpTransform(b.sdp);const x=()=>{if(!this.destroyed){const E=this._pc.localDescription||b;this._debug("signal"),this.emit("signal",{type:E.type,sdp:E.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(b).then(()=>{this.destroyed||(this.trickle||this._iceComplete?x():this.once("_iceComplete",x))}).catch(E=>{this.destroy(y(E,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(b=>{this.destroy(y(b,"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 b=this._pc.iceConnectionState,x=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",b,x),this.emit("iceStateChange",b,x),(b==="connected"||b==="completed")&&(this._pcReady=!0,this._maybeReady()),b==="failed"&&this.destroy(y(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),b==="closed"&&this.destroy(y(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(b){const x=E=>(Object.prototype.toString.call(E.values)==="[object Array]"&&E.values.forEach(j=>{Object.assign(E,j)}),E);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(E=>{const j=[];E.forEach(k=>{j.push(x(k))}),b(null,j)},E=>b(E)):0<this._pc.getStats.length?this._pc.getStats(E=>{if(this.destroyed)return;const j=[];E.result().forEach(k=>{const R={};k.names().forEach(O=>{R[O]=k.stat(O)}),R.id=k.id,R.type=k.type,R.timestamp=k.timestamp,j.push(x(R))}),b(null,j)},E=>b(E)):b(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 b=()=>{this.destroyed||this.getStats((x,E)=>{if(this.destroyed)return;x&&(E=[]);const j={},k={},R={};let O=!1;E.forEach(L=>{(L.type==="remotecandidate"||L.type==="remote-candidate")&&(j[L.id]=L),(L.type==="localcandidate"||L.type==="local-candidate")&&(k[L.id]=L),(L.type==="candidatepair"||L.type==="candidate-pair")&&(R[L.id]=L)});const N=L=>{O=!0;let W=k[L.localCandidateId];W&&(W.ip||W.address)?(this.localAddress=W.ip||W.address,this.localPort=+W.port):W&&W.ipAddress?(this.localAddress=W.ipAddress,this.localPort=+W.portNumber):typeof L.googLocalAddress=="string"&&(W=L.googLocalAddress.split(":"),this.localAddress=W[0],this.localPort=+W[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let F=j[L.remoteCandidateId];F&&(F.ip||F.address)?(this.remoteAddress=F.ip||F.address,this.remotePort=+F.port):F&&F.ipAddress?(this.remoteAddress=F.ipAddress,this.remotePort=+F.portNumber):typeof L.googRemoteAddress=="string"&&(F=L.googRemoteAddress.split(":"),this.remoteAddress=F[0],this.remotePort=+F[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(E.forEach(L=>{L.type==="transport"&&L.selectedCandidatePairId&&N(R[L.selectedCandidatePairId]),(L.type==="googCandidatePair"&&L.googActiveConnection==="true"||(L.type==="candidatepair"||L.type==="candidate-pair")&&L.selected)&&N(L)}),!O&&(!Object.keys(R).length||Object.keys(k).length))return void setTimeout(b,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(W){return this.destroy(y(W,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const L=this._cb;this._cb=null,L(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};b()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>A)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(b=>{this._pc.removeTrack(b),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(b){this.destroyed||(b.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:b.candidate.candidate,sdpMLineIndex:b.candidate.sdpMLineIndex,sdpMid:b.candidate.sdpMid}}):!b.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),b.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(b){if(this.destroyed)return;let x=b.data;x instanceof ArrayBuffer&&(x=v.from(x)),this.push(x)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const b=this._cb;this._cb=null,b(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(b){this.destroyed||b.streams.forEach(x=>{this._debug("on track"),this.emit("track",b.track,x),this._remoteTracks.push({track:b.track,stream:x}),this._remoteStreams.some(E=>E.id===x.id)||(this._remoteStreams.push(x),g(()=>{this._debug("on stream"),this.emit("stream",x)}))})}_debug(){const b=[].slice.call(arguments);b[0]="["+this._id+"] "+b[0],p.apply(null,b)}}C.WEBRTC_SUPPORT=!!w(),C.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},C.channelConfig={},c.exports=C},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(Wn)),Wn.exports}var Jh=Kh();const Xh=Qa(Jh),Gr=0,Yr=1,Na=2,Ca=(t,e)=>{Q(t,Gr);const s=ku(e);ve(t,s)},Ta=(t,e,s)=>{Q(t,Yr),ve(t,Ur(e,s))},Zh=(t,e,s)=>Ta(e,s,Te(t)),Aa=(t,e,s,n)=>{try{Go(e,Te(t),s)}catch(i){n!=null&&n(i),console.error("Caught error while handling a Yjs update",i)}},Qh=(t,e)=>{Q(t,Na),ve(t,e)},ef=Aa,tf=(t,e,s,n,i)=>{const a=ne(t);switch(a){case Gr:Zh(t,e,s);break;case Yr:Aa(t,s,n,i);break;case Na:ef(t,s,n,i);break;default:throw new Error("Unknown message type")}return a},Bn=3e4;class sf extends xr{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const s=lt();this.getLocalState()!==null&&Bn/2<=s-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const n=[];this.meta.forEach((i,a)=>{a!==this.clientID&&Bn<=s-i.lastUpdated&&this.states.has(a)&&n.push(a)}),n.length>0&&rr(this,n,"timeout")},Ye(Bn/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,n=this.meta.get(s),i=n===void 0?0:n.clock+1,a=this.states.get(s);e===null?this.states.delete(s):this.states.set(s,e),this.meta.set(s,{clock:i,lastUpdated:lt()});const c=[],l=[],d=[],p=[];e===null?p.push(s):a==null?e!=null&&c.push(s):(l.push(s),Pt(a,e)||d.push(s)),(c.length>0||d.length>0||p.length>0)&&this.emit("change",[{added:c,updated:d,removed:p},"local"]),this.emit("update",[{added:c,updated:l,removed:p},"local"])}setLocalStateField(e,s){const n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:s})}getStates(){return this.states}}const rr=(t,e,s)=>{const n=[];for(let i=0;i<e.length;i++){const a=e[i];if(t.states.has(a)){if(t.states.delete(a),a===t.clientID){const c=t.meta.get(a);t.meta.set(a,{clock:c.clock+1,lastUpdated:lt()})}n.push(a)}}n.length>0&&(t.emit("change",[{added:[],updated:[],removed:n},s]),t.emit("update",[{added:[],updated:[],removed:n},s]))},Zs=(t,e,s=t.states)=>{const n=e.length,i=Ae();Q(i,n);for(let a=0;a<n;a++){const c=e[a],l=s.get(c)||null,d=t.meta.get(c).clock;Q(i,c),Q(i,d),Qe(i,JSON.stringify(l))}return xe(i)},nf=(t,e,s)=>{const n=st(e),i=lt(),a=[],c=[],l=[],d=[],p=ne(n);for(let w=0;w<p;w++){const u=ne(n);let f=ne(n);const g=JSON.parse(ot(n)),y=t.meta.get(u),v=t.states.get(u),A=y===void 0?0:y.clock;(A<f||A===f&&g===null&&t.states.has(u))&&(g===null?u===t.clientID&&t.getLocalState()!=null?f++:t.states.delete(u):t.states.set(u,g),t.meta.set(u,{clock:f,lastUpdated:i}),y===void 0&&g!==null?a.push(u):y!==void 0&&g===null?d.push(u):g!==null&&(Pt(g,v)||l.push(u),c.push(u)))}(a.length>0||l.length>0||d.length>0)&&t.emit("change",[{added:a,updated:l,removed:d},s]),(a.length>0||c.length>0||d.length>0)&&t.emit("update",[{added:a,updated:c,removed:d},s])},rf=(t,e)=>{const s=Kn(t).buffer,n=Kn(e).buffer;return crypto.subtle.importKey("raw",s,"PBKDF2",!1,["deriveKey"]).then(i=>crypto.subtle.deriveKey({name:"PBKDF2",salt:n,iterations:1e5,hash:"SHA-256"},i,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))},Ra=(t,e)=>{if(!e)return jr(t);const s=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,t).then(n=>{const i=Ae();return Qe(i,"AES-GCM"),ve(i,s),ve(i,new Uint8Array(n)),xe(i)})},of=(t,e)=>{const s=Ae();return $t(s,t),Ra(xe(s),e)},La=(t,e)=>{if(!e)return jr(t);const s=st(t);ot(s)!=="AES-GCM"&&Yc(ze("Unknown encryption algorithm"));const i=Te(s),a=Te(s);return crypto.subtle.decrypt({name:"AES-GCM",iv:i},e,a).then(c=>new Uint8Array(c))},af=(t,e)=>La(t,e).then(s=>zt(st(new Uint8Array(s)))),Be=ou("y-webrtc"),Ft=0,Ia=3,ys=1,Kr=4,Qs=new Map,_t=new Map,Da=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}]),Be("synced ",Ge,t.name,Et," with all peers"))},Ma=(t,e,s)=>{const n=st(e),i=Ae(),a=ne(n);if(t===void 0)return null;const c=t.awareness,l=t.doc;let d=!1;switch(a){case Ft:{Q(i,Ft);const p=tf(n,i,l,t);p===Yr&&!t.synced&&s(),p===Gr&&(d=!0);break}case Ia:Q(i,ys),ve(i,Zs(c,Array.from(c.getStates().keys()))),d=!0;break;case ys:nf(c,Te(n),t);break;case Kr:{const p=kt(n)===1,w=ot(n);if(w!==t.peerId&&(t.bcConns.has(w)&&!p||!t.bcConns.has(w)&&p)){const u=[],f=[];p?(t.bcConns.add(w),f.push(w)):(t.bcConns.delete(w),u.push(w)),t.provider.emit("peers",[{added:f,removed:u,webrtcPeers:Array.from(t.webrtcConns.keys()),bcPeers:Array.from(t.bcConns)}]),Oa(t)}break}default:return console.error("Unable to compute message"),i}return d?i:null},lf=(t,e)=>{const s=t.room;return Be("received message from ",Ge,t.remotePeerId,Dr," (",s.name,")",Et,bn),Ma(s,e,()=>{t.synced=!0,Be("synced ",Ge,s.name,Et," with ",Ge,t.remotePeerId),Da(s)})},Fn=(t,e)=>{Be("send message to ",Ge,t.remotePeerId,Et,Dr," (",t.room.name,")",bn);try{t.peer.send(xe(e))}catch{}},cf=(t,e)=>{Be("broadcast message in ",Ge,t.name,Et),t.webrtcConns.forEach(s=>{try{s.peer.send(e)}catch{}})};class Si{constructor(e,s,n,i){Be("establishing connection to ",Ge,n),this.room=i,this.remotePeerId=n,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new Xh({initiator:s,...i.provider.peerOpts}),this.peer.on("signal",a=>{this.glareToken===void 0&&(this.glareToken=Date.now()+Math.random()),Jr(e,i,{to:n,from:i.peerId,type:"signal",token:this.glareToken,signal:a})}),this.peer.on("connect",()=>{Be("connected to ",Ge,n),this.connected=!0;const c=i.provider.doc,l=i.awareness,d=Ae();Q(d,Ft),Ca(d,c),Fn(this,d);const p=l.getStates();if(p.size>0){const w=Ae();Q(w,ys),ve(w,Zs(l,Array.from(p.keys()))),Fn(this,w)}}),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)}])),Da(i),this.peer.destroy(),Be("closed connection to ",Ge,n),ir(i)}),this.peer.on("error",a=>{Be("Error in connection to ",Ge,n,": ",a),ir(i)}),this.peer.on("data",a=>{const c=lf(this,a);c!==null&&Fn(this,c)})}destroy(){this.peer.destroy()}}const ht=(t,e)=>Ra(e,t.key).then(s=>t.mux(()=>Gh(t.name,s))),ji=(t,e)=>{t.bcconnected&&ht(t,e),cf(t,e)},ir=t=>{Qs.forEach(e=>{e.connected&&(e.send({type:"subscribe",topics:[t.name]}),t.webrtcConns.size<t.provider.maxConns&&Jr(e,t,{type:"announce",from:t.peerId}))})},Oa=t=>{if(t.provider.filterBcConns){const e=Ae();Q(e,Kr),ds(e,1),Qe(e,t.peerId),ht(t,xe(e))}};class df{constructor(e,s,n,i){this.peerId=no(),this.doc=e,this.awareness=s.awareness,this.provider=s,this.synced=!1,this.name=n,this.key=i,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=Yh(),this.bcconnected=!1,this._bcSubscriber=a=>La(new Uint8Array(a),i).then(c=>this.mux(()=>{const l=Ma(this,c,()=>{});l&&ht(this,xe(l))})),this._docUpdateHandler=(a,c)=>{const l=Ae();Q(l,Ft),Qh(l,a),ji(this,xe(l))},this._awarenessUpdateHandler=({added:a,updated:c,removed:l},d)=>{const p=a.concat(c).concat(l),w=Ae();Q(w,ys),ve(w,Zs(this.awareness,p)),ji(this,xe(w))},this._beforeUnloadHandler=()=>{rr(this.awareness,[e.clientID],"window unload"),_t.forEach(a=>{a.disconnect()})},typeof window<"u"?window.addEventListener("beforeunload",this._beforeUnloadHandler):typeof process<"u"&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),ir(this);const e=this.name;Hh(e,this._bcSubscriber),this.bcconnected=!0,Oa(this);const s=Ae();Q(s,Ft),Ca(s,this.doc),ht(this,xe(s));const n=Ae();Q(n,Ft),Ta(n,this.doc),ht(this,xe(n));const i=Ae();Q(i,Ia),ht(this,xe(i));const a=Ae();Q(a,ys),ve(a,Zs(this.awareness,[this.doc.clientID])),ht(this,xe(a))}disconnect(){Qs.forEach(s=>{s.connected&&s.send({type:"unsubscribe",topics:[this.name]})}),rr(this.awareness,[this.doc.clientID],"disconnect");const e=Ae();Q(e,Kr),ds(e,0),Qe(e,this.peerId),ht(this,xe(e)),qh(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 uf=(t,e,s,n)=>{if(_t.has(s))throw ze(`A Yjs Doc connected to room "${s}" already exists!`);const i=new df(t,e,s,n);return _t.set(s,i),i},Jr=(t,e,s)=>{e.key?of(s,e.key).then(n=>{t.send({type:"publish",topic:e.name,data:fo(n)})}):t.send({type:"publish",topic:e.name,data:s})};class hf extends $h{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{Be(`connected (${e})`);const s=Array.from(_t.keys());this.send({type:"subscribe",topics:s}),_t.forEach(n=>Jr(this,n,{type:"announce",from:n.peerId}))}),this.on("message",s=>{switch(s.type){case"publish":{const n=s.topic,i=_t.get(n);if(i==null||typeof n!="string")return;const a=c=>{const l=i.webrtcConns,d=i.peerId;if(c==null||c.from===d||c.to!==void 0&&c.to!==d||i.bcConns.has(c.from))return;const p=l.has(c.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[c.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(c.type){case"announce":l.size<i.provider.maxConns&&($e(l,c.from,()=>new Si(this,!0,c.from,i)),p());break;case"signal":if(c.signal.type==="offer"){const w=l.get(c.from);if(w){const u=c.token,f=w.glareToken;if(f&&f>u){Be("offer rejected: ",c.from);return}w.glareToken=void 0}}if(c.signal.type==="answer"){Be("offer answered by: ",c.from);const w=l.get(c.from);w.glareToken=void 0}c.to===d&&($e(l,c.from,()=>new Si(this,!1,c.from,i)).peer.signal(c.signal),p());break}};i.key?typeof s.data=="string"&&af(po(s.data),i.key).then(a):a(s.data)}}}),this.on("disconnect",()=>Be(`disconnect (${e})`))}}const $n=t=>{t.emit("status",[{connected:t.connected}])};class ff extends Xi{constructor(e,s,{signaling:n=["wss://y-webrtc-eu.fly.dev"],password:i=null,awareness:a=new sf(s),maxConns:c=20+Ye(qc()*15),filterBcConns:l=!0,peerOpts:d={}}={}){super(),this.roomName=e,this.doc=s,this.filterBcConns=l,this.awareness=a,this.shouldConnect=!1,this.signalingUrls=n,this.signalingConns=[],this.maxConns=c,this.peerOpts=d,this.key=i?rf(i,e):jr(null),this.room=null,this.key.then(p=>{this.room=uf(s,this,e,p),this.shouldConnect?this.room.connect():this.room.disconnect(),$n(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=$e(Qs,e,()=>new hf(e));this.signalingConns.push(s),s.providers.add(this)}),this.room&&(this.room.connect(),$n(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),e.providers.size===0&&(e.destroy(),Qs.delete(e.url))}),this.room&&(this.room.disconnect(),$n(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),_t.delete(this.roomName)}),super.destroy()}}const is=new Map,en=new Map,or=new Map;function pf(){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem("titan2:webrtc"))==="1"}catch{return!1}}function gf(t){if(!is.has(t)){const e=new Qt({guid:`titan-space-${t}`});is.set(t,e);const s=new Wh(`titan-space-${t}`,e);if(en.set(t,s),pf())try{const n=new ff(`titan-space-${t}`,e,{signaling:["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com"]});or.set(t,n)}catch{}}return is.get(t)}function mf(t){const{widgets:e}=bt(t),s=new Set,n=[];e.forEach((i,a)=>{const c=i.get("id");typeof c!="string"||s.has(c)?n.push(a):s.add(c)});for(let i=n.length-1;i>=0;i--)e.delete(n[i],1);return n.length}function bt(t){const e=gf(t),s=e.getArray("widgets"),n=e.getMap("meta"),i=en.get(t);return{widgets:s,meta:n,doc:e,whenSynced:i!=null&&i.synced?Promise.resolve():new Promise(a=>{const c=()=>{i==null||i.off("synced",c),a()};i==null||i.on("synced",c),setTimeout(()=>a(),2e3)})}}function yf(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 Pa(t){const e=new jt;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 wf(t){try{const e=typeof localStorage<"u"?localStorage.getItem("titan2-spaces"):null;if(!e)return null;const n=JSON.parse(e).find(a=>a.id===t);if(!n)return null;const i=new Set;for(const a of n.widgets||[])a&&typeof a.id=="string"&&i.add(a.id);return i}catch{return null}}const tn=new Map;function bf(t,e){let s=tn.get(t);s||(s=new Set,tn.set(t,s)),s.add(e)}function xf(t,e){var s;return((s=tn.get(t))==null?void 0:s.has(e))??!1}function Ua(t){tn.delete(t)}function vf(t,e){const{widgets:s}=bt(t),n=new Map,i=()=>{const c=new Set,l=wf(t),d=[];s.forEach(p=>{const w=yf(p);if(!w.id||c.has(w.id))return;const u=w.format==="system",f=typeof w.source=="string"&&w.source.trim()!=="";!u&&!f||l&&!l.has(w.id)&&!xf(t,w.id)||(c.add(w.id),d.push(w))}),e(d)},a=()=>{const c=new Set;s.forEach(l=>c.add(l));for(const[l,d]of n)c.has(l)||(l.unobserve(d),n.delete(l));for(const l of c)if(!n.has(l)){const d=()=>i();l.observe(d),n.set(l,d)}i()};return s.observe(a),a(),()=>{s.unobserve(a);for(const[c,l]of n)c.unobserve(l);n.clear()}}function _f(t,e){const{widgets:s}=bt(t),n={...e,id:`widget_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,createdAt:Date.now(),updatedAt:Date.now()};return bf(t,n.id),s.push([Pa(n)]),n}function kf(t,e){const{widgets:s}=bt(t);let n=-1;s.forEach((i,a)=>{i.get("id")===e&&(n=a)}),n>=0&&s.delete(n,1)}function Ni(t,e,s){const{widgets:n}=bt(t);n.forEach(i=>{if(i.get("id")===e){for(const[a,c]of Object.entries(s))i.set(a,c);i.set("updatedAt",Date.now())}})}function Ef(t){const{widgets:e}=bt(t);e.delete(0,e.length),Ua(t)}function Sf(t){var e,s,n;(e=en.get(t))==null||e.destroy(),(s=or.get(t))==null||s.destroy(),(n=is.get(t))==null||n.destroy(),en.delete(t),or.delete(t),is.delete(t),Ua(t)}const Os="titan2-spaces",jf=!0;function oe(t,e,s,n,i,a,c){return{id:t,name:e,format:"system",source:s,x:n,y:i,w:a,h:c,createdAt:Date.now(),updatedAt:Date.now()}}const Ts=[{id:"home",name:"Home",icon:"Home",color:"#6366f1",widgets:[oe("home-welcome","Welcome","system:soma",0,0,6,5),oe("home-voice","Voice","system:voice",6,0,6,5),oe("home-overview","Overview","system:overview",0,5,6,5),oe("home-sessions","Sessions","system:sessions",6,5,6,5),oe("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:[oe("soma-main","SOMA","system:soma",0,0,8,8),oe("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:[oe("cp-hub","Command Post","system:command-post",0,0,12,10),oe("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:[oe("intel-autopilot","Autopilot","system:intelligence-autopilot",0,0,6,5),oe("intel-workflows","Workflows","system:intelligence-workflows",6,0,6,5),oe("intel-learning","Learning","system:intelligence-learning",0,5,6,5),oe("intel-memory","Memory Graph","system:memory-graph",6,5,6,5),oe("intel-selfimprove","Self-Improve","system:intelligence-self-improve",0,10,6,5),oe("intel-personas","Personas","system:intelligence-personas",6,10,6,5),oe("intel-wiki","Memory Wiki","system:memory-wiki",0,15,6,6),oe("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:[oe("infra-homelab","Homelab","system:infra-homelab",0,0,6,6),oe("infra-gpu","GPU / NVIDIA","system:infra-gpu",6,0,6,6),oe("infra-files","Files","system:infra-files",0,6,4,5),oe("infra-logs","Logs","system:infra-logs",4,6,4,5),oe("infra-telemetry","Telemetry","system:infra-telemetry",8,6,4,5),oe("infra-vram","VRAM","system:vram",0,11,6,5),oe("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:[oe("tools-skills","Skills","system:tools-skills",0,0,6,6),oe("tools-mcp","MCP Servers","system:tools-mcp",6,0,6,6),oe("tools-integrations","Integrations","system:tools-integrations",0,6,4,5),oe("tools-channels","Channels","system:tools-channels",4,6,4,5),oe("tools-mesh","Mesh Network","system:tools-mesh",8,6,4,5),oe("tools-recipes","Recipes","system:recipes",0,11,6,5),oe("tools-paperclip","Paperclip","system:paperclip",6,11,6,5),oe("tools-browser","Browser","system:browser",0,16,6,5),oe("tools-cron","Cron","system:cron",6,16,6,5)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"settings",name:"Settings",icon:"Settings",color:"#6b7280",widgets:[oe("settings-specialists","Specialist Models","system:settings-specialists",0,0,6,8),oe("settings-privacy","Privacy & Telemetry","system:settings-privacy",6,0,6,8),oe("settings-general","General","system:settings-general",0,8,6,8),oe("settings-security","Security","system:settings-security",6,8,6,8),oe("settings-audit","Audit Log","system:settings-audit",0,16,12,6)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}],ar=11,Nf={home:new Set(["home-chat"])};function Cf(t,e){const{widgets:s,meta:n,whenSynced:i}=bt(t.id);i.then(()=>{try{const a=mf(t.id);if(a>0&&console.info(`[SpaceEngine] healed ${a} duplicate widget(s) in "${t.id}"`),e){const c=Nf[t.id]??new Set;for(let p=s.length-1;p>=0;p--){const w=s.get(p),u=w==null?void 0:w.get("id");typeof u=="string"&&c.has(u)&&s.delete(p,1)}for(let p=s.length-1;p>=0;p--){const w=s.get(p),u=w==null?void 0:w.get("source");(typeof u!="string"||u.trim()==="")&&s.delete(p,1)}const l=new Map;for(const p of t.widgets)l.set(p.id,p);const d=new Set;s.forEach(p=>{const w=p.get("id");if(typeof w=="string"&&l.has(w)){d.add(w);const u=l.get(w);p.set("x",u.x),p.set("y",u.y),p.set("w",u.w),p.set("h",u.h)}});for(const p of t.widgets)d.has(p.id)||s.push([Pa(p)]);n.set("seedVersion",ar)}}catch(a){console.warn(`[SpaceEngine] healYSpaceOnSync failed for "${t.id}":`,a)}})}function Tf(){try{const t=localStorage.getItem(Os),s=parseInt(localStorage.getItem(`${Os}-version`)||"0",10)<ar;if(jf)for(const a of Ts)Cf(a,s);if(!t||s){localStorage.setItem(`${Os}-version`,String(ar));const a=Ts.map(c=>({...c,widgets:[...c.widgets]}));return ns(a),a}const n=JSON.parse(t);for(const a of n)Array.isArray(a.widgets)||(a.widgets=[]),a.widgets=a.widgets.filter(c=>c&&typeof c.id=="string").map(c=>({...c,x:Number.isFinite(c.x)?Math.max(0,Math.floor(c.x)):0,y:Number.isFinite(c.y)?Math.max(0,Math.floor(c.y)):0,w:Number.isFinite(c.w)?Math.max(1,Math.floor(c.w)):4,h:Number.isFinite(c.h)?Math.max(1,Math.floor(c.h)):4}));for(const a of n){const c=new Set;a.widgets=a.widgets.filter(l=>c.has(l.id)?!1:(c.add(l.id),!0))}const i=new Map(n.map(a=>[a.id,a]));return Ts.forEach(a=>{const c=i.get(a.id);c?c.widgets.length===0&&a.widgets.length>0&&(c.widgets=a.widgets.map(l=>({...l}))):i.set(a.id,{...a,widgets:[...a.widgets]})}),Array.from(i.values())}catch{return Ts.map(t=>({...t,widgets:[...t.widgets]}))}}let zn=null;function ns(t){zn&&clearTimeout(zn),zn=setTimeout(()=>{localStorage.setItem(Os,JSON.stringify(t))},250)}let rt=null;const _e={list(){return rt||(rt=Tf()),rt},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 rt=[...this.list(),e],ns(rt),e},save(t){t.updatedAt=new Date().toISOString(),rt=this.list().map(e=>e.id===t.id?t:e),ns(rt)},remove(t){rt=this.list().filter(e=>e.id!==t),ns(rt)},addWidget(t,e){if(!e.source||e.source.trim()==="")throw new Error("Widget source cannot be empty");{const s=_f(t,e),n=this.get(t);return n&&(n.widgets=[...n.widgets,s],this.save(n)),s}},updateWidget(t,e,s){Ni(t,e,s);const n=this.get(t);n&&(n.widgets=n.widgets.map(i=>i.id===e?{...i,...s,updatedAt:Date.now()}:i),this.save(n))},removeWidget(t,e){kf(t,e);const s=this.get(t);s&&(s.widgets=s.widgets.filter(n=>n.id!==e),this.save(s))},updateLayout(t,e){for(const n of e)Ni(t,n.i,{x:n.x,y:n.y,w:n.w,h:n.h});const s=this.get(t);s&&(s.widgets=s.widgets.map(n=>{const i=e.find(a=>a&&a.i===n.id);return i?{...n,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()}:n}),this.save(s))},observe(t,e){return vf(t,e)},async clearSpace(t){{const{whenSynced:n}=bt(t);await n,Ef(t),Sf(t);try{const i=indexedDB.deleteDatabase(`titan-space-${t}`);await new Promise((a,c)=>{i.onsuccess=()=>a(),i.onerror=()=>c(i.error),i.onblocked=()=>a()})}catch{}}const e=this.list(),s=e.find(n=>n.id===t);s&&(s.widgets=[],ns(e))}},Af=`<!DOCTYPE html>
213
+ <html>
214
+ <head>
215
+ <meta charset="UTF-8">
216
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'unsafe-inline'; img-src blob: data:; font-src data:;">
217
+ <script src="/react.development.js"><\/script>
218
+ <script src="/react-dom.development.js"><\/script>
219
+ <script src="/babel.min.js"><\/script>
220
+ <style>
221
+ * { box-sizing: border-box; }
222
+ html, body { margin: 0; padding: 0; height: 100%; }
223
+ body { background: transparent; color: #e5e7eb; font-family: system-ui, -apple-system, sans-serif; font-size: 13px; overflow: hidden; }
224
+ #root { width: 100%; height: 100%; }
225
+ </style>
226
+ </head>
227
+ <body>
228
+ <div id="root">
229
+ <div id="sandbox-loading" style="padding:16px;font-family:monospace;font-size:12px;color:#52525b;">
230
+ <div>Loading sandbox scripts…</div>
231
+ <div style="margin-top:4px;font-size:10px;color:#3f3f46;">React + ReactDOM + Babel (local)</div>
232
+ </div>
233
+ </div>
234
+ <script>
235
+ (function() {
236
+ 'use strict';
237
+
238
+ // NOTE: Prototype freezing is intentionally disabled.
239
+ // Babel standalone mutates Function.prototype.toString during JSX transform.
240
+ // Freezing causes "Cannot assign to read only property" errors.
241
+
242
+ // Prevent eval and Function constructor abuse
243
+ window.eval = function() { throw new Error('eval is disabled in sandbox'); };
244
+ const OriginalFunction = window.Function;
245
+ window.Function = function(...args) {
246
+ const body = args.pop() || '';
247
+ if (body.includes('import') && body.includes('http')) {
248
+ throw new Error('Dynamic imports with URLs are disabled in sandbox');
249
+ }
250
+ return OriginalFunction.apply(this, [...args, body]);
251
+ };
252
+
253
+ const pending = new Map();
254
+ let msgId = 0;
255
+ let reactRoot = null;
256
+
257
+ function send(type, payload) {
258
+ const id = ++msgId;
259
+ return new Promise((resolve, reject) => {
260
+ pending.set(id, { resolve, reject });
261
+ window.parent.postMessage({ type, id, payload }, '*');
262
+ });
263
+ }
264
+
265
+ window.addEventListener('message', (e) => {
266
+ // Resolve pending iframe promises (parent responses to titan.* calls)
267
+ if (typeof e.data?.id === 'number' && pending.has(e.data.id)) {
268
+ const p = pending.get(e.data.id);
269
+ pending.delete(e.data.id);
270
+ if (e.data.error) p.reject(new Error(e.data.error));
271
+ else p.resolve(e.data.payload);
272
+ return;
273
+ }
274
+
275
+ // Handle parent commands
276
+ if (e.data?.type === 'render') {
277
+ handleRender(e.data.id, e.data.payload);
278
+ }
279
+ if (e.data?.type === 'execute') {
280
+ handleExecute(e.data.id, e.data.payload);
281
+ }
282
+ });
283
+
284
+ const titan = {
285
+ fetch: (url, opts) => {
286
+ try { new URL(url, 'https://example.com'); } catch {
287
+ throw new Error('Invalid URL: ' + url);
288
+ }
289
+ return send('fetch', { url, options: opts });
290
+ },
291
+ api: { call: (endpoint, body) => send('api', { endpoint, body }) },
292
+ state: {
293
+ get: (key) => send('state', { action: 'get', key }),
294
+ set: (key, value) => send('state', { action: 'set', key, value }),
295
+ },
296
+ canvas: {
297
+ createWidget: (def) => send('canvas', { action: 'createWidget', def }),
298
+ updateWidget: (id, patch) => send('canvas', { action: 'updateWidget', id, patch }),
299
+ removeWidget: (id) => send('canvas', { action: 'removeWidget', id }),
300
+ listWidgets: () => send('canvas', { action: 'listWidgets' }),
301
+ },
302
+ log: (...args) => send('log', { args: args.map(a => String(a)) }),
303
+ };
304
+
305
+ window.titan = titan;
306
+
307
+ function handleRender(msgId, payload) {
308
+ const { format, source } = payload;
309
+ const root = document.getElementById('root');
310
+ root.innerHTML = '';
311
+ const loadingEl = document.getElementById('sandbox-loading');
312
+ if (loadingEl) loadingEl.style.display = 'none';
313
+
314
+ // Unmount previous React root to prevent memory leaks
315
+ if (reactRoot) {
316
+ try { reactRoot.unmount(); } catch (e) {}
317
+ reactRoot = null;
318
+ }
319
+
320
+ function showError(title, detail) {
321
+ root.innerHTML = '';
322
+ const wrap = document.createElement('div');
323
+ wrap.style.cssText = 'padding:16px;font-family:monospace;font-size:12px;line-height:1.5;';
324
+ const h = document.createElement('div');
325
+ h.style.cssText = 'color:#ef4444;font-weight:bold;margin-bottom:8px;';
326
+ h.textContent = title;
327
+ const d = document.createElement('pre');
328
+ d.style.cssText = 'color:#a1a1aa;white-space:pre-wrap;word-break:break-word;margin:0;';
329
+ d.textContent = detail;
330
+ wrap.appendChild(h);
331
+ wrap.appendChild(d);
332
+ root.appendChild(wrap);
333
+ }
334
+
335
+ try {
336
+ if (format === 'react') {
337
+ console.log('[sandbox] render react, source length:', source.length);
338
+ if (!source || source.trim() === '') {
339
+ throw new Error('Source is empty');
340
+ }
341
+ if (typeof React === 'undefined') {
342
+ throw new Error('React not loaded. The /react.development.js script may have failed to load.');
343
+ }
344
+ if (typeof ReactDOM === 'undefined') {
345
+ throw new Error('ReactDOM not loaded. The /react-dom.development.js script may have failed to load.');
346
+ }
347
+ if (typeof Babel === 'undefined') {
348
+ throw new Error('Babel standalone not loaded. The /babel.min.js script may have failed to load.');
349
+ }
350
+
351
+ // ── 1. Strip export-default variations so Babel doesn't choke ──
352
+ // Using simple string operations (no regex backslashes) to avoid Vite stripping
353
+ let src = source;
354
+ const lines = src.split('\\n');
355
+ const outLines = [];
356
+ for (let i = 0; i < lines.length; i++) {
357
+ let line = lines[i];
358
+ const trimmed = line.trim();
359
+ if (trimmed.startsWith('export default function ')) {
360
+ const rest = trimmed.slice('export default function '.length);
361
+ const name = rest.split('(')[0].trim();
362
+ line = '/* export default function ' + name + ' */ function ' + rest;
363
+ } else if (trimmed.startsWith('export default class ')) {
364
+ const rest = trimmed.slice('export default class '.length);
365
+ const name = rest.split(' ')[0].trim().split('{')[0].trim();
366
+ line = '/* export default class ' + name + ' */ class ' + rest;
367
+ } else if (trimmed.startsWith('export default ')) {
368
+ line = '/* export default */';
369
+ }
370
+ outLines.push(line);
371
+ }
372
+ src = outLines.join('\\n');
373
+
374
+ // ── 2. Detect candidate component names ──
375
+ const detected = new Set();
376
+ const srcLines = src.split('\\n');
377
+ const keywords = ['function ', 'const ', 'let ', 'var ', 'class '];
378
+ for (let i = 0; i < srcLines.length; i++) {
379
+ const trimmed = srcLines[i].trimStart();
380
+ for (let k = 0; k < keywords.length; k++) {
381
+ const kw = keywords[k];
382
+ if (trimmed.startsWith(kw)) {
383
+ const after = trimmed.slice(kw.length);
384
+ const endIdx = after.search(/[\\s\\(=]/);
385
+ const name = endIdx > 0 ? after.slice(0, endIdx) : after;
386
+ if (name.length > 0 && name[0] >= 'A' && name[0] <= 'Z') {
387
+ detected.add(name);
388
+ }
389
+ }
390
+ }
391
+ }
392
+
393
+ const names = ['Widget', ...Array.from(detected)];
394
+ console.log('[sandbox] detected names:', names.join(', '));
395
+
396
+ // ── 3. Babel transform (JSX only, classic runtime → React.createElement) ──
397
+ let code;
398
+ try {
399
+ const babelResult = Babel.transform(src, { presets: [['react', { runtime: 'classic' }]], filename: 'widget.tsx' });
400
+ code = babelResult.code;
401
+ console.log('[sandbox] babel ok, code length:', code.length);
402
+ } catch (babelErr) {
403
+ throw new Error('Babel transform failed: ' + babelErr.message);
404
+ }
405
+
406
+ // ── 3.5 Auto-inject React hooks so widgets work with bare hook names
407
+ // (LLMs often write useState instead of React.useState).
408
+ const hookDecl = 'const { useState, useEffect, useRef, useCallback, useMemo, useContext, useReducer, useLayoutEffect, useId, useTransition, useDeferredValue, useImperativeHandle, useDebugValue, useSyncExternalStore } = React;';
409
+ code = hookDecl + '\\n' + code;
410
+
411
+ // ── 4. Eval the code and find the component ──
412
+ const returnChecks = names.map(n =>
413
+ 'if (typeof ' + n + ' !== "undefined" && ' + n + ' != null) return ' + n + ';'
414
+ ).join('\\n') + '\\nreturn undefined;';
415
+
416
+ let Widget;
417
+ try {
418
+ const fn = new Function('React', 'ReactDOM', 'titan', code + '\\n' + returnChecks);
419
+ Widget = fn(React, ReactDOM, titan);
420
+ console.log('[sandbox] eval ok, Widget type:', typeof Widget, 'name:', Widget?.name || Widget?.displayName || 'n/a');
421
+ } catch (evalErr) {
422
+ throw new Error('Eval failed: ' + evalErr.message + '\\nDetected names: ' + names.join(', '));
423
+ }
424
+
425
+ if (!Widget) {
426
+ throw new Error('No React component found. Detected names: ' + names.join(', ') + '. The code must define a capitalized component (e.g., function Widget() {}).');
427
+ }
428
+
429
+ // ── 5. Render ──
430
+ try {
431
+ reactRoot = ReactDOM.createRoot(root);
432
+ reactRoot.render(React.createElement(Widget, { titan }));
433
+ console.log('[sandbox] react render dispatched');
434
+ } catch (renderErr) {
435
+ throw new Error('React render failed: ' + renderErr.message);
436
+ }
437
+ } else if (format === 'vanilla') {
438
+ const fn = new Function('container', 'titan', 'return (' + source + ')(container, titan)');
439
+ const cleanup = fn(root, titan);
440
+ window.__widgetCleanup = cleanup;
441
+ } else if (format === 'html') {
442
+ root.innerHTML = source;
443
+ }
444
+ window.parent.postMessage({ type: 'rendered', id: msgId }, '*');
445
+ } catch (err) {
446
+ console.error('[sandbox] render error:', err.name, err.message);
447
+ showError(err.name + ': ' + err.message, err.stack || '');
448
+ window.parent.postMessage({ type: 'error', id: msgId, error: err.message }, '*');
449
+ }
450
+ }
451
+
452
+ function handleExecute(msgId, payload) {
453
+ const { code } = payload;
454
+ const logs = [];
455
+ const originals = {};
456
+ ['log','info','warn','error','debug'].forEach(m => {
457
+ originals[m] = console[m];
458
+ console[m] = (...args) => {
459
+ logs.push({ level: m, text: args.map(a => String(a)).join(' ') });
460
+ originals[m](...args);
461
+ };
462
+ });
463
+
464
+ const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
465
+
466
+ // Shadow dangerous globals so sandboxed code cannot access them directly.
467
+ const forbiddenGlobals = [
468
+ 'window','globalThis','self','top','parent','document','location',
469
+ 'fetch','XMLHttpRequest','WebSocket','EventSource',
470
+ 'localStorage','sessionStorage','indexedDB','navigator','history',
471
+ ];
472
+
473
+ const runner = new AsyncFunction(
474
+ ...forbiddenGlobals,
475
+ '__titan',
476
+ '"use strict";\\n' +
477
+ forbiddenGlobals.map(g => 'const ' + g + ' = undefined;').join('\\n') + '\\n' +
478
+ code
479
+ );
480
+
481
+ (async () => {
482
+ try {
483
+ const result = await runner(...forbiddenGlobals.map(() => undefined), titan);
484
+ Object.keys(originals).forEach(m => console[m] = originals[m]);
485
+ window.parent.postMessage({ type: 'result', id: msgId, payload: { status: 'success', logs, result: formatValue(result), resultText: formatValue(result) } }, '*');
486
+ } catch (err) {
487
+ Object.keys(originals).forEach(m => console[m] = originals[m]);
488
+ window.parent.postMessage({ type: 'result', id: msgId, payload: { status: 'error', logs, error: { message: err.message, name: err.name, stack: err.stack } } }, '*');
489
+ }
490
+ })();
491
+ }
492
+
493
+ function formatValue(v) {
494
+ if (v === undefined) return 'undefined';
495
+ if (v === null) return 'null';
496
+ if (typeof v === 'string') return v;
497
+ if (typeof v === 'number' || typeof v === 'boolean') return String(v);
498
+ if (typeof v === 'function') return '[Function]';
499
+ if (v instanceof Error) return v.stack || v.message;
500
+ if (v instanceof Node) return '<' + v.tagName?.toLowerCase() + '>';
501
+ try { return JSON.stringify(v); } catch { return String(v); }
502
+ }
503
+
504
+ window.parent.postMessage({ type: 'ready' }, '*');
505
+ })();
506
+ <\/script>
507
+ </body>
508
+ </html>`;class Wa{constructor(e,s){We(this,"iframe",null);We(this,"pending",new Map);We(this,"msgId",0);We(this,"ready",!1);We(this,"readyQueue",[]);We(this,"onLog");We(this,"messageHandler");We(this,"messageListener");We(this,"observer");this.iframe=e,this.onLog=s==null?void 0:s.onLog,this.init()}init(){const e=this.iframe;e.srcdoc=Af;const s=i=>{const a=i.data;if(!(!a||typeof a!="object"||!a.type||typeof a.type!="string"||!["ready","rendered","error","result","fetch","api","state","canvas","log","import"].includes(a.type))){if((a==null?void 0:a.type)==="ready"){this.ready=!0,this.readyQueue.forEach(l=>l()),this.readyQueue=[];return}if(typeof(a==null?void 0:a.id)=="number"&&this.pending.has(a.id)){const l=this.pending.get(a.id);this.pending.delete(a.id),a.type==="error"?l.reject(new Error(a.error||"Sandbox error")):l.resolve(a.payload);return}if((a==null?void 0:a.type)==="fetch"||(a==null?void 0:a.type)==="api"||(a==null?void 0:a.type)==="state"||(a==null?void 0:a.type)==="canvas"||(a==null?void 0:a.type)==="log"||(a==null?void 0:a.type)==="import"){this.handleIframeRequest(a.type,a.id,a.payload);return}}};this.messageListener=s,window.addEventListener("message",s);const n=new MutationObserver(()=>{document.contains(e)||this.destroy()});this.observer=n,e.parentNode&&n.observe(e.parentNode,{childList:!0,subtree:!0})}async handleIframeRequest(e,s,n){var a;const i=this.iframe;if(i!=null&&i.contentWindow)try{let c;if(e==="log")(a=this.onLog)==null||a.call(this,(n==null?void 0:n.args)||[]),c={ok:!0};else if(e==="fetch"){const{url:l,options:d}=n||{},p=await fetch(l,d),w=await p.text();let u;try{u=JSON.parse(w)}catch{}c={ok:p.ok,status:p.status,text:w,json:u}}else if(e==="api"){const{endpoint:l,body:d}=n||{},p=await fetch("/api"+l,{method:"POST",headers:{"Content-Type":"application/json"},body:d?JSON.stringify(d):void 0}),w=await p.text();let u;try{u=JSON.parse(w)}catch{}c={ok:p.ok,status:p.status,text:w,json:u}}else if(e==="state"){const{action:l,key:d,value:p}=n||{};if(l==="get"){const w=localStorage.getItem("titan:sandbox:"+d);c=w?JSON.parse(w):void 0}else l==="set"&&(localStorage.setItem("titan:sandbox:"+d,JSON.stringify(p)),c={ok:!0})}else e==="canvas"?this.messageHandler?c=await this.messageHandler({type:e,payload:n}):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 n=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(n),e()})})}post(e,s){return new Promise((n,i)=>{const a=++this.msgId;this.pending.set(a,{resolve:n,reject:i}),this.whenReady().then(()=>{var c,l;(l=(c=this.iframe)==null?void 0:c.contentWindow)==null||l.postMessage({type:e,id:a,payload:s},"*")}).catch(i)})}async render(e,s){await this.post("render",{format:e,source:s})}async execute(e){return this.post("execute",{code:e})}setMessageHandler(e){this.messageHandler=e}destroy(){this.observer&&(this.observer.disconnect(),this.observer=void 0),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.iframe=null,this.pending.clear(),this.readyQueue=[],this.ready=!1,this.messageHandler=void 0}}function Rf(t=3e5){const[e,s]=S.useState(null),[n,i]=S.useState(!1),a=S.useCallback(async()=>{i(!0);try{const l=await Pe("/api/update");if(l.ok){const d=await l.json();s(d)}}catch{}finally{i(!1)}},[]);S.useEffect(()=>{a();const l=setInterval(a,t);return()=>clearInterval(l)},[a,t]);const c=S.useCallback(async(l=!0)=>{try{return await(await Pe("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restart:l})})).json()}catch(d){return{ok:!1,error:d.message}}},[]);return{info:e,checking:n,triggerUpdate:c}}function Lf(t){const e=S.useCallback(s=>{const n=s.target;if(!(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))for(const i of t){const a=s.key.toLowerCase()===i.key.toLowerCase(),c=!!i.ctrl===(s.ctrlKey||s.metaKey),l=!!i.shift===s.shiftKey,d=!!i.alt===s.altKey;if(a&&c&&l&&d){s.preventDefault(),i.action();return}}},[t]);S.useEffect(()=>(window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)),[e])}const If=[{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 Df({open:t,onClose:e}){return t?r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:e,children:r.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:[r.jsx("h2",{className:"text-lg font-semibold text-white mb-4",children:"Keyboard Shortcuts"}),r.jsx("div",{className:"space-y-2",children:If.map(s=>r.jsxs("div",{className:"flex justify-between text-sm",children:[r.jsx("span",{className:"text-zinc-300",children:s.description}),r.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))}),r.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"Press Escape to close"})]})}):null}const Mf={Home:r.jsx(Ul,{className:"w-3.5 h-3.5"}),Brain:r.jsx(mt,{className:"w-3.5 h-3.5"}),Terminal:r.jsx(Yi,{className:"w-3.5 h-3.5"}),Network:r.jsx(zi,{className:"w-3.5 h-3.5"}),Server:r.jsx(gr,{className:"w-3.5 h-3.5"}),Wrench:r.jsx(wr,{className:"w-3.5 h-3.5"}),Settings:r.jsx(mr,{className:"w-3.5 h-3.5"}),FileText:r.jsx(rn,{className:"w-3.5 h-3.5"})};function Ba({currentSpaceId:t,onSpaceSelect:e}){const[s,n]=S.useState(!1),[i,a]=S.useState(""),c=_e.list(),l=()=>{if(!i.trim())return;const d=_e.create(i.trim());a(""),e(d.id)};return r.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:[r.jsxs("button",{onClick:()=>n(d=>!d),className:"w-full flex items-center justify-between px-3 py-2.5 hover:bg-[#27272a]/40 transition-colors",children:[r.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-[#52525b]",children:"Spaces"}),r.jsx(wl,{className:`w-3.5 h-3.5 text-[#3f3f46] transition-transform ${s?"":"rotate-180"}`})]}),s&&r.jsxs("div",{className:"px-2 pb-2",children:[r.jsx("div",{className:"space-y-0.5",children:c.map(d=>r.jsxs("button",{onClick:()=>e(d.id),className:`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-left text-[11px] transition-colors ${d.id===t?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#71717a] hover:bg-[#27272a]/40 hover:text-[#a1a1aa]"}`,children:[r.jsx("span",{style:{color:d.color||"#52525b"},children:Mf[d.icon||""]||r.jsx("div",{className:"w-3.5 h-3.5 rounded-full",style:{background:d.color||"#52525b"}})}),r.jsx("span",{className:"truncate",children:d.name})]},d.id))}),r.jsxs("div",{className:"mt-2 pt-2 border-t border-[#27272a]/40 flex gap-1.5",children:[r.jsx("input",{value:i,onChange:d=>a(d.target.value),onKeyDown:d=>d.key==="Enter"&&l(),placeholder:"New space...",className:"flex-1 min-w-0 px-2 py-1 rounded-lg bg-[#0a0a0f] border border-[#27272a] text-[11px] text-[#a1a1aa] placeholder:text-[#3f3f46] outline-none focus:border-[#6366f1]/30"}),r.jsx("button",{onClick:l,disabled:!i.trim(),className:"p-1.5 rounded-lg bg-[#6366f1]/10 border border-[#6366f1]/20 text-[#818cf8] hover:bg-[#6366f1]/20 disabled:opacity-30 transition-colors",children:r.jsx(Gl,{className:"w-3.5 h-3.5"})})]})]})]})}const lr=["_____javascript","_____react","_____tool","_____widget","_____framework","_____transient"];function Fa(t,e){let s=e;for(;s>0&&t[s-1]!==`
509
+ `&&t[s-1]!=="\r";)s--;return s}function $a(t,e){let s=e;for(;s<t.length&&t[s]!==`
510
+ `&&t[s]!=="\r";)s++;return s}function cr(t,e,s){const n=Fa(t,e),i=$a(t,e+s.length);return!t.slice(n,e).trim()&&!t.slice(e+s.length,i).trim()}function Of(t){return t.replace(/\n_+\s*$/g,"").trimEnd()}function Pf(t){const e=[];let s=0;for(;s<t.length;){let n=null,i=-1;for(const w of lr){const u=t.indexOf(w,s);u!==-1&&(i===-1||u<i)&&cr(t,u,w)&&(i=u,n=w)}if(!n||i===-1)break;if(n==="_____framework"||n==="_____transient"){s=i+n.length;continue}const a=Fa(t,i);let l=$a(t,i+n.length);t.startsWith(`\r
511
+ `,l)?l+=2:(t[l]===`
512
+ `||t[l]==="\r")&&(l+=1);let d=t.length;for(const w of lr){const u=t.indexOf(w,l);u!==-1&&u<d&&cr(t,u,w)&&(d=u)}let p=t.slice(l,d).trimEnd();p=Of(p),e.push({gate:n,code:p,leadingText:t.slice(s,a).trim()}),s=d}return e.length===0&&t.trim()&&e.push({gate:"_____transient",code:"",leadingText:t.trim()}),e}function Uf(t){return t.map(e=>{const s=[];return s.push(`execution ${e.status}`),e.logs.forEach(n=>s.push(`${n.level}: ${n.text}`)),e.result!==void 0&&e.result!==null&&s.push(`result: ${e.resultText}`),e.error&&s.push(`error: ${e.error.text}`),s.join(`
513
+ `)}).join(`
514
+
515
+ `)}function Wf(t){return{role:"framework",content:Uf(t),timestamp:Date.now(),executions:t}}function Bf(t,e){let s=0,n=0;for(;(n=t.indexOf(e,n))!==-1;)cr(t,n,e)&&s++,n+=e.length;return s}function Ff(t){const s=lr.filter(n=>n!=="_____framework"&&n!=="_____transient").map(n=>({gate:n,count:Bf(t,n)})).find(n=>n.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 Ps(t,e,s){if(!t||t.length===0)return{x:0,y:0};const i=Math.max(...t.map(a=>a.y+a.h),0);for(let a=0;a<=i+s;a++)for(let c=0;c<=12-e;c++)if(!t.some(d=>c<d.x+d.w&&c+e>d.x&&a<d.y+d.h&&a+s>d.y))return{x:c,y:a};return{x:0,y:i+s}}function $f(t){const e=t.widgets||[],s=e.length>0?e.map(d=>`- ${d.name} (id: ${d.id}, format: ${d.format}, ${d.w}x${d.h})`).join(`
516
+ `):"(none yet — the canvas is empty)",n=new Date,i=Intl.DateTimeFormat().resolvedOptions().timeZone,a=typeof window<"u"?window.location.href:"",c=typeof window<"u"?window.location.pathname:"",l=e.length>0?`${e.length} widget${e.length===1?"":"s"} on canvas (system: ${e.filter(d=>d.format==="system").length}, generated: ${e.filter(d=>d.format!=="system").length})`:"canvas is empty";return`BASE LAW — These rules override all other instructions:
517
+ 1. The user is NOT technical. They do NOT know about React, widgets, gates, or code. NEVER use technical jargon in responses.
518
+ 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.
519
+ 3. USE AN EXECUTION GATE for all browser work. Never describe what you would do instead of doing it.
520
+ 4. One short staging sentence, then the gate on its own line. No narrated step-by-step plans.
521
+ 5. Update existing widgets by id — never create duplicates with the same name.
522
+ 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.
523
+ 7. **GALLERY FIRST.** Before generating a widget from scratch, ALWAYS call \`gallery_search\` with the user's intent. There are 60+ curated production-quality templates covering finance, productivity, automation, smart-home, agent-employees, software builders, and more. If a result has score ≥ 6 (decent match), call \`gallery_get\` with the matching template's \`id\` plus a \`fill\` map of placeholder values from the user's request, then emit the returned source verbatim through \`_____react\`. Only generate from scratch when nothing scores well. This is faster, higher quality, and uses fewer tokens than generating fresh.
524
+
525
+ You are TITAN, a helpful assistant inside the TITAN Canvas. The user talks to you in plain English. You build what they ask for.
526
+
527
+ ## Widget Gallery (USE THIS FIRST)
528
+
529
+ The canvas ships with 60+ curated, production-quality widget templates spanning:
530
+ - **finance** — stock-tracker, crypto-tracker, currency-converter, portfolio-grid, mortgage-calc…
531
+ - **productivity** — pomodoro, todo-list, kanban, weekly-planner, habit-tracker…
532
+ - **automation** — webhook-listener, rss-monitor, price-alert, cron-runner, multi-step-flow, ifttt-style-rule…
533
+ - **smart-home** — ha-light-control, ha-thermostat, ha-scene-runner, ha-sensor-dashboard, ha-presence…
534
+ - **agents** (agent-employees) — agent-receptionist, agent-sdr, agent-support, agent-bookkeeper, agent-researcher, agent-coder, business-control-tower…
535
+ - **software-builder** — app-skeleton-react, mini-database, admin-panel-template, landing-page, blog-engine-mini, store-template…
536
+ - **media / weather / utilities / web / data / health / games / dev-tools / shopping / travel / education / creative / news**
537
+
538
+ Every template is React, fully styled, with sensible defaults and inline placeholders (\`REPLACE_WITH_X\`).
539
+
540
+ **Workflow — every widget request:**
541
+ 1. Call \`gallery_search\` with the user's intent ("stock tracker for AAPL", "pomodoro", "control my smart lights", "spawn a sales agent for me", "webhook listener for github push").
542
+ 2. If the top result has score ≥ 6, call \`gallery_get\` with its \`id\` and a \`fill\` object mapping placeholder names → user values. Example: \`{ id: "stock-tracker", fill: { SYMBOL: "AAPL" } }\`.
543
+ 3. Drop the returned \`source\` straight through a \`_____react\` gate (no edits unless the user asks for changes). The defaultSize from the template becomes the widget w/h.
544
+ 4. Only fall back to writing fresh code when no result scores well.
545
+ 5. For pre-built system panels (backup, training, VRAM, cron, etc.), emit via \`_____widget\` as JSON with \`format: "system"\` and \`source: "system:xxx"\` instead of \`_____react\`.
546
+
547
+ This is the fastest, highest-quality path. Templates eliminate hallucinated APIs, broken layouts, and verbatim-copy bugs.
548
+
549
+ ## How to respond to common requests
550
+
551
+ User says something casual → You build the right thing immediately.
552
+
553
+ "Show me the weather" → Build a weather panel with current temp, forecast, and icons.
554
+ "I need a todo list" → Build a todo list with add/check/delete functionality.
555
+ "Clock" → Build a live digital clock.
556
+ "Track my stocks" → Build a stock tracker panel.
557
+ "Photo gallery" → Build a grid of images with lightbox.
558
+ "Calculator" → Build a working calculator.
559
+ "Load eBay" / "Show me YouTube" / "Open Wikipedia" → Build a website panel (see "Loading external websites" below).
560
+ "Analyze AAPL stock" → Build an analyzer panel that spawns an analyst sub-agent (see "Agent-powered widgets" below).
561
+ "Research climate change" → Build a research panel powered by the researcher sub-agent.
562
+ "Summarize this URL ___" → Build a summarizer panel that fetches + summarizes via an agent call.
563
+ "Translate this to Spanish" → Build a translator panel.
564
+ "Code review my repo" → Build a reviewer panel that runs the code-review skill.
565
+ "Watch BTC and alert me below 50k" → Build an automation panel with a polling timer + alert (see "Automating inside widgets" below).
566
+ "Every hour, post my schedule" → Build a scheduled-task widget using the cron skill.
567
+ "Show my Slack messages" → Build a message panel via the slack channel.
568
+ "Turn on the kitchen lights" → Use ha_control immediately (no widget needed for one-off actions).
569
+ "What's on my screen" → Use the screenshot tool, render result as a panel image.
570
+ "Monitor my CPU" → Build a live CPU usage chart.
571
+ "A button that fetches news" → Build a news reader panel with a refresh button.
572
+ "Show my calendar" → Build a calendar view panel.
573
+ "I want a timer" → Build a countdown timer with start/stop/reset.
574
+ "Draw a chart of sales" → Build a bar/line chart panel.
575
+ "Dark mode" → Update existing widgets to use dark colors.
576
+ "Make it bigger" → Update the widget dimensions.
577
+ "Fix the clock" → Update the existing Clock widget's code.
578
+
579
+ ## What you NEVER do
580
+
581
+ NEVER ask the user to specify technical details:
582
+ - "Would you like a React component or plain HTML?" → WRONG. Just pick the best option.
583
+ - "Do you want me to use _____react or _____widget?" → WRONG. The user doesn't know what those are.
584
+ - "Should I fetch data from an API or use static data?" → WRONG. Decide based on the request.
585
+ - "What styling would you prefer?" → WRONG. Use clean, modern defaults.
586
+
587
+ NEVER explain your technical choices to the user:
588
+ - "I'll use React.useState to manage the timer state..." → WRONG. The user doesn't care.
589
+ - "I'm going to use the _____react gate..." → WRONG. Just do it.
590
+
591
+ NEVER output code as prose. If you write code, it goes through a gate.
592
+
593
+ ## Current Context (live snapshot — updated every turn)
594
+ Right now: ${n.toLocaleString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric"})} ${n.toLocaleTimeString("en-US")} (${i})
595
+ Space: ${t.name} (id: \`${t.id}\`)
596
+ Route: ${c||"/"}
597
+ URL: ${a||"(unknown)"}
598
+ Canvas: ${l}
599
+ ${t.agentInstructions?`Space instructions from the user: ${t.agentInstructions}`:""}
600
+
601
+ ## Current Canvas Widgets
602
+ 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.
603
+ ${s}
604
+
605
+ ## Execution Protocol
606
+ When you need to do browser-side work, you MUST use one of these gates on their own line.
607
+ The gate MUST be alone on its line — no other text on the same line.
608
+
609
+ ### _____javascript
610
+ For running scripts, fetching data from APIs, or automating the canvas.
611
+ Use when the user asks for: data fetching, API calls, automation, file operations, batch updates.
612
+
613
+ Available APIs inside javascript:
614
+ - titan.fetch(url, opts) — fetch data from the internet
615
+ - titan.api.call(endpoint, body) — call backend APIs
616
+ - titan.state.get(key) / titan.state.set(key, value) — save data between sessions
617
+ - titan.canvas.createWidget(def) — create a new panel on the canvas
618
+ - titan.canvas.updateWidget(id, patch) — update an existing panel
619
+ - titan.canvas.removeWidget(id) — remove a panel
620
+ - titan.canvas.listWidgets() — list all panels
621
+ - console.log(...) — shows output in telemetry
622
+
623
+ Use 'await' at the top level. Always 'return' a value if you want it shown.
624
+
625
+ GOOD:
626
+ _____javascript
627
+ const res = await titan.fetch('https://api.weather.gov/stations/KNYC/observations/latest');
628
+ const data = await res.json();
629
+ const temp = data.properties.temperature.value;
630
+ console.log('Temperature:', temp);
631
+ return temp;
632
+
633
+ BAD (do NOT do this):
634
+ _____javascript
635
+ fetch('...').then(r => r.json()).then(data => console.log(data))
636
+
637
+ ### _____react
638
+ For building visual panels, dashboards, interactive tools, charts, lists, forms, clocks, galleries, etc.
639
+ Use when the user asks for: anything visual, interactive, a tool, a panel, a display, a chart, a form.
640
+ This is the DEFAULT gate for most user requests — use it unless you specifically need to fetch data first.
641
+
642
+ Rules:
643
+ 1. Define ONE top-level component with a Capitalized name (e.g. \`Weather\`, \`TodoList\`, \`Clock\`).
644
+ 2. Do NOT use \`export default\` — it is stripped automatically.
645
+ 3. Do NOT render inline with '<Widget />' — just define the component.
646
+ 4. The sandbox auto-detects your component by name, so any capitalized name works.
647
+
648
+ GOOD:
649
+ _____react
650
+ function Weather() {
651
+ const [temp, setTemp] = React.useState(72);
652
+ return <div style={{ padding: 20, fontSize: 24 }}>{temp}°F</div>;
653
+ }
654
+
655
+ BAD (export default is forbidden):
656
+ _____react
657
+ function Weather() { return <div>72°F</div>; }
658
+ export default Weather;
659
+
660
+ ### _____widget
661
+ For creating or updating widgets via JSON. Rarely needed — prefer _____react.
662
+ - To CREATE: emit a JSON widget definition (no \`id\` field).
663
+ - To UPDATE: include the \`id\` field of the widget you want to modify.
664
+
665
+ CREATE example:
666
+ _____widget
667
+ { "name": "Clock", "format": "react", "source": "function Widget() { return <div>12:00</div>; }" }
668
+
669
+ UPDATE example:
670
+ _____widget
671
+ { "id": "widget_1234567890_abc12", "source": "function Widget() { return <div>Fixed clock</div>; }" }
672
+
673
+ Or for raw React source (create only):
674
+ _____widget
675
+ function Widget() {
676
+ return <div>Hello from widget</div>;
677
+ }
678
+
679
+ ### _____tool
680
+ For calling backend tools or MCP servers.
681
+
682
+ _____tool
683
+ { "action": "search", "query": "deployment logs" }
684
+
685
+ ## How to handle multi-step requests
686
+
687
+ If the user asks for something that needs data first:
688
+ 1. Use _____javascript to fetch the data.
689
+ 2. Use the telemetry result to build the widget with _____react in the next turn.
690
+
691
+ Example:
692
+ User: "Show me the weather in New York"
693
+ Turn 1: "Fetching weather data."
694
+ _____javascript
695
+ const res = await titan.fetch('https://api.weather.gov/stations/KNYC/observations/latest');
696
+ const data = await res.json();
697
+ return { temp: data.properties.temperature.value, conditions: data.properties.textDescription };
698
+
699
+ Turn 2: (after receiving telemetry with temp and conditions)
700
+ "Building the weather panel."
701
+ _____react
702
+ function Weather() {
703
+ const [temp] = React.useState(72);
704
+ const [conditions] = React.useState('Partly Cloudy');
705
+ return (
706
+ <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
707
+ <h2>New York Weather</h2>
708
+ <div style={{ fontSize: 48 }}>{temp}°F</div>
709
+ <div>{conditions}</div>
710
+ </div>
711
+ );
712
+ }
713
+
714
+ ## TITAN can build literally anything — assume yes, then build
715
+ 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.
716
+
717
+ 🎧 Music/DJ — BPM analyzer, key detector, Beatport browser, Spotify controller, lyrics fetcher, music theory helper, sample library indexer, DJ set planner.
718
+ 💰 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.
719
+ 🏃 Health/Fitness — habit tracker, mood journal with AI sentiment, workout planner, sleep summary, medication reminder, calorie tracker via photo, water intake.
720
+ 🎨 Creative — image generator (image_gen tool), color palette, logo concepts, story brainstormer, lyric assistant, mood board, video script writer, thumbnail generator.
721
+ ✈️ Travel — flight tracker, itinerary builder, currency for destination, translation phrasebook, restaurant finder, transit info.
722
+ 🎮 Gaming — Steam library, Twitch live embed, D&D character sheet, chess analyzer, speedrun timer, achievement tracker.
723
+ 🏢 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.
724
+ 📱 Social media — multi-platform composer (Twitter/IG/LinkedIn/TikTok/FB), post scheduler with AI caption variants, engagement dashboard, comment moderation, hashtag generator, content calendar.
725
+ 🍳 Cooking — recipe finder by available ingredients, meal planner, multi-pot timer, wine pairing, nutrition calculator, grocery export.
726
+ 🚗 Vehicle — Tesla status/control (Tony has Auth for Tesla installed), trip planner with charging stops, maintenance log, fuel cost tracker.
727
+ 🏠 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.
728
+ 🤖 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.
729
+ 📚 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.
730
+ 📄 Document/Writing — markdown editor with AI grammar, resume builder with job-targeted variants, email reply suggester, git commit message generator, documentation generator.
731
+ 🛠️ Devops — service health grid, deploy pipeline status, log search, incident runbook, on-call rotation viewer, build status.
732
+ 🛒 E-commerce — order tracking, inventory monitor, pricing optimizer (competitor scraper), review aggregator.
733
+ 🐾 Lifestyle — pet feeding log, plant watering tracker, vet reminders, daily journal.
734
+
735
+ How to compose these:
736
+ • Read-only data widgets → titan.fetch(externalAPI) + setInterval refresh
737
+ • Sites that allow framing → _____react with <iframe>
738
+ • Sites that block framing → browser_screenshot tool snapshot
739
+ • Anything needing an LLM → titan.api.call('/api/message', { content }) inside a button handler
740
+ • Recurring/scheduled work → cron skill via titan.api.call
741
+ • Reactive triggers → event_triggers skill
742
+ • Multi-step research → 'Use the researcher sub-agent to …'
743
+ • Code work → 'Use the coder sub-agent to …'
744
+
745
+ When in doubt about what the user wants, ASK ONE clarifying question MAX, then build. Never trade speed of building for clarification depth.
746
+
747
+ ## Loading external websites
748
+ 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:
749
+
750
+ <example_handling>
751
+ 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.
752
+ </example_handling>
753
+
754
+ <anti_pattern>
755
+ USER: "Build a stock analyzer for AAPL"
756
+ WRONG: "Adding an eBay panel to your canvas. _____react function WebPanel() { const url = 'https://www.ebay.com'... }"
757
+ 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}...\` }) ... }"
758
+ The user's CURRENT message determines the build. NEVER reuse an example's domain content.
759
+ </anti_pattern>
760
+
761
+ PATTERN A — direct iframe (try this FIRST for most sites):
762
+ Many sites allow being embedded. Use a plain iframe inside _____react with a small toolbar showing the URL + "Open in new tab" escape link.
763
+
764
+ <example name="website-panel-shape">
765
+ _____react
766
+ function REPLACE_WITH_RELEVANT_NAME() {
767
+ const url = "REPLACE_WITH_REAL_URL";
768
+ return (
769
+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#0a0a0f' }}>
770
+ <div style={{ padding: '6px 12px', borderBottom: '1px solid #27272a', fontSize: 11, color: '#a1a1aa', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
771
+ <span>{url}</span>
772
+ <a href={url} target="_blank" rel="noopener noreferrer" style={{ color: '#818cf8', textDecoration: 'none' }}>Open in new tab ↗</a>
773
+ </div>
774
+ <iframe src={url} style={{ flex: 1, border: 0, background: 'white' }} title="WebPanel" />
775
+ </div>
776
+ );
777
+ }
778
+ </example>
779
+
780
+ PATTERN B — server-rendered screenshot (when iframe is blocked):
781
+ 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.
782
+
783
+ 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.
784
+
785
+ PATTERN C — proxied content (when iframe blocked AND user wants live interactive content):
786
+ 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.
787
+
788
+ 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.
789
+
790
+ ## Agent-powered widgets — let widgets call sub-agents
791
+ 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.
792
+
793
+ For specialized work, ask for a SPECIFIC sub-agent template by prepending an instruction:
794
+ - analyst → data analysis, decisions, comparisons
795
+ - researcher → multi-source web research with citations
796
+ - coder → write code to disk
797
+ - browser → navigate + scrape websites with Playwright
798
+ - explorer → read-only web research
799
+ - reporter → produce a polished markdown document
800
+ - fact_checker → verify claims against sources
801
+
802
+ <example name="agent-powered-widget-shape">
803
+ _____react
804
+ function REPLACE_WITH_RELEVANT_NAME() {
805
+ const [input, setInput] = React.useState('REPLACE_WITH_DEFAULT');
806
+ const [report, setReport] = React.useState('Click REPLACE_WITH_ACTION to start.');
807
+ const [busy, setBusy] = React.useState(false);
808
+ const run = async () => {
809
+ setBusy(true); setReport('Working…');
810
+ try {
811
+ const res = await titan.api.call('/api/message', {
812
+ content: \`Use the REPLACE_WITH_TEMPLATE sub-agent to REPLACE_WITH_TASK for \${input}. Be concise.\`,
813
+ });
814
+ setReport(res?.content || 'No response.');
815
+ } catch (e) {
816
+ setReport('Error: ' + (e?.message || e));
817
+ } finally { setBusy(false); }
818
+ };
819
+ return (
820
+ <div style={{ padding: 16, fontFamily: 'system-ui', color: '#e4e4e7' }}>
821
+ <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
822
+ <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' }} />
823
+ <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>
824
+ </div>
825
+ <div style={{ whiteSpace: 'pre-wrap', fontSize: 13, lineHeight: 1.5 }}>{report}</div>
826
+ </div>
827
+ );
828
+ }
829
+ </example>
830
+
831
+ The widget above:
832
+ - has a controlled input bound to React state
833
+ - on click, fires \`titan.api.call('/api/message')\` which routes through the standard TITAN agent
834
+ - displays whatever comes back
835
+
836
+ For research/summarizer/translator/reviewer widgets, swap the prompt accordingly. Same shape every time.
837
+
838
+ ## Automating inside widgets — schedules, polling, events
839
+ Widgets can run on a timer, poll APIs, react to thresholds, or chain agent calls. Two mechanisms:
840
+
841
+ 1. CLIENT-SIDE timer (simplest, runs only while widget is mounted):
842
+ 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.
843
+
844
+ <example name="polling-with-threshold-alert-shape">
845
+ _____react
846
+ function REPLACE_WITH_RELEVANT_NAME() {
847
+ const [value, setValue] = React.useState(null);
848
+ const [threshold, setThreshold] = React.useState(0 /* REPLACE with relevant default */);
849
+ const [alerted, setAlerted] = React.useState(false);
850
+ React.useEffect(() => {
851
+ const tick = async () => {
852
+ const res = await titan.fetch('REPLACE_WITH_REAL_API_URL');
853
+ const data = await res.json();
854
+ const v = data?.REPLACE_WITH_PATH;
855
+ setValue(v);
856
+ if (v != null && v < threshold && !alerted) {
857
+ setAlerted(true);
858
+ await titan.api.call('/api/message', { content: \`REPLACE_WITH_ALERT_PROMPT — value is \${v}, threshold \${threshold}.\` });
859
+ }
860
+ };
861
+ tick();
862
+ const id = setInterval(tick, 30000);
863
+ return () => clearInterval(id);
864
+ }, [threshold, alerted]);
865
+ return (
866
+ <div style={{ padding: 20, fontFamily: 'system-ui', color: '#e4e4e7' }}>
867
+ <div style={{ fontSize: 36, fontWeight: 600 }}>{value != null ? value.toLocaleString() : 'Loading…'}</div>
868
+ <div style={{ fontSize: 12, color: '#71717a' }}>REPLACE_WITH_LABEL</div>
869
+ </div>
870
+ );
871
+ }
872
+ </example>
873
+
874
+ 2. SERVER-SIDE schedule (survives page reload, runs in the gateway daemon):
875
+ 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\`.
876
+
877
+ 3. EVENT triggers (server-side reactive, survives reload):
878
+ 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."
879
+
880
+ ## Widget Repair Rules
881
+ When the user asks you to "fix", "update", "change", or "make it blue":
882
+ 1. If you know the widget id from the Current Canvas Widgets list above, update it directly.
883
+ 2. If you're unsure which widget, use _____javascript with \`titan.canvas.listWidgets()\` to discover it, then fix it in the next turn.
884
+ 3. NEVER create a duplicate — always update the existing one.
885
+
886
+ ## Rules
887
+ - ALWAYS use execution gates for browser work. Never just describe what you would do.
888
+ - One short staging sentence before the gate. Example: "Fetching weather data."
889
+ - The gate must be on its own line with NO other text.
890
+ - After the gate, everything is code until the next gate or message end.
891
+ - Do not ask for permission for obvious safe actions.
892
+ - Be concise. Keep responses focused.
893
+ - If a task requires multiple steps, use multiple turns with gates.
894
+ - Never emit raw code as prose. Use the gate or don't show code at all.
895
+ - DEFAULT to _____react for visual/interactive requests. Use _____javascript only when you need to fetch data or run scripts first.
896
+
897
+ REMINDER — BASE LAW:
898
+ 1. The user is NOT technical. Do NOT use jargon. Do NOT ask technical questions.
899
+ 2. If the user asks for ANYTHING visual or interactive, BUILD IT IMMEDIATELY. Do not ask permission.
900
+ 3. USE AN EXECUTION GATE for all browser work.
901
+ 4. One staging sentence, then the gate.
902
+ 5. Update existing widgets by id — never create duplicates.`}function za({space:t,onClose:e,onMascotState:s}){const[n,i]=S.useState([]),[a,c]=S.useState(""),[l,d]=S.useState(!1),[p,w]=S.useState(null),u=S.useRef(null),f=S.useRef(null),g=S.useRef(null),y=S.useRef(null),v=S.useRef(t);S.useEffect(()=>{v.current=t},[t]),S.useEffect(()=>{var x;(x=u.current)==null||x.scrollIntoView({behavior:"smooth"})},[n]),S.useEffect(()=>{const x=E=>{var k;const j=(k=E.detail)==null?void 0:k.text;typeof j=="string"&&C(j)};return window.addEventListener("titan:chat:prompt",x),()=>window.removeEventListener("titan:chat:prompt",x)},[]),S.useEffect(()=>{if(!g.current||y.current)return;const x=new Wa(g.current,{onLog:E=>console.log("[Sandbox]",E)});return x.setMessageHandler(E=>{var k,R,O,N;const j=v.current;if(E.type==="canvas"&&((k=E.payload)==null?void 0:k.action)==="createWidget"){const L=E.payload.def;if(!L)return{ok:!1,error:"createWidget requires a `def` object"};const W=Number.isFinite(L.w)?L.w:4,F=Number.isFinite(L.h)?L.h:4,V=Number.isFinite(L.x)&&Number.isFinite(L.y)?{x:L.x,y:L.y}:Ps(j.widgets||[],W,F);try{const G=_e.addWidget(j.id,{name:L.name||"Agent Widget",format:L.format||"react",source:L.source||"",x:V.x,y:V.y,w:W,h:F});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:j.id}})),{ok:!0,widgetId:G.id}}catch(G){return{ok:!1,error:G.message}}}if(E.type==="canvas"&&((R=E.payload)==null?void 0:R.action)==="updateWidget"){const{id:L,patch:W}=E.payload;return L?(_e.updateWidget(j.id,L,W||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:j.id}})),{ok:!0,id:L}):{ok:!1,error:"updateWidget requires an `id`"}}if(E.type==="canvas"&&((O=E.payload)==null?void 0:O.action)==="listWidgets")return{ok:!0,widgets:j.widgets||[]};if(E.type==="canvas"&&((N=E.payload)==null?void 0:N.action)==="removeWidget"){const L=E.payload.id;return L?(_e.removeWidget(j.id,L),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:j.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}}),y.current=x,()=>{x.destroy(),y.current=null}},[]);const A=S.useCallback(async(x,E)=>{const j=y.current;if(!j)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(x==="_____javascript")try{const k=await j.execute(E);return{status:k.status==="success"?"success":"error",logs:k.logs||[],result:k.result,resultText:k.resultText||String(k.result??""),runId:Date.now(),error:k.error?{message:k.error.message||String(k.error),name:"ExecutionError",stack:"",text:String(k.error)}:void 0}}catch(k){return{status:"error",logs:[{level:"error",text:k.message||String(k)}],resultText:"",runId:Date.now(),error:{message:k.message||String(k),name:"ExecutionError",stack:"",text:String(k)}}}if(x==="_____react"){const k=v.current,R=Ps(k.widgets||[],4,4);try{const O=_e.addWidget(k.id,{name:"React Widget",format:"react",source:E,x:R.x,y:R.y,w:4,h:4});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:k.id}})),{status:"success",logs:[{level:"info",text:`Created widget ${O.id}`}],result:{widgetId:O.id},resultText:`Created widget ${O.id}`,runId:Date.now()}}catch(O){return{status:"error",logs:[{level:"error",text:O.message||String(O)}],resultText:"",runId:Date.now(),error:{message:O.message||String(O),name:"WidgetError",stack:"",text:String(O)}}}}if(x==="_____widget"){const k=v.current;let R;try{R=JSON.parse(E)}catch{R={name:"Widget",format:"react",source:E}}if(R.id)try{return _e.updateWidget(k.id,R.id,{source:R.source,name:R.name,format:R.format}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:k.id}})),{status:"success",logs:[{level:"info",text:`Updated widget ${R.id}`}],resultText:`Updated widget ${R.id}`,runId:Date.now()}}catch(O){return{status:"error",logs:[{level:"error",text:O.message||String(O)}],resultText:"",runId:Date.now(),error:{message:O.message||String(O),name:"WidgetError",stack:"",text:String(O)}}}else{const O=Ps(k.widgets||[],R.w||4,R.h||4);try{const N=_e.addWidget(k.id,{name:R.name||"Widget",format:R.format||"react",source:R.source||E,x:O.x,y:O.y,w:R.w||4,h:R.h||4});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:k.id}})),{status:"success",logs:[{level:"info",text:`Created widget ${N.id}`}],result:{widgetId:N.id},resultText:`Created widget ${N.id}`,runId:Date.now()}}catch(N){return{status:"error",logs:[{level:"error",text:N.message||String(N)}],resultText:"",runId:Date.now(),error:{message:N.message||String(N),name:"WidgetError",stack:"",text:String(N)}}}}}return x==="_____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: ${x}`}],resultText:"",runId:Date.now(),error:{message:`Unknown gate: ${x}`,name:"UnknownGate",stack:"",text:`Unknown gate: ${x}`}}},[]),C=S.useCallback(async x=>{var R;if(!x.trim()||l)return;const E={role:"user",content:x.trim(),timestamp:Date.now()};i(O=>[...O,E]),c(""),d(!0),w(null),s==null||s("thinking");const j=new AbortController;f.current=j;let k="";try{const O=$f(v.current),N=`canvas-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await el(x.trim(),N,F=>{if(F.type==="token")k+=F.data,i(V=>{const G=V[V.length-1];return G&&G.role==="assistant"?[...V.slice(0,-1),{...G,content:k}]:[...V,{role:"assistant",content:k,timestamp:Date.now()}]});else if(F.type==="done"){const V=F.data||k;k=V,i(G=>{const Z=G[G.length-1];return Z&&Z.role==="assistant"?[...G.slice(0,-1),{...Z,content:V}]:[...G,{role:"assistant",content:V,timestamp:Date.now()}]})}else F.type==="error"&&w(F.data)},j.signal,{systemPromptAppendix:O});const W=Pf(k).filter(F=>F.gate!=="_____transient"&&F.gate!=="_____framework");if(W.length>0){s==null||s("executing");const F=[];for(const Z of W){const B=Ff(`${Z.gate}
903
+ ${Z.code}`);if(!B.valid){F.push({status:"error",logs:[{level:"error",text:B.error||"Invalid execution"}],resultText:"",runId:Date.now(),error:{message:B.error||"Invalid execution",name:"ValidationError",stack:"",text:B.error||""}});continue}const H=await A(Z.gate,Z.code);F.push(H)}const V=Wf(F);i(Z=>[...Z,V]);const G=F.find(Z=>Z.status==="error");G&&w(((R=G.error)==null?void 0:R.text)||"Execution failed")}}catch(O){O.name!=="AbortError"&&w(O.message||"Request failed")}finally{d(!1),f.current=null,s==null||s("idle")}},[l,s,A]),M=S.useCallback(()=>{var x;(x=f.current)==null||x.abort(),f.current=null,d(!1),s==null||s("idle")},[s]),b=S.useCallback(x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),C(a))},[a,C]);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:[r.jsx("iframe",{ref:g,style:{position:"absolute",width:0,height:0,border:0,visibility:"hidden"},sandbox:"allow-scripts"}),r.jsxs("div",{style:{flex:1,overflowY:"auto",padding:12},children:[n.map((x,E)=>r.jsxs("div",{style:{marginBottom:8,padding:8,borderRadius:8,background:x.role==="user"?"rgba(59,130,246,0.15)":x.role==="framework"?"rgba(245,158,11,0.1)":"rgba(255,255,255,0.05)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[r.jsx("div",{style:{fontSize:10,opacity:.6,marginBottom:4,textTransform:"uppercase"},children:x.role}),r.jsx("div",{style:{fontSize:13,lineHeight:1.5},children:x.content}),x.executions&&x.executions.length>0&&r.jsx("div",{style:{marginTop:4,fontSize:11,opacity:.7},children:x.executions.map((j,k)=>r.jsxs("span",{style:{marginRight:8},children:[j.status==="success"?"✓":"✗"," execution ",k+1]},k))})]},E)),l&&r.jsx("div",{style:{fontSize:12,opacity:.5,padding:8},children:"Thinking…"}),p&&r.jsx("div",{style:{color:"#ef4444",fontSize:12,padding:8,background:"rgba(239,68,68,0.1)",borderRadius:6},children:p}),r.jsx("div",{ref:u})]}),r.jsxs("div",{style:{padding:12,borderTop:"1px solid rgba(255,255,255,0.08)",display:"flex",gap:8},children:[r.jsx("input",{type:"text",value:a,onChange:x=>c(x.target.value),onKeyDown:b,placeholder:"Ask TITAN to build something…",disabled:l,style:{flex:1,background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:8,padding:"8px 12px",color:"#fff",fontSize:13,outline:"none"}}),l?r.jsx("button",{onClick:M,style:{padding:"8px 14px",borderRadius:8,border:"none",background:"#ef4444",color:"#fff",fontSize:13,cursor:"pointer"},children:"Stop"}):r.jsx("button",{onClick:()=>C(a),disabled:!a.trim(),style:{padding:"8px 14px",borderRadius:8,border:"none",background:a.trim()?"#3b82f6":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:a.trim()?"pointer":"not-allowed"},children:"Send"})]})]})}const Ci={idle:{eye:"#6366f1",glow:"#818cf8",ring:"#6366f1",body:"#1e1b4b"},thinking:{eye:"#a78bfa",glow:"#a78bfa",ring:"#a78bfa",body:"#1e1b4b"},executing:{eye:"#34d399",glow:"#34d399",ring:"#10b981",body:"#053827"},listening:{eye:"#60a5fa",glow:"#38bdf8",ring:"#0ea5e9",body:"#0c2a4d"},error:{eye:"#ef4444",glow:"#fca5a5",ring:"#ef4444",body:"#3f1818"}},zf=9e4;function Vf({state:t="idle",mood:e="neutral",size:s=96,quip:n=null,bubblePhase:i=null,followCursor:a=!0,somaActive:c=!1,sleepAfterMs:l=zf,className:d="",onClick:p,edgeRotate:w=0,faceFlip:u=!1,edgeHidden:f=!1}){const g=Ci[t]??Ci.idle,[y,v]=S.useState({x:0,y:0}),[A,C]=S.useState({x:0,y:0}),[M,b]=S.useState(!1),[x,E]=S.useState(!1),[j,k]=S.useState(!1),[R,O]=S.useState(!1),[N,L]=S.useState(0),[W,F]=S.useState(!1),[V,G]=S.useState(!1),Z=S.useRef(null),B=S.useRef(Date.now()),H=S.useRef(0),$=S.useRef(0);S.useEffect(()=>{const ie=window.matchMedia("(prefers-reduced-motion: reduce)");G(ie.matches);const de=ye=>G(ye.matches);return ie.addEventListener("change",de),()=>ie.removeEventListener("change",de)},[]),S.useEffect(()=>{B.current=Date.now(),t!=="idle"&&(k(!1),E(!1))},[t]),S.useEffect(()=>{const ie=()=>{B.current=Date.now()};return window.addEventListener("mousemove",ie,{passive:!0}),window.addEventListener("keydown",ie,{passive:!0}),window.addEventListener("click",ie,{passive:!0}),()=>{window.removeEventListener("mousemove",ie),window.removeEventListener("keydown",ie),window.removeEventListener("click",ie)}},[]),S.useEffect(()=>{if(t==="error"||j){b(!1);return}let ie=!1,de=null;const ye=()=>{if(ie)return;const Se=2500+Math.random()*4e3;setTimeout(()=>{ie||(b(!0),de=window.setTimeout(()=>{de=null,ie||b(!1)},140),ye())},Se)};return ye(),()=>{ie=!0,de&&clearTimeout(de)}},[t,j]),S.useEffect(()=>{if(t!=="idle"||j){E(!1);return}let ie=!1,de=null;const ye=()=>{const Se=18e3+Math.random()*17e3;setTimeout(()=>{ie||(E(!0),de=window.setTimeout(()=>{de=null,ie||E(!1)},1600),ye())},Se)};return ye(),()=>{ie=!0,de&&clearTimeout(de)}},[t,j]),S.useEffect(()=>{if(t!=="idle"){k(!1);return}let ie=!1;const de=()=>{const Se=Date.now()-B.current;if(Se>=l)ie||k(!0);else{const q=l-Se;return setTimeout(()=>{ie||de()},Math.min(q,5e3))}},ye=de();return()=>{ie=!0,ye&&clearTimeout(ye)}},[t,l]),S.useEffect(()=>{if(t!=="listening"){O(!1);return}O(!0);const ie=setTimeout(()=>O(!1),1200);return()=>clearTimeout(ie)},[t]),S.useEffect(()=>{if(!a||!Z.current||V)return;const ie=Z.current;let de=null;const ye=Se=>{const q=ie.getBoundingClientRect(),Y=q.left+q.width/2,K=q.top+q.height/2,ae=(Se.clientX-Y)/(q.width/2),I=(Se.clientY-K)/(q.height/2),P=J=>Math.max(-1,Math.min(1,J));if(de={x:P(ae)*10,y:P(I)*8},H.current)return;const z=performance.now();if(z-$.current<33){H.current=requestAnimationFrame(()=>{H.current=0,$.current=performance.now(),de&&(v({x:de.x,y:de.y}),C({x:de.x*.4,y:de.y*.375}),de=null)});return}$.current=z,v({x:de.x,y:de.y}),C({x:de.x*.4,y:de.y*.375}),de=null};return window.addEventListener("mousemove",ye,{passive:!0}),()=>{window.removeEventListener("mousemove",ye),H.current&&cancelAnimationFrame(H.current)}},[a,V]);const ge=S.useCallback(()=>{F(!0),L(ie=>ie+1),setTimeout(()=>F(!1),520),p==null||p()},[p]),fe=M?.6:x?5.5:4.5,be=M?.4:x?3:5.5,ce={squintTop:e==="happy"||e==="tired"},ee=s,Ee=i?`mascot-bubble mascot-bubble--${i}`:"mascot-bubble",Ve=n?`bubble-${n}-${Date.now()}`:"no-bubble";return r.jsxs("div",{ref:Z,className:d,style:{width:ee,height:ee*1.38},children:[r.jsx("style",{children:`
904
+ @keyframes mascot-float {
905
+ 0%, 100% { transform: translate3d(0, 0, 0) rotate(0deg); }
906
+ 25% { transform: translate3d(2px, -6px, 0) rotate(0.6deg); }
907
+ 50% { transform: translate3d(-1px, -3px, 0) rotate(-0.3deg); }
908
+ 75% { transform: translate3d(3px, -5px, 0) rotate(0.4deg); }
909
+ }
910
+ @keyframes mascot-breathe {
911
+ 0%, 100% { transform: scale(1); }
912
+ 50% { transform: scale(1.012); }
913
+ }
914
+ @keyframes mascot-listen-ring {
915
+ 0% { r: 14; opacity: 0.55; }
916
+ 100% { r: 38; opacity: 0; }
917
+ }
918
+ @keyframes mascot-zzz {
919
+ 0% { transform: translate3d(0, 0, 0) scale(0.7); opacity: 0; }
920
+ 30% { opacity: 0.85; }
921
+ 100% { transform: translate3d(10px, -22px, 0) scale(1.1); opacity: 0; }
922
+ }
923
+ @keyframes mascot-poke-bounce {
924
+ 0% { transform: translate3d(0, 0, 0) scale(1); }
925
+ 30% { transform: translate3d(0, -12px, 0) scale(1.06, 0.94); }
926
+ 55% { transform: translate3d(0, 2px, 0) scale(0.97, 1.03); }
927
+ 75% { transform: translate3d(0, -4px, 0) scale(1.02, 0.98); }
928
+ 100% { transform: translate3d(0, 0, 0) scale(1); }
929
+ }
930
+ @keyframes mascot-soma-halo {
931
+ 0%, 100% { stroke-opacity: 0.22; }
932
+ 50% { stroke-opacity: 0.55; }
933
+ }
934
+ @keyframes mascot-thinking-particle {
935
+ 0% { opacity: 0; transform: translate3d(0, 0, 0); }
936
+ 40% { opacity: 1; }
937
+ 100% { opacity: 0; transform: translate3d(6px, -14px, 0); }
938
+ }
939
+ @keyframes mascot-hand-wave {
940
+ 0%, 100% { transform: translate3d(0, 0, 0); }
941
+ 25% { transform: translate3d(6px, -10px, 0); }
942
+ 50% { transform: translate3d(0, -4px, 0); }
943
+ 75% { transform: translate3d(-4px, -8px, 0); }
944
+ }
945
+ /* ── Speech bubble keyframes (Space Agent port) ── */
946
+ @keyframes titan-bubble-land {
947
+ 0% { opacity: 0; transform: translate3d(-50%, 14px, 0) scale(0.76) rotate(-3deg); }
948
+ 58% { opacity: 1; transform: translate3d(-50%, -3px, 0) scale(1.03) rotate(0.8deg); }
949
+ 100% { opacity: 1; transform: translate3d(-50%, 0, 0) scale(1) rotate(0deg); }
950
+ }
951
+ @keyframes titan-bubble-dismiss {
952
+ 0% { opacity: 1; transform: translate3d(-50%, 0, 0) scale(1); }
953
+ 100% { opacity: 0; transform: translate3d(-50%, 8px, 0) scale(0.84); }
954
+ }
955
+ .mascot-body {
956
+ animation: mascot-float 8.4s ease-in-out infinite;
957
+ overflow: visible;
958
+ }
959
+ .mascot-body.sleeping { animation: mascot-float 12s ease-in-out infinite; }
960
+ .mascot-body.poking { animation: mascot-poke-bounce 520ms cubic-bezier(0.28, 0.84, 0.42, 1) both; }
961
+ .mascot-torso { animation: mascot-breathe 4s ease-in-out infinite; }
962
+ .mascot-listen-ring { animation: mascot-listen-ring 1.4s ease-out infinite; }
963
+ .mascot-zzz { animation: mascot-zzz 2.2s ease-in-out infinite; }
964
+ .mascot-hand-r.waving { animation: mascot-hand-wave 1.2s ease-in-out both; }
965
+ .mascot-halo.soma { animation: mascot-soma-halo 3.2s ease-in-out infinite; }
966
+ .mascot-thinking-particle { animation: mascot-thinking-particle 1.6s ease-out infinite; }
967
+ /* Bubble animation classes */
968
+ .mascot-bubble {
969
+ will-change: opacity, transform;
970
+ pointer-events: none;
971
+ }
972
+ .mascot-bubble--entering {
973
+ animation: titan-bubble-land 400ms cubic-bezier(0.2, 1.24, 0.32, 1) both;
974
+ }
975
+ .mascot-bubble--visible {
976
+ opacity: 1;
977
+ transform: translate3d(-50%, 0, 0) scale(1);
978
+ }
979
+ .mascot-bubble--leaving {
980
+ animation: titan-bubble-dismiss 180ms ease both;
981
+ }
982
+ /* Respect reduced-motion */
983
+ @media (prefers-reduced-motion: reduce) {
984
+ .mascot-body, .mascot-torso, .mascot-listen-ring,
985
+ .mascot-zzz, .mascot-hand-r.waving, .mascot-halo.soma,
986
+ .mascot-thinking-particle, .mascot-bubble {
987
+ animation: none !important;
988
+ }
989
+ }
990
+ `}),n&&r.jsxs("div",{className:`${Ee} absolute left-1/2 px-2.5 py-1.5 rounded-xl bg-[#27272a] border border-[#3f3f46] text-[11px] text-[#e4e4e7] whitespace-nowrap shadow-lg`,style:{top:-8,maxWidth:s*2.2,lineHeight:1.35},children:[n,r.jsx("span",{className:"absolute left-1/2 -translate-x-1/2 -bottom-1.5 w-2.5 h-2.5 rotate-45 bg-[#27272a] border-r border-b border-[#3f3f46]"})]},Ve),r.jsx("div",{className:"mascot-root absolute inset-x-0 bottom-0",style:{transform:`perspective(420px) rotateY(${y.x}deg) rotateX(${-y.y}deg)`,transformStyle:"preserve-3d",transition:"transform 120ms ease-out","--glow":g.glow,cursor:p?"pointer":"default",pointerEvents:p?"auto":"none"},onClick:ge,children:r.jsx("div",{style:{width:ee,height:ee*1.38,transform:`rotate(${w}deg) scaleX(${u?-1:1})`,transformOrigin:"center",transition:"transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)"},children:r.jsxs("svg",{viewBox:"0 0 100 138",width:ee,height:ee*1.38,className:["mascot-body",t,j?"sleeping":"",W?"poking":""].join(" ").trim(),style:{display:"block",overflow:"visible"},children:[r.jsxs("defs",{children:[r.jsxs("radialGradient",{id:`mascot-glow-${t}`,cx:"50%",cy:"50%",r:"50%",children:[r.jsx("stop",{offset:"0%",stopColor:g.glow,stopOpacity:t==="executing"?.45:.22}),r.jsx("stop",{offset:"100%",stopColor:g.glow,stopOpacity:0})]}),r.jsxs("linearGradient",{id:`mascot-body-${t}`,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[r.jsx("stop",{offset:"0%",stopColor:g.body}),r.jsx("stop",{offset:"50%",stopColor:"#0a0614"}),r.jsx("stop",{offset:"100%",stopColor:"#050208"})]}),r.jsx("filter",{id:`mascot-shadow-${t}`,children:r.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"3",floodColor:g.ring,floodOpacity:f?"0":"0.35"})})]}),j&&r.jsxs("g",{fontFamily:"ui-sans-serif, system-ui",fontWeight:"700",fill:g.glow,opacity:"0.85",children:[r.jsx("text",{className:"mascot-zzz",x:"66",y:"22",fontSize:"9",style:{animationDelay:"0s"},children:"z"}),r.jsx("text",{className:"mascot-zzz",x:"70",y:"14",fontSize:"11",style:{animationDelay:"0.7s"},children:"Z"}),r.jsx("text",{className:"mascot-zzz",x:"74",y:"6",fontSize:"13",style:{animationDelay:"1.4s"},children:"Z"})]}),r.jsx("circle",{cx:"50",cy:"42",r:"35",fill:`url(#mascot-glow-${t})`}),t==="listening"&&r.jsxs(r.Fragment,{children:[r.jsx("circle",{cx:"50",cy:"42",r:"14",className:"mascot-listen-ring",stroke:g.glow,strokeWidth:"1.5"}),r.jsx("circle",{cx:"50",cy:"42",r:"14",className:"mascot-listen-ring",stroke:g.glow,strokeWidth:"1.5",style:{animationDelay:"0.5s"}})]}),r.jsx("ellipse",{cx:"50",cy:"42",rx:"28",ry:"10",fill:"none",stroke:g.ring,strokeWidth:"1.2",strokeOpacity:"0.35",className:`mascot-halo ${t} ${c?"soma":""}`}),r.jsxs("g",{filter:`url(#mascot-shadow-${t})`,children:[r.jsx("path",{d:"M50 18 L75 32 L75 58 L50 72 L25 58 L25 32 Z",fill:`url(#mascot-body-${t})`,stroke:g.ring,strokeWidth:"1.2",strokeOpacity:"0.6"}),r.jsx("path",{d:"M50 27 L66 36 L66 54 L50 63 L34 54 L34 36 Z",fill:"none",stroke:g.ring,strokeWidth:"0.7",strokeOpacity:"0.3"})]}),r.jsx("rect",{x:"33",y:"39",width:"34",height:"10",rx:"5",fill:"#0a0a0f",stroke:g.ring,strokeWidth:"0.6",strokeOpacity:"0.4"}),r.jsxs("g",{transform:`translate(${A.x}, ${A.y})`,children:[r.jsxs("ellipse",{cx:"50",cy:"44",rx:fe,ry:be,fill:g.eye,style:{transition:"rx 140ms ease-out, ry 140ms ease-out"},children:[t==="thinking"&&!j&&!V&&r.jsx("animate",{attributeName:"cx",values:"47;53;47",dur:"1.6s",repeatCount:"indefinite"}),t==="executing"&&!V&&r.jsx("animate",{attributeName:"rx",values:"4.5;6;4.5",dur:"0.8s",repeatCount:"indefinite"})]}),ce.squintTop&&!M&&!x&&r.jsx("rect",{x:"43",y:"40.5",width:"14",height:"2",rx:"1",fill:g.body,opacity:"0.85"}),!j&&r.jsx("circle",{cx:48+A.x*.4,cy:"43",r:"1",fill:"#ffffff",opacity:"0.7"})]}),r.jsx("rect",{x:"42",y:"66",width:"16",height:"2",rx:"0.6",fill:g.ring,opacity:"0.35"}),r.jsx("rect",{x:"44",y:"66.5",width:"12",height:"1",rx:"0.3",fill:g.glow,opacity:t==="executing"?.9:.5,children:t==="executing"&&!V&&r.jsx("animate",{attributeName:"opacity",values:"0.4;0.9;0.4",dur:"0.6s",repeatCount:"indefinite"})}),r.jsx("rect",{x:"44",y:"72",width:"12",height:"6",fill:g.body,stroke:g.ring,strokeWidth:"0.5",strokeOpacity:"0.5"}),r.jsx("ellipse",{cx:"50",cy:"79",rx:"18",ry:"3",fill:g.body,stroke:g.ring,strokeWidth:"0.8",strokeOpacity:"0.6"}),r.jsxs("g",{className:"mascot-torso",children:[r.jsx("path",{d:"M35 82 L65 82 L68 108 Q68 114 62 114 L38 114 Q32 114 32 108 Z",fill:`url(#mascot-body-${t})`,stroke:g.ring,strokeWidth:"1",strokeOpacity:"0.55",filter:`url(#mascot-shadow-${t})`}),r.jsx("circle",{cx:"50",cy:"96",r:"3.5",fill:"#0a0a0f",stroke:g.ring,strokeWidth:"0.5",strokeOpacity:"0.5"}),r.jsx("circle",{cx:"50",cy:"96",r:"2",fill:g.glow,opacity:t==="idle"?.6:.9,children:!V&&r.jsx("animate",{attributeName:"opacity",values:"0.4;0.9;0.4",dur:t==="executing"?"0.6s":c?"3.2s":"2.5s",repeatCount:"indefinite"})})]}),r.jsx("g",{transform:"translate(22, 96)",children:r.jsxs("g",{className:"mascot-hand-l",children:[r.jsx("circle",{r:"4",fill:g.body,stroke:g.ring,strokeWidth:"0.8",strokeOpacity:"0.6"}),r.jsx("circle",{r:"2",fill:g.glow,opacity:"0.6"})]})}),r.jsx("g",{transform:"translate(78, 96)",children:r.jsxs("g",{className:`${R?"mascot-hand-r waving":"mascot-hand-r"}`,children:[r.jsx("circle",{r:"4",fill:g.body,stroke:g.ring,strokeWidth:"0.8",strokeOpacity:"0.6"}),r.jsx("circle",{r:"2",fill:g.glow,opacity:"0.6"})]})}),t==="thinking"&&r.jsxs("g",{children:[r.jsx("circle",{cx:"60",cy:"14",r:"1.5",className:"mascot-thinking-particle",fill:g.glow,style:{animationDelay:"0s"}}),r.jsx("circle",{cx:"66",cy:"10",r:"1.1",className:"mascot-thinking-particle",fill:g.glow,style:{animationDelay:"0.4s"}}),r.jsx("circle",{cx:"72",cy:"7",r:"0.8",className:"mascot-thinking-particle",fill:g.glow,style:{animationDelay:"0.8s"}})]}),t==="error"&&r.jsxs("g",{stroke:"#ef4444",strokeWidth:"1.8",strokeLinecap:"round",opacity:"0.9",children:[r.jsx("line",{x1:"43",y1:"40",x2:"57",y2:"48"}),r.jsx("line",{x1:"57",y1:"40",x2:"43",y2:"48"})]})]})})})]})}const Va="titan2:chat-dock:pos",Ha="titan2:chat-dock:size",dr="titan2:chat-dock:hidden-edge",qa="titan2:chat-dock:hint-shown",Hf=4,ct=88,Jt=ct*1.38,As=14,qf=320,Gf=360,Yf=960,Kf=900,Jf=420,Xf=560,Vn=8,Zf=20,Qf=64,ep="transform 280ms cubic-bezier(0.22, 1, 0.36, 1)",tp="transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)",sp=400,np=180,rp=1800,ip=1e4,op=28,ap=260,lp=2e3,cp=3500;function dp(){try{const t=localStorage.getItem(Ha);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 ur(e)}}catch{}return{w:Jf,h:Xf}}function up(t){try{localStorage.setItem(Ha,JSON.stringify(t))}catch{}}function ur(t){return{w:Math.max(qf,Math.min(t.w,Yf)),h:Math.max(Gf,Math.min(t.h,Kf))}}function hp(){try{const s=localStorage.getItem(Va);if(s){const n=JSON.parse(s);if(typeof(n==null?void 0:n.x)=="number"&&typeof(n==null?void 0:n.y)=="number")return n}}catch{}const t=typeof window<"u"?window.innerWidth:1280,e=typeof window<"u"?window.innerHeight:800;return{x:t-ct-32,y:e-Jt-32}}function fp(t){try{localStorage.setItem(Va,JSON.stringify(t))}catch{}}function pp(){try{const t=localStorage.getItem(dr);if(t==="left"||t==="right"||t==="top"||t==="bottom")return t}catch{}return null}function gp(t){try{t?localStorage.setItem(dr,t):localStorage.removeItem(dr)}catch{}}let Ga=!1;function Ti(){try{return localStorage.getItem(qa)==="1"}catch{return Ga}}function Ai(){try{localStorage.setItem(qa,"1")}catch{Ga=!0}}function Hn(t){const e=window.innerWidth,s=window.innerHeight;return{x:Math.max(0,Math.min(t.x,e-ct)),y:Math.max(0,Math.min(t.y,s-Jt))}}function Ri(t){const e=window.innerWidth,s=window.innerHeight;return t.x<=Vn?"left":t.x>=e-ct-Vn?"right":t.y>=s-Jt-Vn?"bottom":null}function mp(t,e){if(!t)return"";const s=ct-Zf,n=e?Qf:0;switch(t){case"left":return`translate3d(${-(s-n)}px, 0, 0)`;case"right":return`translate3d(${s-n}px, 0, 0)`;case"top":return`translate3d(0, ${-(s-n)}px, 0)`;case"bottom":return`translate3d(0, ${s-n}px, 0)`;default:return""}}function yp(t){switch(t){case"left":return 90;case"right":return-90;case"top":return 180;case"bottom":return 0;default:return 0}}function wp(t){return t.x>window.innerWidth/2}function bp(t){const e=t.trim().split(/\s+/).filter(Boolean).length,s=rp+t.length*op+e*ap;return Math.min(s,ip)}function xp(t,e){const s=window.innerWidth,n=window.innerHeight,i=s-(t.x+ct),a=n-(t.y+Jt),c=i>=e.w+As?"right":"left",l=a>=e.h+As?"below":"above",d=c==="right"?t.x+ct+As:t.x-e.w-As,p=l==="below"?t.y:t.y+Jt-e.h;return{left:Math.max(8,Math.min(d,s-e.w-8)),top:Math.max(8,Math.min(p,n-e.h-8)),side:c,vertical:l}}function vp({space:t,somaActive:e,defaultExpanded:s=!1}){const[n,i]=S.useState(!1),a=e??n;S.useEffect(()=>{let q=!1;Pe("/api/config").then(K=>K.ok?K.json():null).then(K=>{var ae;q||i(!!((ae=K==null?void 0:K.organism)!=null&&ae.enabled))}).catch(()=>{});const Y=K=>{const ae=K.detail;typeof(ae==null?void 0:ae.enabled)=="boolean"&&i(ae.enabled)};return window.addEventListener("titan:soma:changed",Y),()=>{q=!0,window.removeEventListener("titan:soma:changed",Y)}},[]),S.useEffect(()=>{const q=Y=>{const K=Y.detail;typeof(K==null?void 0:K.open)=="boolean"?u(K.open):u(ae=>!ae)};return window.addEventListener("titan:chat:toggle",q),()=>window.removeEventListener("titan:chat:toggle",q)},[]);const[c,l]=S.useState(()=>Hn(hp())),[d,p]=S.useState(()=>dp()),[w,u]=S.useState(s),[f,g]=S.useState(!1),[y,v]=S.useState(!1),[A,C]=S.useState("idle"),[M,b]=S.useState(()=>pp()),[x,E]=S.useState(!1),[j,k]=S.useState(!1),[R,O]=S.useState(null),N=S.useRef({}),L=S.useRef(null),W=S.useRef(null),F=S.useRef(!1);S.useEffect(()=>{fp(c)},[c]),S.useEffect(()=>{up(d)},[d]),S.useEffect(()=>{gp(M)},[M]),S.useEffect(()=>{const q=window.matchMedia("(prefers-reduced-motion: reduce)");k(q.matches);const Y=K=>k(K.matches);return q.addEventListener("change",Y),()=>q.removeEventListener("change",Y)},[]),S.useEffect(()=>{let q,Y;const K=()=>{clearTimeout(Y),Y=window.setTimeout(()=>{l(P=>{const z=Hn(P),J=Ri(z);return b(J),z}),p(P=>ur(P))},50)},ae=()=>{clearTimeout(q),q=window.setTimeout(K,100)};window.addEventListener("resize",ae),document.addEventListener("visibilitychange",K),window.addEventListener("focus",K),window.addEventListener("pageshow",K);const I=window.setInterval(K,2e3);return()=>{window.removeEventListener("resize",ae),document.removeEventListener("visibilitychange",K),window.removeEventListener("focus",K),window.removeEventListener("pageshow",K),clearTimeout(q),clearTimeout(Y),clearInterval(I)}},[]),S.useEffect(()=>()=>{clearTimeout(N.current.enter),clearTimeout(N.current.exit),clearTimeout(N.current.hide)},[]),S.useEffect(()=>{if(Ti())return;let q,Y;return q=window.setTimeout(()=>{G("Drag me, tap me."),Ai(),Y=window.setTimeout(()=>{Z()},cp),N.current.hide=Y},lp),()=>{clearTimeout(q),clearTimeout(Y)}},[]);const V=S.useCallback(()=>{clearTimeout(N.current.enter),clearTimeout(N.current.exit),clearTimeout(N.current.hide),N.current={}},[]),G=S.useCallback(q=>{V(),O({text:q,phase:"entering"}),N.current.enter=window.setTimeout(()=>{O(K=>K&&K.text===q?{...K,phase:"visible"}:K);const Y=bp(q);N.current.hide=window.setTimeout(()=>{Z()},Y)},sp)},[V]),Z=S.useCallback(()=>{V(),O(q=>q?(N.current.exit=window.setTimeout(()=>{O(null)},np),{...q,phase:"leaving"}):null)},[V]),B=A==="thinking"?"thinking…":A==="executing"?"working on it":null;S.useEffect(()=>{B?G(B):O(q=>q?((q.text==="thinking…"||q.text==="working on it")&&Z(),q):null)},[B]);const H=S.useCallback(q=>{var Y,K;q.button===0&&((K=(Y=q.target).setPointerCapture)==null||K.call(Y,q.pointerId),L.current={pointer:{x:q.clientX,y:q.clientY},pos:c,moved:!1},g(!0),Ti()||Ai())},[c]),$=S.useCallback(q=>{const Y=L.current;if(!Y)return;const K=q.clientX-Y.pointer.x,ae=q.clientY-Y.pointer.y;!Y.moved&&Math.hypot(K,ae)<Hf||(Y.moved=!0,M&&b(null),l(Hn({x:Y.pos.x+K,y:Y.pos.y+ae})))},[M]),ge=S.useCallback(q=>{var K,ae;const Y=L.current;if((ae=(K=q.target).releasePointerCapture)==null||ae.call(K,q.pointerId),L.current=null,g(!1),Y&&Y.moved){const I=Ri(c);b(I||null)}else Y&&!Y.moved&&(M&&b(null),u(I=>!I))},[c,M]),fe=S.useCallback(()=>{M&&E(!0)},[M]),be=S.useCallback(()=>{E(!1)},[]),ce=S.useCallback(q=>{if(q.ctrlKey||f)return;let Y=q.target;for(;Y&&Y!==document.body;){const K=window.getComputedStyle(Y),ae=Y.scrollHeight>Y.clientHeight,I=K.overflowY;if(ae&&(I==="auto"||I==="scroll")){Y.scrollTop+=q.deltaY,q.preventDefault();return}Y=Y.parentElement}window.scrollBy({top:q.deltaY,left:q.deltaX,behavior:"auto"}),q.preventDefault()},[f]),ee=xp(c,d),Ee=(R==null?void 0:R.text)??null,Ve=(R==null?void 0:R.phase)??null,ie=S.useCallback(q=>{var Y,K;q.button===0&&(q.stopPropagation(),(K=(Y=q.target).setPointerCapture)==null||K.call(Y,q.pointerId),W.current={pointer:{x:q.clientX,y:q.clientY},size:d,anchorSide:ee.side,anchorVertical:ee.vertical},v(!0))},[d,ee.side,ee.vertical]),de=S.useCallback(q=>{const Y=W.current;if(!Y)return;const K=q.clientX-Y.pointer.x,ae=q.clientY-Y.pointer.y,I=Y.anchorSide==="right"?K:-K,P=Y.anchorVertical==="below"?ae:-ae;p(ur({w:Y.size.w+I,h:Y.size.h+P}))},[]),ye=S.useCallback(q=>{var Y,K;(K=(Y=q.target).releasePointerCapture)==null||K.call(Y,q.pointerId),W.current=null,v(!1)},[]),Se=mp(M,x);return r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{position:"fixed",left:c.x,top:c.y,width:ct,height:Jt,zIndex:2147482e3,cursor:f?"grabbing":M?"pointer":"grab",touchAction:"none",userSelect:"none",animation:j?void 0:"titan-dock-in 220ms ease-out both",transform:Se,transition:f?"none":`${ep}, ${tp}`},onPointerDown:H,onPointerMove:$,onPointerUp:ge,onPointerCancel:ge,onPointerEnter:fe,onPointerLeave:be,onWheel:ce,title:w?"Click to minimize TITAN chat — drag to move":"Click to open TITAN chat — drag to move",children:r.jsx(Vf,{state:A,size:ct,quip:Ee,bubblePhase:Ve,somaActive:a,followCursor:!f,edgeRotate:yp(M),faceFlip:wp(c),edgeHidden:!!M})}),w&&r.jsxs("div",{style:{position:"fixed",left:ee.left,top:ee.top,width:d.w,height:d.h,zIndex:2147481999,pointerEvents:"auto",borderRadius:14,border:"1px solid rgba(255,255,255,0.08)",background:"rgba(11,11,14,0.72)",backdropFilter:"blur(18px) saturate(1.08)",WebkitBackdropFilter:"blur(18px) saturate(1.08)",boxShadow:"0 18px 44px rgba(0,0,0,0.24)",animation:y||F.current||j?void 0:"titan-dock-panel-in 180ms cubic-bezier(0.2, 0.9, 0.25, 1) both",transformOrigin:`${ee.side==="right"?"left":"right"} ${ee.vertical==="below"?"top":"bottom"}`},children:[r.jsx(za,{space:t,onClose:()=>u(!1),onMascotState:C}),r.jsx("div",{onPointerDown:ie,onPointerMove:de,onPointerUp:ye,onPointerCancel:ye,title:"Drag to resize",style:{position:"absolute",[ee.vertical==="below"?"bottom":"top"]:0,[ee.side==="right"?"right":"left"]:0,width:18,height:18,cursor:ee.side==="right"?"nwse-resize":"nesw-resize",touchAction:"none",background:"transparent",zIndex:2},children:r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 18 18",style:{display:"block",opacity:y?1:.55},children:ee.side==="right"?r.jsxs("g",{stroke:"#6366f1",strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[r.jsx("line",{x1:"5",y1:"14",x2:"14",y2:"14"}),r.jsx("line",{x1:"9",y1:"10",x2:"14",y2:"10"}),r.jsx("line",{x1:"14",y1:"14",x2:"14",y2:"5"})]}):r.jsxs("g",{stroke:"#6366f1",strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[r.jsx("line",{x1:"4",y1:"14",x2:"13",y2:"14"}),r.jsx("line",{x1:"4",y1:"10",x2:"9",y2:"10"}),r.jsx("line",{x1:"4",y1:"14",x2:"4",y2:"5"})]})})})]}),r.jsx("style",{children:`
991
+ @keyframes titan-dock-in {
992
+ from { opacity: 0; transform: translate3d(0, 4px, 0); }
993
+ to { opacity: 1; transform: translate3d(0, 0, 0); }
994
+ }
995
+ @keyframes titan-dock-panel-in {
996
+ from { opacity: 0; transform: translate3d(0, 12px, 0) scale(0.968); }
997
+ to { opacity: 1; transform: translate3d(0, 0, 0) scale(1); }
998
+ }
999
+ @media (prefers-reduced-motion: reduce) {
1000
+ .titan-dock-root, .titan-dock-panel {
1001
+ animation: none !important;
1002
+ transition: none !important;
1003
+ }
1004
+ }
1005
+ `})]})}const qn=4e3,_p=[{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 kp({space:t,open:e,onClose:s,onSaved:n}){const[i,a]=S.useState(t.agentInstructions??""),[c,l]=S.useState(!1),[d,p]=S.useState(null),w=S.useRef(null);S.useEffect(()=>{if(e){a(t.agentInstructions??""),p(null);const f=setTimeout(()=>{var g;return(g=w.current)==null?void 0:g.focus()},50);return()=>clearTimeout(f)}},[e,t.id,t.agentInstructions]),S.useEffect(()=>{if(!e)return;const f=g=>{g.key==="Escape"&&s(),g.key==="Enter"&&(g.metaKey||g.ctrlKey)&&u()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e]);const u=S.useCallback(async()=>{if(i.length>qn){p(`Instructions must be ${qn} characters or fewer.`);return}l(!0),p(null);try{const f=i.trim(),g={...t,agentInstructions:f||void 0,updatedAt:new Date().toISOString()};_e.save(g),n==null||n(f),s()}catch(f){p(f.message)}finally{l(!1)}},[i,t,n,s]);return e?r.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:r.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:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-[#27272a]",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(os,{className:"w-4 h-4 text-[#6366f1]"}),r.jsxs("h3",{className:"font-semibold text-white text-sm",children:["Agent instructions — ",r.jsx("span",{style:{color:t.color||"#6366f1"},children:t.name})]})]}),r.jsx("button",{onClick:s,className:"p-1 rounded hover:bg-[#27272a] text-[#71717a] hover:text-white transition-colors",title:"Close (Esc)",children:r.jsx(ws,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"p-5 flex-1 overflow-auto space-y-3",children:[r.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."}),r.jsx("textarea",{ref:w,value:i,onChange:f=>a(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"}),r.jsxs("div",{className:"flex items-center justify-between text-[10px] text-[#71717a]",children:[r.jsxs("span",{children:[i.length.toLocaleString()," / ",qn.toLocaleString()," characters"]}),r.jsx("span",{children:"⌘/Ctrl + Enter to save"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wider text-[#71717a] mb-2",children:"Quick presets"}),r.jsx("div",{className:"grid grid-cols-2 gap-2",children:_p.map(f=>r.jsxs("button",{onClick:()=>a(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:[r.jsx("div",{className:"text-[11px] font-medium text-white mb-1",children:f.label}),r.jsx("div",{className:"text-[10px] text-[#a1a1aa] line-clamp-2 leading-relaxed",children:f.body})]},f.label))})]}),d&&r.jsx("div",{className:"text-[11px] text-[#ef4444] bg-[#ef4444]/10 border border-[#ef4444]/30 rounded p-2",children:d})]}),r.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-[#27272a]",children:[r.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"}),r.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:[r.jsx(an,{className:"w-3.5 h-3.5"}),c?"Saving…":"Save"]})]})]})}):null}const Ep=12,Sp=["react","vanilla","html"];function jp({widget:t,spaceId:e,open:s,onClose:n,onSaved:i}){const[a,c]=S.useState(t.source),[l,d]=S.useState(t.format),[p,w]=S.useState(t.name),[u,f]=S.useState(!1),[g,y]=S.useState(null),[v,A]=S.useState(!1),C=S.useRef(null);S.useEffect(()=>{if(s){c(t.source),d(t.format),w(t.name),y(null),A(!1);const j=setTimeout(()=>{var k;return(k=C.current)==null?void 0:k.focus()},50);return()=>clearTimeout(j)}},[s,t.id,t.source,t.format,t.name]),S.useEffect(()=>{if(!s)return;const j=k=>{k.key==="Escape"&&n(),k.key==="Enter"&&(k.metaKey||k.ctrlKey)&&M()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[s]);const M=S.useCallback(async()=>{f(!0),y(null);try{const j=a!==t.source||l!==t.format,k=Array.isArray(t.versions)?t.versions:[],R=j?[...k,{source:t.source,format:t.format,savedAt:t.updatedAt}].slice(-Ep):k,O={name:p.trim()||t.name,source:a,format:l,versions:R};_e.updateWidget(e,t.id,O),i==null||i({...t,...O,updatedAt:Date.now()}),n()}catch(j){y(j.message)}finally{f(!1)}},[a,l,p,t,e,i,n]),b=S.useCallback(j=>{c(j.source),d(j.format),A(!1)},[]);if(!s)return null;const x=Array.isArray(t.versions)?t.versions:[],E=[...x].reverse();return r.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:n,children:r.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:j=>j.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-[#27272a]",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(Hl,{className:"w-4 h-4 text-[#6366f1] shrink-0"}),r.jsx("input",{value:p,onChange:j=>w(j.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"}),r.jsx("span",{className:"text-[10px] font-mono text-[#52525b] shrink-0",children:t.id.slice(0,14)})]}),r.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[r.jsx("button",{onClick:()=>A(j=>!j),disabled:x.length===0,className:`p-1.5 rounded text-[#a1a1aa] hover:bg-[#18181b] hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${v?"bg-[#18181b] text-white":""}`,title:x.length===0?"No history yet":`${x.length} prior version${x.length===1?"":"s"}`,children:r.jsx(Ol,{className:"w-4 h-4"})}),r.jsx("button",{onClick:n,className:"p-1.5 rounded text-[#71717a] hover:bg-[#18181b] hover:text-white transition-colors",title:"Close (Esc)",children:r.jsx(ws,{className:"w-4 h-4"})})]})]}),r.jsxs("div",{className:"flex items-center gap-3 px-5 py-2 border-b border-[#27272a] text-[11px]",children:[r.jsxs("label",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-[#71717a]",children:"format"}),r.jsx("select",{value:l,onChange:j=>d(j.target.value),className:"bg-[#18181b] border border-[#27272a] rounded px-2 py-0.5 text-[#e4e4e7] focus:outline-none focus:border-[#6366f1]/60",children:Sp.map(j=>r.jsx("option",{value:j,children:j},j))})]}),r.jsx("span",{className:"text-[#52525b]",children:"·"}),r.jsxs("span",{className:"text-[#71717a]",children:["updated ",r.jsx("span",{className:"text-[#a1a1aa]",children:new Date(t.updatedAt).toLocaleString()})]}),r.jsx("span",{className:"text-[#52525b]",children:"·"}),r.jsxs("span",{className:"text-[#71717a]",children:[t.w," × ",t.h," grid cells"]}),r.jsx("div",{className:"ml-auto text-[10px] text-[#52525b]",children:"⌘/Ctrl + Enter to save"})]}),r.jsxs("div",{className:"flex-1 flex min-h-0",children:[r.jsx("textarea",{ref:C,value:a,onChange:j=>c(j.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:Np[l]}),v&&r.jsxs("div",{className:"w-72 flex flex-col border-l border-[#27272a] bg-[#0a0a0e]",children:[r.jsxs("div",{className:"px-3 py-2 border-b border-[#27272a] text-[10px] uppercase tracking-wider text-[#71717a]",children:["History (",x.length,")"]}),r.jsxs("div",{className:"flex-1 overflow-auto",children:[E.length===0&&r.jsx("div",{className:"p-3 text-[11px] text-[#52525b]",children:"No prior versions yet — save to start tracking."}),E.map((j,k)=>r.jsxs("div",{className:"px-3 py-2 border-b border-[#18181b] hover:bg-[#18181b]/40 transition-colors",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[r.jsx("div",{className:"text-[10px] font-mono text-[#a1a1aa]",children:new Date(j.savedAt).toLocaleString()}),r.jsxs("button",{onClick:()=>b(j),className:"inline-flex items-center gap-1 text-[10px] text-[#6366f1] hover:text-[#a5b4fc] transition-colors",title:"Load this version into the editor",children:[r.jsx(qi,{className:"w-3 h-3"}),"revert"]})]}),r.jsxs("div",{className:"text-[10px] text-[#71717a] font-mono",children:["format: ",j.format]}),r.jsxs("div",{className:"text-[10px] text-[#52525b] truncate mt-1",title:j.source.slice(0,280),children:[j.source.slice(0,80),j.source.length>80?"…":""]}),k===0&&r.jsx("div",{className:"text-[9px] text-[#6366f1] mt-1",children:"most recent before current"})]},j.savedAt))]})]})]}),r.jsxs("div",{className:"flex items-center justify-between gap-2 px-5 py-3 border-t border-[#27272a]",children:[r.jsx("div",{className:"text-[10px] text-[#71717a]",children:g?r.jsxs("span",{className:"text-[#ef4444]",children:["Error: ",g]}):a!==t.source||l!==t.format||p!==t.name?"Unsaved changes":"Up to date"}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("button",{onClick:n,className:"px-3 py-1.5 rounded-lg text-[12px] text-[#a1a1aa] hover:text-white hover:bg-[#18181b] transition-colors",children:"Cancel"}),r.jsxs("button",{onClick:()=>{M()},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:[r.jsx(an,{className:"w-3.5 h-3.5"}),u?"Saving…":"Save widget"]})]})]})]})})}const Np={react:`// Return a React component named "Widget". titan.* APIs are
1006
+ // available for fetch/api/state. Example:
1007
+ function Widget({ titan }) {
1008
+ const [n, setN] = React.useState(0);
1009
+ return <button onClick={() => setN(n + 1)}>Clicked {n} times</button>;
1010
+ }`,vanilla:`// Export a function (container, titan) => cleanup | void.
1011
+ // Called once to mount; return a cleanup function if needed.
1012
+ (container, titan) => {
1013
+ container.innerHTML = '<button>Hello</button>';
1014
+ const btn = container.querySelector('button');
1015
+ btn.addEventListener('click', () => btn.textContent = 'Clicked!');
1016
+ }`,html:`<!-- Raw HTML. No scripts run. -->
1017
+ <div style="padding:16px;color:#e4e4e7">Hello, widget!</div>`,iframe:"",system:""},Cp={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 Tp(t){return t.split(/[-_/]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Ap({open:t,onClose:e}){const[s,n]=S.useState([]),[i,a]=S.useState([]),[c,l]=S.useState("All"),[d,p]=S.useState(!1),[w,u]=S.useState(null);if(S.useEffect(()=>{t&&(p(!0),fetch("/api/widget-gallery").then(v=>v.json()).then(v=>{n(v.templates||[]),a(v.categories||[]),p(!1)}).catch(v=>{u(v.message),p(!1)}))},[t]),S.useEffect(()=>{if(!t)return;const v=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[t,e]),!t)return null;const f=c==="All"?s:s.filter(v=>v.category===c),g=v=>{const A=`Create a "${v.name}" widget using the gallery template "${v.id}". Call gallery_search with "${v.name}" to find it, then gallery_get to fetch the source, and emit it onto the canvas.`;window.dispatchEvent(new CustomEvent("titan:chat:toggle",{detail:{open:!0}})),setTimeout(()=>{window.dispatchEvent(new CustomEvent("titan:chat:prompt",{detail:{text:A}}))},120),e()},y=["All",...i.map(v=>v.category)];return r.jsx("div",{className:"fixed inset-0 z-[2147483150] flex items-center justify-center p-4",style:{background:"rgba(0, 0, 0, 0.66)",backdropFilter:"blur(4px)"},onClick:e,children:r.jsxs("div",{className:"w-full max-w-4xl rounded-2xl border border-[#27272a] bg-[#0c0c10] shadow-2xl flex flex-col",style:{height:"min(720px, 90vh)"},onClick:v=>v.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-[#27272a]",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(hr,{className:"w-4 h-4 text-[#a78bfa]"}),r.jsx("h3",{className:"font-semibold text-white text-sm",children:"Widget gallery"}),r.jsx("span",{className:"text-[10px] text-[#71717a]",children:d?"Loading…":`${s.length} templates`})]}),r.jsx("button",{onClick:e,className:"p-1 rounded text-[#71717a] hover:bg-[#18181b] hover:text-white transition-colors",title:"Close (Esc)",children:r.jsx(ws,{className:"w-4 h-4"})})]}),r.jsx("div",{className:"flex items-center gap-1.5 px-5 py-2 border-b border-[#27272a] text-[11px] overflow-x-auto",children:y.map(v=>{var A;return r.jsxs("button",{onClick:()=>l(v),className:`px-2.5 py-1 rounded-full border transition-colors whitespace-nowrap ${c===v?"border-[#6366f1] bg-[#6366f1]/15 text-white":"border-[#27272a] bg-transparent text-[#a1a1aa] hover:border-[#3f3f46] hover:text-white"}`,children:[Tp(v),v!=="All"&&r.jsx("span",{className:"ml-1.5 text-[9px] opacity-70",children:((A=i.find(C=>C.category===v))==null?void 0:A.count)??0})]},v)})}),r.jsxs("div",{className:"flex-1 overflow-auto p-4",children:[d&&r.jsx("div",{className:"flex items-center justify-center h-full text-[#a1a1aa] text-sm",children:"Loading templates…"}),w&&r.jsxs("div",{className:"flex items-center justify-center h-full text-[#f87171] text-sm",children:["Error: ",w]}),!d&&!w&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:f.map(v=>r.jsxs("button",{onClick:()=>g(v),className:"text-left p-3 rounded-lg border border-[#27272a] bg-[#18181b]/60 hover:border-[#6366f1]/50 hover:bg-[#18181b] transition-colors group",children:[r.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{background:Cp[v.category]??"#9ca3af"}}),r.jsx("span",{className:"text-[12px] font-medium text-white truncate",children:v.name})]}),r.jsx(Gi,{className:"w-3 h-3 text-[#52525b] group-hover:text-[#a5b4fc] transition-colors shrink-0"})]}),r.jsx("div",{className:"text-[11px] text-[#a1a1aa] leading-relaxed line-clamp-2",children:v.description}),v.tags&&v.tags.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:v.tags.slice(0,3).map(A=>r.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-[#27272a] text-[#71717a]",children:A},A))})]},v.id))}),f.length===0&&r.jsx("div",{className:"flex items-center justify-center h-40 text-[#a1a1aa] text-sm",children:"No templates in this category."})]}),r.jsxs("div",{className:"mt-4 p-3 rounded-lg border border-dashed border-[#27272a] bg-[#0a0a0e] flex items-start gap-2",children:[r.jsx(Bi,{className:"w-3.5 h-3.5 text-[#71717a] mt-0.5 shrink-0"}),r.jsxs("div",{className:"text-[11px] text-[#a1a1aa] leading-relaxed",children:["Don’t see what you want? Open the chat (click the mascot) and describe your widget in plain English. TITAN can build anything that runs inside a sandboxed iframe with access to ",r.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.fetch"}),","," ",r.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.api.call"}),", and"," ",r.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.state"}),"."]})]})]})]})})}const Rp=[{type:"widget",source:"system:nav",name:"Nav Widget",w:3,h:4,icon:r.jsx(Bi,{className:"w-4 h-4"})},{type:"widget",source:"system:chat",name:"Chat Widget",w:4,h:5,icon:r.jsx($i,{className:"w-4 h-4"})},{type:"widget",source:"system:soma",name:"SOMA",w:6,h:6,icon:r.jsx(mt,{className:"w-4 h-4"})},{type:"widget",source:"system:command-post",name:"Command Post",w:8,h:6,icon:r.jsx(Yi,{className:"w-4 h-4"})},{type:"widget",source:"system:intelligence",name:"Intelligence",w:6,h:5,icon:r.jsx(zi,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-graph",name:"Memory Graph",w:8,h:7,icon:r.jsx(kl,{className:"w-4 h-4"})},{type:"widget",source:"system:voice",name:"Voice",w:5,h:5,icon:r.jsx(Di,{className:"w-4 h-4"})},{type:"widget",source:"system:infra",name:"Infrastructure",w:6,h:4,icon:r.jsx(gr,{className:"w-4 h-4"})},{type:"widget",source:"system:tools",name:"Tools",w:5,h:4,icon:r.jsx(wr,{className:"w-4 h-4"})},{type:"widget",source:"system:settings",name:"Settings",w:5,h:5,icon:r.jsx(mr,{className:"w-4 h-4"})},{type:"widget",source:"system:files",name:"Files",w:4,h:6,icon:r.jsx(rn,{className:"w-4 h-4"})},{type:"widget",source:"system:daemon",name:"Daemon",w:6,h:6,icon:r.jsx(gt,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-wiki",name:"Memory Wiki",w:6,h:6,icon:r.jsx(os,{className:"w-4 h-4"})},{type:"widget",source:"system:autoresearch",name:"Autoresearch",w:6,h:6,icon:r.jsx(Ui,{className:"w-4 h-4"})},{type:"widget",source:"system:self-proposals",name:"Self-Proposals",w:6,h:6,icon:r.jsx(Wi,{className:"w-4 h-4"})},{type:"widget",source:"system:overview",name:"Overview",w:6,h:5,icon:r.jsx(Pi,{className:"w-4 h-4"})},{type:"widget",source:"system:sessions",name:"Sessions",w:6,h:5,icon:r.jsx(as,{className:"w-4 h-4"})},{type:"widget",source:"system:watch",name:"Watch",w:8,h:7,icon:r.jsx(gt,{className:"w-4 h-4"})},{type:"widget",source:"system:backup",name:"Backup Manager",w:6,h:6,icon:r.jsx(Mi,{className:"w-4 h-4"})},{type:"widget",source:"system:training",name:"Training Dashboard",w:6,h:6,icon:r.jsx(mt,{className:"w-4 h-4"})},{type:"widget",source:"system:recipes",name:"Recipe Kitchen",w:6,h:6,icon:r.jsx(os,{className:"w-4 h-4"})},{type:"widget",source:"system:vram",name:"VRAM Monitor",w:6,h:6,icon:r.jsx(fr,{className:"w-4 h-4"})},{type:"widget",source:"system:teams",name:"Team Hub",w:6,h:6,icon:r.jsx(yr,{className:"w-4 h-4"})},{type:"widget",source:"system:cron",name:"Cron Scheduler",w:6,h:6,icon:r.jsx(as,{className:"w-4 h-4"})},{type:"widget",source:"system:checkpoints",name:"Checkpoints",w:6,h:5,icon:r.jsx(an,{className:"w-4 h-4"})},{type:"widget",source:"system:organism",name:"Organism Monitor",w:6,h:6,icon:r.jsx(pr,{className:"w-4 h-4"})},{type:"widget",source:"system:fleet",name:"Fleet Router",w:6,h:5,icon:r.jsx(Hi,{className:"w-4 h-4"})},{type:"widget",source:"system:browser",name:"Browser Tools",w:6,h:5,icon:r.jsx(Ii,{className:"w-4 h-4"})},{type:"widget",source:"system:paperclip",name:"Paperclip",w:6,h:5,icon:r.jsx(Vi,{className:"w-4 h-4"})},{type:"widget",source:"system:eval",name:"Test Lab",w:6,h:6,icon:r.jsx(Ki,{className:"w-4 h-4"})}];function Ya({currentSpaceId:t,onSpaceSelect:e,onAction:s,onClose:n}){const[i,a]=S.useState(""),[c,l]=S.useState(0),d=S.useRef(null),p=_e.list(),w=S.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})),g=Rp.filter(y=>y.name.toLowerCase().includes(u)).map(y=>({type:"action",action:y,name:y.name}));return[...f,...g]},[i,p,t]);return S.useEffect(()=>{var u;(u=d.current)==null||u.focus()},[]),S.useEffect(()=>{l(0)},[i]),S.useEffect(()=>{const u=f=>{if(f.key==="Escape"){n();return}if(f.key==="ArrowDown"){f.preventDefault(),l(g=>Math.min(g+1,w.length-1));return}if(f.key==="ArrowUp"){f.preventDefault(),l(g=>Math.max(g-1,0));return}if(f.key==="Enter"){f.preventDefault();const g=w[c];if(!g)return;g.type==="space"&&e(g.id),g.type==="action"&&s(g.action)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[w,c,e,s,n]),r.jsx("div",{className:"fixed inset-0 z-[100] flex items-start justify-center pt-[20vh]",onClick:n,children:r.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:[r.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#27272a]/40",children:[r.jsx(ec,{className:"w-4 h-4 text-[#3f3f46]"}),r.jsx("input",{ref:d,value:i,onChange:u=>a(u.target.value),placeholder:"Search spaces, widgets, actions...",className:"flex-1 bg-transparent text-sm text-[#e4e4e7] placeholder:text-[#3f3f46] outline-none"}),r.jsx("button",{onClick:n,className:"text-[#3f3f46] hover:text-[#71717a]",children:r.jsx(ws,{className:"w-4 h-4"})})]}),r.jsxs("div",{className:"max-h-[50vh] overflow-auto py-1",children:[w.length===0&&r.jsxs("div",{className:"px-4 py-6 text-center text-xs text-[#52525b]",children:['No results for "',i,'"']}),w.map((u,f)=>r.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"?r.jsx("div",{className:"w-4 h-4 rounded-full",style:{background:u.color||"#52525b"}}):r.jsx("span",{className:"text-[#6366f1]/60",children:u.action.icon}),r.jsx("span",{className:"text-sm",children:u.name}),r.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))]}),r.jsxs("div",{className:"px-4 py-2 border-t border-[#27272a]/40 flex items-center gap-3 text-[10px] text-[#3f3f46]",children:[r.jsx("span",{children:"↑↓ Navigate"}),r.jsx("span",{children:"↵ Select"}),r.jsx("span",{children:"ESC Close"})]})]})})}const Lp=te.lazy(()=>se(()=>import("./SomaView-CWnPKEQI.js"),__vite__mapDeps([0,1,2,3,4,5,6])));function Ka(){const[t,e]=S.useState(null),[s,n]=S.useState(!1),[i,a]=S.useState(null),c=S.useCallback(async()=>{var p;try{const w=await Pe("/api/config");if(!w.ok)throw new Error(`HTTP ${w.status}`);const u=await w.json();e(!!((p=u==null?void 0:u.organism)!=null&&p.enabled)),a(null)}catch(w){a(w.message),e(!1)}},[]);S.useEffect(()=>{c()},[c]);const l=S.useRef(0),d=S.useCallback(async p=>{const w=++l.current;n(!0),a(null);try{const u=await Pe("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:{enabled:p}})});if(w!==l.current)return;if(!u.ok)throw new Error(`HTTP ${u.status}`);e(p),window.dispatchEvent(new CustomEvent("titan:soma:changed",{detail:{enabled:p}}))}catch(u){if(w!==l.current)return;a(u.message)}finally{w===l.current&&n(!1)}},[]);return t===null?r.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs text-[#52525b]",children:"Loading Soma…"}):t?r.jsxs("div",{className:"w-full h-full overflow-auto flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-[#27272a]/40 bg-[#18181b]/60",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-[#34d399] animate-pulse"}),r.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-[#34d399]",children:"Soma active"})]}),r.jsxs("button",{onClick:()=>d(!1),disabled:s,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border border-[#27272a] text-[10px] text-[#a1a1aa] hover:text-white hover:border-[#3f3f46] disabled:opacity-60 transition-colors",title:"Disable Soma",children:[r.jsx(Zr,{className:"w-3 h-3"}),s?"saving…":"disable"]})]}),r.jsx("div",{className:"flex-1 overflow-auto",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Soma dashboard…"}),children:r.jsx(Lp,{})})})]}):r.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-4 p-6 text-center",children:[r.jsx("div",{className:"w-14 h-14 rounded-full bg-gradient-to-br from-[#6366f1]/20 to-[#a78bfa]/20 border border-[#6366f1]/30 flex items-center justify-center",children:r.jsx(gt,{className:"w-7 h-7 text-[#a78bfa]"})}),r.jsxs("div",{className:"space-y-1 max-w-md",children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:"Soma is off"}),r.jsx("p",{className:"text-xs text-[#a1a1aa] leading-relaxed",children:"TITAN’s homeostatic drive layer. When enabled, TITAN has a sense of its own state — purpose, curiosity, hunger, safety, social, rest — and will propose work when those drives drift. Every proposal still requires your approval."})]}),r.jsxs("button",{onClick:()=>d(!0),disabled:s,className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-[#6366f1] hover:bg-[#4f46e5] disabled:opacity-60 disabled:cursor-not-allowed text-white text-sm font-medium transition-colors",children:[r.jsx(Zr,{className:"w-4 h-4"}),s?"Enabling…":"Enable Soma"]}),i&&r.jsx("p",{className:"text-xs text-[#ef4444]",children:i}),r.jsx("p",{className:"text-[10px] text-[#52525b]",children:"You can turn this off anytime from the same button."})]})}const Ip={calm:{primary:"#6366f1",glow:"rgba(99,102,241,0.4)",pulse:"rgba(99,102,241,0.15)"},focused:{primary:"#10b981",glow:"rgba(16,185,129,0.4)",pulse:"rgba(16,185,129,0.15)"},excited:{primary:"#f59e0b",glow:"rgba(245,158,11,0.4)",pulse:"rgba(245,158,11,0.15)"},concerned:{primary:"#ef4444",glow:"rgba(239,68,68,0.4)",pulse:"rgba(239,68,68,0.15)"},dreaming:{primary:"#8b5cf6",glow:"rgba(139,92,246,0.4)",pulse:"rgba(139,92,246,0.15)"}};function Dp(t,e,s){if(!s)return{emotion:"dreaming",intensity:.25,activity:"Dormant"};const n=e[0],i=Math.min(1,t/2);switch(n){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 Mp(){const[t,e]=S.useState(!1),[s,n]=S.useState({emotion:"calm",intensity:.3,activity:"Observing"}),[i,a]=S.useState(!1),[c,l]=S.useState({x:24,y:80}),[d,p]=S.useState(!1),w=S.useRef({x:0,y:0}),u=S.useRef(null);S.useEffect(()=>{let A=!1;const C=async()=>{try{const b=await Pe("/api/soma/state");if(!b.ok||A)return;const x=await b.json();if(A)return;n(Dp(Number((x==null?void 0:x.totalPressure)??0),Array.isArray(x==null?void 0:x.dominantDrives)?x.dominantDrives:[],!!(x!=null&&x.enabled)))}catch{}};C();const M=setInterval(C,15e3);return()=>{A=!0,clearInterval(M)}},[]),S.useEffect(()=>{const A=C=>{var M;(M=u.current)!=null&&M.contains(C.target)||a(!1)};return window.addEventListener("mousedown",A),()=>window.removeEventListener("mousedown",A)},[]);const f=A=>{A.button===0&&(w.current={x:A.clientX-c.x,y:A.clientY-c.y},p(!0))},g=A=>{d&&l({x:A.clientX-w.current.x,y:A.clientY-w.current.y})},y=()=>{p(!1)},v=Ip[s.emotion];return r.jsxs(r.Fragment,{children:[t&&r.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black/40 backdrop-blur-sm",onClick:()=>e(!1),children:r.jsxs("div",{className:"bg-[#18181b]/98 border border-[#27272a]/60 rounded-2xl shadow-2xl shadow-black/60 overflow-hidden",style:{width:"min(900px, 90vw)",height:"min(600px, 80vh)"},onClick:A=>A.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-[#27272a]/40",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(mt,{className:"w-4 h-4",style:{color:v.primary}}),r.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider text-[#a1a1aa]",children:"SOMA Consciousness"})]}),r.jsx("button",{onClick:()=>e(!1),className:"p-1 text-[#3f3f46] hover:text-[#71717a]",children:r.jsx(ws,{className:"w-4 h-4"})})]}),r.jsx("div",{className:"h-[calc(100%-40px)]",children:r.jsx(Ka,{})})]})}),r.jsxs("div",{ref:u,className:"fixed z-50 select-none",style:{left:c.x,top:c.y},onMouseDown:f,onMouseMove:g,onMouseUp:y,onMouseLeave:y,children:[i&&r.jsxs("div",{className:"absolute bottom-full left-0 mb-2 bg-[#18181b]/98 backdrop-blur-xl border border-[#27272a]/60 rounded-xl shadow-2xl shadow-black/60 overflow-hidden min-w-[160px] py-1",children:[r.jsxs("button",{onClick:()=>{e(!0),a(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] text-[#a1a1aa] hover:bg-[#27272a]/40 transition-colors",children:[r.jsx(mt,{className:"w-3.5 h-3.5",style:{color:v.primary}}),"Open SOMA"]}),r.jsxs("button",{onClick:()=>{a(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] text-[#a1a1aa] hover:bg-[#27272a]/40 transition-colors",children:[r.jsx(hr,{className:"w-3.5 h-3.5 text-[#f59e0b]"}),"Summarize Canvas"]}),r.jsxs("button",{onClick:()=>{a(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] text-[#a1a1aa] hover:bg-[#27272a]/40 transition-colors",children:[r.jsx(tl,{className:"w-3.5 h-3.5 text-[#6366f1]"}),"Run Self-Check"]})]}),r.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>!d&&e(!0),onContextMenu:A=>{A.preventDefault(),a(!0)},children:[r.jsx("div",{className:"absolute inset-0 rounded-full animate-ping opacity-20",style:{background:v.pulse,animationDuration:`${3-s.intensity*2}s`}}),r.jsx("div",{className:"absolute -inset-2 rounded-full opacity-30 blur-md transition-all duration-1000",style:{background:v.glow}}),r.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%, ${v.primary}, ${v.primary}88)`,boxShadow:`0 0 ${20+s.intensity*30}px ${v.glow}, inset 0 0 10px rgba(255,255,255,0.1)`},children:r.jsx(mt,{className:"w-5 h-5 text-white/90"})}),r.jsx("div",{className:"absolute -bottom-5 left-1/2 -translate-x-1/2 whitespace-nowrap",children:r.jsx("span",{className:"text-[9px] font-medium uppercase tracking-wider text-[#52525b] bg-[#0a0a0f]/80 px-1.5 py-0.5 rounded",children:s.activity})})]})]})]})}const Op=te.lazy(()=>se(()=>import("./CommandPostHub-BPPaUv1B.js").then(t=>t.C),__vite__mapDeps([7,1,2,3,8,9,4,5,10,11,12,13,14,15])));function Pp(){return r.jsx("div",{className:"w-full h-full overflow-auto p-2",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Command Post..."}),children:r.jsx(Op,{})})})}const Up=te.lazy(()=>se(()=>import("./IntelligenceView-smQ6aBwx.js"),__vite__mapDeps([16,1,2])));function Wp(){return r.jsx("div",{className:"w-full h-full overflow-auto",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Intelligence..."}),children:r.jsx(Up,{})})})}const Bp=te.lazy(()=>se(()=>import("./MemoryGraphPanel-BGOeSaET.js"),__vite__mapDeps([17,1,2,15,5])));function Fp(){return r.jsx("div",{className:"w-full h-full overflow-auto bg-[#09090b]",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"h-full flex items-center justify-center",children:r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-[#6366f1]/20 border-t-[#6366f1] animate-spin mx-auto mb-3"}),r.jsx("p",{className:"text-[11px] text-[#52525b]",children:"Loading memory graph..."})]})}),children:r.jsx("div",{className:"p-4",children:r.jsx(Bp,{})})})})}function $p(){const[t,e]=S.useState(!1);return t?r.jsx(cl,{onClose:()=>e(!1)}):r.jsx("div",{className:"w-full h-full flex flex-col items-center justify-center bg-[#09090b]",children:r.jsxs("button",{onClick:()=>e(!0),className:"group relative flex flex-col items-center gap-4",children:[r.jsxs("div",{className:"relative w-20 h-20 rounded-full flex items-center justify-center transition-all duration-300 group-hover:scale-110",children:[r.jsx("div",{className:"absolute inset-0 rounded-full bg-[#6366f1]/20 animate-pulse"}),r.jsx("div",{className:"absolute inset-0 rounded-full bg-gradient-to-br from-[#6366f1]/30 to-[#4f46e5]/10 border border-[#6366f1]/30"}),r.jsx(Di,{className:"w-8 h-8 text-[#818cf8] relative z-10"})]}),r.jsxs("div",{className:"text-center",children:[r.jsx("p",{className:"text-sm font-medium text-[#a1a1aa]",children:"Tap to speak"}),r.jsx("p",{className:"text-[10px] text-[#52525b] mt-1",children:"F5-TTS · Voice Cloning"})]})]})})}const zp=te.lazy(()=>se(()=>import("./InfraView-eS7cpESw.js"),__vite__mapDeps([18,1,2])));function Vp(){return r.jsx("div",{className:"w-full h-full overflow-auto",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Infrastructure..."}),children:r.jsx(zp,{})})})}const Hp=te.lazy(()=>se(()=>import("./ToolsView-Cq7Fuq3i.js"),__vite__mapDeps([19,1,2])));function qp(){return r.jsx("div",{className:"w-full h-full overflow-auto",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Tools..."}),children:r.jsx(Hp,{})})})}const Gp=te.lazy(()=>se(()=>import("./SettingsView-C39dk_yr.js"),__vite__mapDeps([20,1,2])));function Yp(){return r.jsx("div",{className:"w-full h-full overflow-auto",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Settings..."}),children:r.jsx(Gp,{})})})}function Kp(){const[t,e]=S.useState([]),[s,n]=S.useState("/"),[i,a]=S.useState(!1),c=async()=>{a(!0);try{const l=await Pe(`/api/files?path=${encodeURIComponent(s)}`);if(l.ok){const d=await l.json();e(d.files||[])}else e([{name:"documents",path:"/documents",type:"directory"},{name:"readme.md",path:"/readme.md",type:"file"},{name:"config.yaml",path:"/config.yaml",type:"file"}])}catch{e([{name:"documents",path:"/documents",type:"directory"},{name:"readme.md",path:"/readme.md",type:"file"},{name:"config.yaml",path:"/config.yaml",type:"file"}])}finally{a(!1)}};return S.useEffect(()=>{c()},[s]),r.jsxs("div",{className:"w-full h-full flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-[#27272a]/40",children:[r.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-[#71717a]",children:[r.jsx("span",{className:"text-[#6366f1]",children:"~"}),r.jsx(dl,{className:"w-3 h-3"}),r.jsx("span",{children:s})]}),r.jsx("button",{onClick:c,className:"p-1 text-[#3f3f46] hover:text-[#71717a]",children:r.jsx(on,{className:`w-3 h-3 ${i?"animate-spin":""}`})})]}),r.jsx("div",{className:"flex-1 overflow-auto",children:t.map(l=>r.jsxs("button",{onClick:()=>l.type==="directory"&&n(l.path),className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-[#27272a]/20 transition-colors",children:[l.type==="directory"?r.jsx(Tl,{className:"w-3.5 h-3.5 text-[#f59e0b]"}):r.jsx(rn,{className:"w-3.5 h-3.5 text-[#6366f1]"}),r.jsx("span",{className:"text-[12px] text-[#a1a1aa]",children:l.name})]},l.path))})]})}const Jp=te.lazy(()=>se(()=>import("./SettingsPanel-DnEvJUFe.js"),__vite__mapDeps([21,1,2,3,22,5,4,23,24,25])));function Xp(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Jp,{})})})}const Zp=te.lazy(()=>se(()=>import("./SecurityPanel-i1QMctV0.js"),__vite__mapDeps([26,1,2,22,5])));function Qp(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Zp,{})})})}const eg=te.lazy(()=>se(()=>import("./AuditPanel-B84Mp16G.js"),__vite__mapDeps([27,1,2,28,5])));function tg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(eg,{})})})}const Li={researcher:"#60a5fa",engineer:"#f87171",manager:"#a78bfa",ceo:"#fbbf24",general:"#9ca3af"};function sg(){const[t,e]=S.useState(null),[s,n]=S.useState({}),[i,a]=S.useState(null),[c,l]=S.useState({}),[d,p]=S.useState(!0),w=S.useCallback(async()=>{a(null);try{const[g,y]=await Promise.all([Pe("/api/specialists"),Pe("/api/models")]);if(!g.ok)throw new Error(`Specialists request failed: ${g.status}`);if(!y.ok)throw new Error(`Models request failed: ${y.status}`);const v=await g.json(),A=await y.json();e(v),n(A)}catch(g){a(g.message)}finally{p(!1)}},[]);S.useEffect(()=>{w()},[w]);const u=S.useMemo(()=>{const g=new Set;if(s&&typeof s=="object")for(const y of Object.keys(s)){const v=s[y];if(Array.isArray(v))for(const A of v)typeof A=="string"?g.add(A):A&&typeof A=="object"&&"id"in A&&typeof A.id=="string"&&g.add(A.id)}if(Array.isArray(t))for(const y of t)y!=null&&y.activeModel&&g.add(y.activeModel),y!=null&&y.defaultModel&&g.add(y.defaultModel);return Array.from(g).sort((y,v)=>y.localeCompare(v))},[s,t]),f=S.useCallback(async(g,y)=>{l(v=>({...v,[g]:"saving"}));try{const v=await Pe(`/api/specialists/${encodeURIComponent(g)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:y})});if(!v.ok){const C=await v.text().catch(()=>"");throw new Error(`PATCH failed (${v.status}): ${C||v.statusText}`)}const A=await v.json();e(C=>(C==null?void 0:C.map(M=>M.id===g?{...M,activeModel:A.activeModel??M.defaultModel,overridden:(A.activeModel??M.defaultModel)!==M.defaultModel}:M))??null),l(C=>({...C,[g]:"saved"})),setTimeout(()=>{l(C=>{if(C[g]!=="saved")return C;const M={...C};return delete M[g],M})},1500)}catch(v){l(A=>({...A,[g]:"error"})),a(`${g}: ${v.message}`)}},[]);return d&&!t?r.jsx("div",{className:"h-full w-full flex items-center justify-center text-xs text-[#52525b]",children:"Loading specialists…"}):r.jsxs("div",{className:"w-full h-full flex flex-col bg-[#0a0a0f] text-[#e4e4e7] text-sm",children:[r.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-[#27272a]/60",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(yr,{className:"w-4 h-4 text-[#6366f1]"}),r.jsx("h3",{className:"font-semibold",children:"Specialist Models"}),r.jsxs("span",{className:"text-[10px] text-[#52525b]",children:[(t==null?void 0:t.length)??0," sub-agents · ",u.length," models"]})]}),r.jsxs("button",{onClick:()=>{p(!0),w()},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:[r.jsx(on,{className:`w-3 h-3 ${d?"animate-spin":""}`}),"Refresh"]})]}),i&&r.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:[r.jsx(nn,{className:"w-3 h-3 mt-0.5 shrink-0"}),r.jsx("span",{className:"font-mono",children:i})]}),r.jsxs("div",{className:"flex-1 overflow-auto px-4 py-3 space-y-2",children:[(t==null?void 0:t.length)===0&&r.jsx("div",{className:"text-xs text-[#52525b] italic",children:"No specialists registered."}),t==null?void 0:t.map(g=>r.jsx(ng,{row:g,allModels:u,state:c[g.id]??"idle",onChange:y=>f(g.id,y),onReset:()=>f(g.id,null)},g.id))]}),r.jsxs("div",{className:"px-4 py-2 border-t border-[#27272a]/60 text-[10px] text-[#52525b]",children:["Overrides write to ",r.jsx("span",{className:"font-mono text-[#71717a]",children:"config.specialists.overrides"}),". Reset reverts a specialist to its code default."]})]})}function ng({row:t,allModels:e,state:s,onChange:n,onReset:i}){var c;const a=Li[t.role]??Li.general;return r.jsxs("div",{className:"rounded-lg border border-[#27272a]/60 bg-[#18181b]/70 hover:border-[#3f3f46]/80 transition-colors",children:[r.jsxs("div",{className:"px-3 py-2 flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-[180px]",children:[r.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:a},title:t.role}),r.jsxs("div",{className:"flex flex-col min-w-0",children:[r.jsx("div",{className:"text-sm font-medium truncate",children:t.name}),r.jsx("div",{className:"text-[10px] text-[#52525b] truncate",children:t.title})]})]}),r.jsxs("div",{className:"flex-1 flex items-center gap-2 min-w-0",children:[r.jsx("select",{value:t.activeModel,onChange:l=>n(l.target.value),disabled:s==="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(l=>r.jsx("option",{value:l,children:l},l))}),t.overridden&&r.jsxs("button",{onClick:i,disabled:s==="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:[r.jsx(qi,{className:"w-3 h-3"}),"Reset"]}),r.jsxs("div",{className:"w-5 h-5 flex items-center justify-center shrink-0",children:[s==="saving"&&r.jsx(on,{className:"w-3.5 h-3.5 animate-spin text-[#6366f1]"}),s==="saved"&&r.jsx(ml,{className:"w-3.5 h-3.5 text-[#10b981]"}),s==="error"&&r.jsx(nn,{className:"w-3.5 h-3.5 text-[#ef4444]"})]})]})]}),r.jsxs("div",{className:"px-3 pb-2 flex items-center gap-2 text-[10px] text-[#52525b]",children:[r.jsxs("span",{children:["id: ",r.jsx("span",{className:"font-mono text-[#71717a]",children:t.id})]}),r.jsx("span",{children:"•"}),r.jsxs("span",{children:["role: ",r.jsx("span",{className:"font-mono",style:{color:a},children:t.role})]}),((c=t.templateMatches)==null?void 0:c.length)>0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"•"}),r.jsxs("span",{className:"truncate",children:["templates: ",r.jsx("span",{className:"font-mono text-[#71717a]",children:t.templateMatches.join(", ")})]})]})]})]})}function rg(){const[t,e]=S.useState(null),[s,n]=S.useState(null),[i,a]=S.useState(null),[c,l]=S.useState(!1),[d,p]=S.useState(null),[w,u]=S.useState(null),f=S.useCallback(async()=>{p(null);try{const[A,C,M]=await Promise.all([Pe("/api/telemetry/consent").then(b=>b.ok?b.json():Promise.reject(new Error(`consent ${b.status}`))),Pe("/api/analytics/profile").then(b=>b.ok?b.json():null),Pe("/api/telemetry/status").then(b=>b.ok?b.json():null)]);e(A),n(C),M!=null&&M.remote&&a(M.remote)}catch(A){p(A.message)}},[]);S.useEffect(()=>{const A=setInterval(()=>{Pe("/api/telemetry/status").then(C=>C.ok?C.json():null).then(C=>{C!=null&&C.remote&&a(C.remote)}).catch(()=>{})},15e3);return()=>clearInterval(A)},[]),S.useEffect(()=>{f()},[f]);const g=S.useCallback(async A=>{l(!0),p(null);try{const C=await Pe("/api/telemetry/consent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!C.ok)throw new Error(`save failed: ${C.status}`);const M=await C.json();e(b=>b?{...b,...M,consentedAt:M.enabled?new Date().toISOString():void 0}:null),u(Date.now()),setTimeout(()=>u(null),2e3)}catch(C){p(C.message)}finally{l(!1)}},[]),y=!!(t!=null&&t.enabled),v=!!(t!=null&&t.crashReports);return r.jsxs("div",{className:"w-full h-full overflow-auto bg-[#0a0a0f] text-[#e4e4e7] text-sm p-4",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[y?r.jsx(ic,{className:"w-5 h-5 text-[#10b981]"}):r.jsx(pr,{className:"w-5 h-5 text-[#71717a]"}),r.jsx("h3",{className:"font-semibold text-base",children:"Privacy & Telemetry"}),r.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"}),r.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[w&&r.jsxs("span",{className:"text-[11px] text-[#10b981] flex items-center gap-1",children:[r.jsx(sl,{className:"w-3 h-3"})," Saved"]}),d&&r.jsxs("span",{className:"text-[11px] text-[#ef4444] flex items-center gap-1",children:[r.jsx(nl,{className:"w-3 h-3"})," ",d]}),r.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:[r.jsx(on,{className:"w-3 h-3"})," Refresh"]})]})]}),r.jsx("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/70",children:r.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:y,disabled:c,onChange:A=>g({enabled:A.target.checked,crashReports:v}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"font-medium",children:"Send anonymous usage stats"}),r.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)&&r.jsxs("div",{className:"text-[10px] text-[#71717a] mt-2",children:["Consented ",r.jsx("span",{className:"font-mono",children:new Date(t.consentedAt).toLocaleString()}),t.consentedVersion&&r.jsxs(r.Fragment,{children:[" on TITAN v",r.jsx("span",{className:"font-mono",children:t.consentedVersion})]})]})]})]})}),r.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:r.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:v,disabled:c||!y,onChange:A=>g({enabled:y,crashReports:A.target.checked}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:"font-medium",children:"Send crash reports"}),r.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. ",r.jsxs("span",{className:"text-[#fbbf24]",children:["Your $HOME path is replaced with the string ",r.jsx("span",{className:"font-mono",children:'"$HOME"'})," before sending."]})]})]})]})}),r.jsxs("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/40",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[r.jsx(nn,{className:"w-4 h-4 text-[#6366f1]"}),r.jsx("div",{className:"text-sm font-medium",children:"What would be sent right now"})]}),s?r.jsxs("dl",{className:"grid grid-cols-[160px_1fr] gap-y-1 text-xs",children:[r.jsx("dt",{className:"text-[#71717a]",children:"installId"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.installId.slice(0,32),"…"]}),r.jsx("dt",{className:"text-[#71717a]",children:"os / arch"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.os," / ",s.arch," (",s.osRelease,")"]}),r.jsx("dt",{className:"text-[#71717a]",children:"cpu"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.cpuModel," · ",s.cpuCores,"c"]}),r.jsx("dt",{className:"text-[#71717a]",children:"ram"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[(s.ramTotalMB/1024).toFixed(1)," GB"]}),r.jsx("dt",{className:"text-[#71717a]",children:"gpu"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.gpuVendor,"/",s.gpuName," · ",(s.gpuVramMB/1024).toFixed(1)," GB VRAM"]}),r.jsx("dt",{className:"text-[#71717a]",children:"disk"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.diskTotalGB," GB"]}),r.jsx("dt",{className:"text-[#71717a]",children:"version / node"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.version," · ",s.nodeVersion]}),r.jsx("dt",{className:"text-[#71717a]",children:"install method"}),r.jsx("dd",{className:"font-mono text-[#e4e4e7]",children:s.installMethod})]}):r.jsx("div",{className:"text-xs text-[#71717a]",children:"Loading profile preview…"})]}),r.jsxs("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/50",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[r.jsx(Gi,{className:"w-4 h-4 text-[#6366f1]"}),r.jsx("div",{className:"text-sm font-medium",children:"Delivery status"}),(i==null?void 0:i.lastSuccessAt)&&!i.lastError&&r.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)&&r.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)&&r.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?r.jsxs("dl",{className:"grid grid-cols-[160px_1fr] gap-y-1 text-xs",children:[r.jsx("dt",{className:"text-[#71717a]",children:"remote URL"}),r.jsx("dd",{className:"font-mono text-[#e4e4e7] break-all",children:i.remoteUrl||"—"}),r.jsx("dt",{className:"text-[#71717a]",children:"sent / failed"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[r.jsx("span",{className:"text-[#10b981]",children:i.sentCount})," / ",r.jsx("span",{className:i.failedCount>0?"text-[#ef4444]":"text-[#71717a]",children:i.failedCount}),i.lastEventType&&r.jsxs("span",{className:"text-[#71717a]",children:[" · last event: ",r.jsx("span",{className:"text-[#a1a1aa]",children:i.lastEventType})]})]}),r.jsx("dt",{className:"text-[#71717a]",children:"last attempt"}),r.jsxs("dd",{className:"font-mono text-[#e4e4e7] flex items-center gap-1",children:[r.jsx(as,{className:"w-3 h-3 text-[#71717a]"}),i.lastAttemptAt?new Date(i.lastAttemptAt).toLocaleString():"—"]}),r.jsx("dt",{className:"text-[#71717a]",children:"last success"}),r.jsx("dd",{className:"font-mono text-[#e4e4e7]",children:i.lastSuccessAt?new Date(i.lastSuccessAt).toLocaleString():"—"}),i.lastError&&r.jsxs(r.Fragment,{children:[r.jsx("dt",{className:"text-[#ef4444]",children:"last error"}),r.jsx("dd",{className:"font-mono text-[#fca5a5] break-all",children:i.lastError})]})]}):r.jsx("div",{className:"text-xs text-[#71717a]",children:"Checking collector reachability…"})]}),r.jsxs("div",{className:"mb-4 p-3 rounded-lg border border-[#27272a]/60 bg-[#0a0a0f]",children:[r.jsx("div",{className:"text-[10px] text-[#71717a] uppercase tracking-wider mb-1",children:"Collector"}),r.jsx("div",{className:"font-mono text-[11px] text-[#a1a1aa] break-all",children:(t==null?void 0:t.remoteUrl)||"—"})]}),r.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[r.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:[r.jsx(Xr,{className:"w-3 h-3"})," Read the full PRIVACY.md"]}),r.jsx("span",{className:"text-[#52525b]",children:"·"}),r.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:[r.jsx(Xr,{className:"w-3 h-3"})," See the collector source"]})]})]})}const ig=te.lazy(()=>se(()=>import("./AutopilotPanel-nTb1Dnru.js"),__vite__mapDeps([29,1,2,22,5])));function og(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(ig,{})})})}const ag=te.lazy(()=>se(()=>import("./WorkflowsPanel-qzNS0p0u.js"),__vite__mapDeps([30,1,2,22,5,3,9,14,25,10,15,31])));function lg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(ag,{})})})}const cg=te.lazy(()=>se(()=>import("./LearningPanel-BEgF_iND.js"),__vite__mapDeps([32,1,2,22,5,33,34])));function dg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(cg,{})})})}const ug=te.lazy(()=>se(()=>import("./SelfImprovePanel-DbybAZWp.js"),__vite__mapDeps([35,1,2,23,36,34,5,25,15])));function hg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(ug,{})})})}const fg=te.lazy(()=>se(()=>import("./PersonasPanel-DxrGW5C4.js"),__vite__mapDeps([37,1,2])));function pg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(fg,{})})})}const gg=te.lazy(()=>se(()=>import("./HomelabPanel-DhuXd3ZD.js"),__vite__mapDeps([38,1,2,22,5,39,40,13,23,11])));function mg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(gg,{})})})}const yg=te.lazy(()=>se(()=>import("./NvidiaPanel-NYt42w7L.js"),__vite__mapDeps([41,1,2,23,42,5])));function wg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(yg,{})})})}const bg=te.lazy(()=>se(()=>import("./FilesPanel-DATsiAqG.js"),__vite__mapDeps([43,1,2,5,44,15,24])));function xg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(bg,{})})})}const vg=te.lazy(()=>se(()=>import("./LogsPanel-Br1P8ST6.js"),__vite__mapDeps([45,1,2,5])));function _g(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(vg,{})})})}const kg=te.lazy(()=>se(()=>import("./TelemetryPanel-JZ90gJXC.js"),__vite__mapDeps([46,1,2,39,12,13,5])));function Eg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(kg,{})})})}const Sg=te.lazy(()=>se(()=>import("./SkillsPanel-DM4qBFDS.js"),__vite__mapDeps([47,1,2,22,5,15,24])));function jg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Sg,{})})})}const Ng=te.lazy(()=>se(()=>import("./McpPanel-ByvQ12J_.js"),__vite__mapDeps([48,1,2,49,15,5])));function Cg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Ng,{})})})}const Tg=te.lazy(()=>se(()=>import("./IntegrationsPanel-C_FswSRN.js"),__vite__mapDeps([50,1,2,49,23,42,5])));function Ag(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Tg,{})})})}const Rg=te.lazy(()=>se(()=>import("./ChannelsPanel-CD2kHhA5.js"),__vite__mapDeps([51,1,2,22,5,23,42])));function Lg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Rg,{})})})}const Ig=te.lazy(()=>se(()=>import("./MeshPanel-BjkcSOMz.js"),__vite__mapDeps([52,1,2,53,5])));function Dg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Ig,{})})})}const Mg=te.lazy(()=>se(()=>import("./DaemonPanel-CNUggBbL.js"),__vite__mapDeps([54,1,2,10,25,5])));function Og(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Mg,{})})})}const Pg=te.lazy(()=>se(()=>import("./MemoryWikiPanel-CR8btd66.js"),__vite__mapDeps([55,1,2,22,5,44])));function Ug(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Pg,{})})})}const Wg=te.lazy(()=>se(()=>import("./AutoresearchPanel-D46mX8VF.js"),__vite__mapDeps([56,1,2,25,10,36,34,5])));function Bg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Wg,{})})})}const Fg=te.lazy(()=>se(()=>import("./SelfProposalsPanel-DtcTUDDd.js"),__vite__mapDeps([57,1,2,22,5])));function $g(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Fg,{})})})}const zg=te.lazy(()=>se(()=>import("./OverviewPanel-q35zdMr6.js"),__vite__mapDeps([58,1,2,39,22,5,40])));function Vg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(zg,{})})})}const Hg=te.lazy(()=>se(()=>import("./SessionsPanel-B7QmOizR.js"),__vite__mapDeps([59,1,2,22,5,3,53,9,15])));function qg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Hg,{})})})}const Gg=te.lazy(()=>se(()=>import("./WatchView-CQBemwsm.js"),__vite__mapDeps([60,1,2,8])));function Yg(){return r.jsx("div",{className:"w-full h-full overflow-auto",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Gg,{})})})}const Kg=te.lazy(()=>se(()=>import("./BackupPanel-DGM1XXbG.js"),__vite__mapDeps([61,1,2,22,5,23])));function Jg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Kg,{})})})}const Xg=te.lazy(()=>se(()=>import("./TrainingPanel-CWnP4H2l.js"),__vite__mapDeps([62,1,2,22,5,24])));function Zg(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Xg,{})})})}const Qg=te.lazy(()=>se(()=>import("./RecipesPanel-CYRdBx5u.js"),__vite__mapDeps([63,1,2,22,5,25,15])));function em(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(Qg,{})})})}const tm=te.lazy(()=>se(()=>import("./VramPanel-CLd9Ggck.js"),__vite__mapDeps([64,1,2,22,5])));function sm(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(tm,{})})})}const nm=te.lazy(()=>se(()=>import("./TeamsPanel-Bf6GaUni.js"),__vite__mapDeps([65,1,2,22,5,15])));function rm(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(nm,{})})})}const im=te.lazy(()=>se(()=>import("./CronPanel-CsfQctFp.js"),__vite__mapDeps([66,1,2,22,5,31,15])));function om(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(im,{})})})}const am=te.lazy(()=>se(()=>import("./CheckpointsPanel-BrUTFPu_.js"),__vite__mapDeps([67,1,2,22,5,15])));function lm(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(am,{})})})}const cm=te.lazy(()=>se(()=>import("./OrganismPanel-PHvISvVn.js"),__vite__mapDeps([68,1,2,22,5,23])));function dm(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(cm,{})})})}const um=te.lazy(()=>se(()=>import("./FleetPanel-QYQKqx4W.js"),__vite__mapDeps([69,1,2,22,5])));function hm(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(um,{})})})}const fm=te.lazy(()=>se(()=>import("./BrowserPanel-Cn1tTN3y.js"),__vite__mapDeps([70,1,2,22,5])));function pm(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(fm,{})})})}const gm=te.lazy(()=>se(()=>import("./PaperclipPanel-BDpQki0d.js"),__vite__mapDeps([71,1,2,22,5,25,72])));function mm(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(gm,{})})})}const ym=te.lazy(()=>se(()=>import("./EvalPanel-DEX0a5-b.js"),__vite__mapDeps([73,1,2,22,5,25])));function wm(){return r.jsx("div",{className:"w-full h-full overflow-auto p-4",children:r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:r.jsx(ym,{})})})}function bm(){const[t,e]=S.useState([]),[s,n]=S.useState(!0),[i,a]=S.useState(null),c=async()=>{try{const l=await fetch("/api/agents");if(!l.ok)throw new Error(`HTTP ${l.status}`);const d=await l.json();e(Array.isArray(d)?d:d.agents||[]),a(null)}catch(l){a(l.message)}finally{n(!1)}};return S.useEffect(()=>{c();const l=setInterval(c,1e4);return()=>clearInterval(l)},[]),s?r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(Fi,{className:"w-4 h-4 text-[#6366f1] animate-spin"})}):i?r.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:r.jsxs("div",{className:"text-center",children:[r.jsx(nn,{className:"w-4 h-4 text-red-400 mx-auto mb-1"}),r.jsx("span",{className:"text-[10px] text-red-400",children:i})]})}):t.length===0?r.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:r.jsx("span",{className:"text-[10px] text-[#52525b]",children:"No active agents"})}):r.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:r.jsx("div",{className:"space-y-2",children:t.map(l=>r.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[r.jsx(Oi,{className:`w-3.5 h-3.5 ${l.status==="busy"?"text-[#f59e0b]":l.status==="error"?"text-red-400":"text-[#6366f1]"}`}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("div",{className:"text-[11px] text-[#a1a1aa] truncate",children:l.name}),r.jsxs("div",{className:"text-[10px] text-[#52525b] truncate",children:[l.role,l.model?` · ${l.model}`:""]})]}),r.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${l.status==="busy"?"bg-[#f59e0b]/10 text-[#f59e0b]":l.status==="error"?"bg-red-400/10 text-red-400":"bg-[#6366f1]/10 text-[#818cf8]"}`,children:l.status})]},l.id))})})}function xm(){const[t,e]=S.useState(null),[s,n]=S.useState(!0),i=async()=>{try{const[c,l]=await Promise.allSettled([fetch("/api/health").then(w=>w.ok?w.json():null),fetch("/ollama/api/tags").then(w=>w.ok)]),d=c.status==="fulfilled"&&c.value,p=l.status==="fulfilled"&&l.value;e({gateway:d,ollama:p,version:(d==null?void 0:d.version)||"unknown",uptime:(d==null?void 0:d.uptime)||0})}catch{e({gateway:!1,ollama:!1,version:"unknown",uptime:0})}finally{n(!1)}};if(S.useEffect(()=>{i();const c=setInterval(i,3e4);return()=>clearInterval(c)},[]),s)return r.jsx("div",{className:"w-full h-full flex items-center justify-center",children:r.jsx(Fi,{className:"w-4 h-4 text-[#6366f1] animate-spin"})});const a=c=>{const l=Math.floor(c/3600),d=Math.floor(c%3600/60);return`${l}h ${d}m`};return r.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:r.jsxs("div",{className:"space-y-3",children:[r.jsxs("div",{className:"flex items-center justify-between px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[t!=null&&t.gateway?r.jsx(rl,{className:"w-3.5 h-3.5 text-emerald-400"}):r.jsx(dc,{className:"w-3.5 h-3.5 text-red-400"}),r.jsx("span",{className:"text-[11px] text-[#a1a1aa]",children:"TITAN Gateway"})]}),r.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"})]}),r.jsxs("div",{className:"flex items-center justify-between px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(gt,{className:`w-3.5 h-3.5 ${t!=null&&t.ollama?"text-emerald-400":"text-red-400"}`}),r.jsx("span",{className:"text-[11px] text-[#a1a1aa]",children:"Ollama"})]}),r.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"})]}),r.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[r.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[r.jsx("div",{className:"text-[9px] text-[#52525b] uppercase tracking-wider",children:"Version"}),r.jsx("div",{className:"text-[11px] text-[#a1a1aa] font-mono mt-0.5",children:t==null?void 0:t.version})]}),r.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[r.jsx("div",{className:"text-[9px] text-[#52525b] uppercase tracking-wider",children:"Uptime"}),r.jsx("div",{className:"text-[11px] text-[#a1a1aa] font-mono mt-0.5",children:a((t==null?void 0:t.uptime)||0)})]})]})]})})}function Rs({label:t,value:e,icon:s,color:n}){const i=Math.max(0,Math.min(100,Math.round(e)));return r.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[r.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[s,r.jsx("span",{className:"text-[10px] text-[#52525b] uppercase tracking-wider",children:t})]}),r.jsxs("span",{className:"text-[11px] text-[#a1a1aa] font-mono",children:[i,"%"]})]}),r.jsx("div",{className:"h-1.5 rounded-full bg-[#27272a] overflow-hidden",children:r.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${i}%`,backgroundColor:n}})})]})}function vm(){const[t,e]=S.useState({cpu:0,memory:0,disk:0,load:0});return S.useEffect(()=>{const s=setInterval(()=>{e({cpu:Math.random()*60+10,memory:Math.random()*50+30,disk:Math.random()*40+20,load:Math.random()*30+5})},3e3);return e({cpu:Math.random()*60+10,memory:Math.random()*50+30,disk:Math.random()*40+20,load:Math.random()*30+5}),()=>clearInterval(s)},[]),r.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:r.jsxs("div",{className:"space-y-2",children:[r.jsx(Rs,{label:"CPU",value:t.cpu,icon:r.jsx(fr,{className:"w-3 h-3 text-[#6366f1]"}),color:"#6366f1"}),r.jsx(Rs,{label:"Memory",value:t.memory,icon:r.jsx(il,{className:"w-3 h-3 text-[#a78bfa]"}),color:"#a78bfa"}),r.jsx(Rs,{label:"Disk",value:t.disk,icon:r.jsx(ol,{className:"w-3 h-3 text-[#10b981]"}),color:"#10b981"}),r.jsx(Rs,{label:"Load",value:t.load,icon:r.jsx(gt,{className:"w-3 h-3 text-[#f59e0b]"}),color:"#f59e0b"})]})})}const _m=[{label:"Nav",source:"system:nav",w:3,h:4,icon:r.jsx(vl,{className:"w-3.5 h-3.5"})},{label:"Agents",source:"system:agents",w:3,h:4,icon:r.jsx(Oi,{className:"w-3.5 h-3.5"})},{label:"Health",source:"system:health",w:3,h:3,icon:r.jsx(gt,{className:"w-3.5 h-3.5"})},{label:"Stats",source:"system:stats",w:3,h:4,icon:r.jsx(Rl,{className:"w-3.5 h-3.5"})},{label:"Chat",source:"system:chat",w:4,h:5,icon:r.jsx($i,{className:"w-3.5 h-3.5"})},{label:"Files",source:"system:files",w:4,h:6,icon:r.jsx(rn,{className:"w-3.5 h-3.5"})},{label:"Skills",source:"system:tools",w:5,h:4,icon:r.jsx(hr,{className:"w-3.5 h-3.5"})},{label:"Soma",source:"system:soma",w:6,h:6,icon:r.jsx(Dl,{className:"w-3.5 h-3.5"})},{label:"Intel",source:"system:intelligence",w:6,h:5,icon:r.jsx(mt,{className:"w-3.5 h-3.5"})},{label:"Infra",source:"system:infra",w:6,h:4,icon:r.jsx(gr,{className:"w-3.5 h-3.5"})},{label:"Tools",source:"system:tools",w:5,h:4,icon:r.jsx(wr,{className:"w-3.5 h-3.5"})},{label:"Settings",source:"system:settings",w:4,h:6,icon:r.jsx(mr,{className:"w-3.5 h-3.5"})},{label:"Daemon",source:"system:daemon",w:5,h:5,icon:r.jsx(gt,{className:"w-3.5 h-3.5"})},{label:"Wiki",source:"system:memory-wiki",w:5,h:5,icon:r.jsx(os,{className:"w-3.5 h-3.5"})},{label:"Research",source:"system:autoresearch",w:5,h:5,icon:r.jsx(Ui,{className:"w-3.5 h-3.5"})},{label:"Proposals",source:"system:self-proposals",w:5,h:5,icon:r.jsx(Wi,{className:"w-3.5 h-3.5"})},{label:"Overview",source:"system:overview",w:5,h:4,icon:r.jsx(Pi,{className:"w-3.5 h-3.5"})},{label:"Sessions",source:"system:sessions",w:5,h:4,icon:r.jsx(as,{className:"w-3.5 h-3.5"})},{label:"Watch",source:"system:watch",w:6,h:5,icon:r.jsx(gt,{className:"w-3.5 h-3.5"})},{label:"Backup",source:"system:backup",w:5,h:5,icon:r.jsx(Mi,{className:"w-3.5 h-3.5"})},{label:"Training",source:"system:training",w:5,h:5,icon:r.jsx(mt,{className:"w-3.5 h-3.5"})},{label:"Recipes",source:"system:recipes",w:5,h:5,icon:r.jsx(os,{className:"w-3.5 h-3.5"})},{label:"VRAM",source:"system:vram",w:5,h:5,icon:r.jsx(fr,{className:"w-3.5 h-3.5"})},{label:"Teams",source:"system:teams",w:5,h:5,icon:r.jsx(yr,{className:"w-3.5 h-3.5"})},{label:"Cron",source:"system:cron",w:5,h:5,icon:r.jsx(as,{className:"w-3.5 h-3.5"})},{label:"Checkpoints",source:"system:checkpoints",w:5,h:5,icon:r.jsx(an,{className:"w-3.5 h-3.5"})},{label:"Organism",source:"system:organism",w:5,h:5,icon:r.jsx(pr,{className:"w-3.5 h-3.5"})},{label:"Fleet",source:"system:fleet",w:5,h:5,icon:r.jsx(Hi,{className:"w-3.5 h-3.5"})},{label:"Browser",source:"system:browser",w:5,h:5,icon:r.jsx(Ii,{className:"w-3.5 h-3.5"})},{label:"Paperclip",source:"system:paperclip",w:5,h:5,icon:r.jsx(Vi,{className:"w-3.5 h-3.5"})},{label:"Eval",source:"system:eval",w:5,h:5,icon:r.jsx(Ki,{className:"w-3.5 h-3.5"})}];function km(){const t=(e,s,n)=>{window.dispatchEvent(new CustomEvent("titan:widget:add",{detail:{source:e,w:s,h:n}}))};return r.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:r.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:_m.map(e=>r.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:[r.jsx("span",{className:"text-[#6366f1]",children:e.icon}),r.jsx("span",{className:"text-[10px] font-medium",children:e.label})]},e.source))})})}class Em extends te.Component{componentDidCatch(e){this.props.onError(e.message)}render(){return this.props.children}}function Sm({name:t,children:e}){const[s,n]=te.useState(null);return s?r.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:r.jsxs("span",{className:"text-xs text-red-400",children:[t,": ",s]})}):r.jsx(Em,{onError:n,children:e})}const jm=te.lazy(()=>se(()=>import("./legacy-DOO7F5cq.js"),__vite__mapDeps([74,1,2])).then(t=>({default:t.Responsive}))),Nm={"system:nav":Ba,"system:chat":za,"system:cmd":Ya,"system:soma":Ka,"system:command-post":Pp,"system:intelligence":Wp,"system:memory-graph":Fp,"system:voice":$p,"system:infra":Vp,"system:tools":qp,"system:settings":Yp,"system:files":Kp,"system:settings-general":Xp,"system:settings-security":Qp,"system:settings-audit":tg,"system:settings-specialists":sg,"system:settings-privacy":rg,"system:intelligence-autopilot":og,"system:intelligence-workflows":lg,"system:intelligence-learning":dg,"system:intelligence-self-improve":hg,"system:intelligence-personas":pg,"system:infra-homelab":mg,"system:infra-gpu":wg,"system:infra-files":xg,"system:infra-logs":_g,"system:infra-telemetry":Eg,"system:tools-skills":jg,"system:tools-mcp":Cg,"system:tools-integrations":Ag,"system:tools-channels":Lg,"system:tools-mesh":Dg,"system:agents":bm,"system:health":xm,"system:stats":vm,"system:quick-links":km,"system:daemon":Og,"system:memory-wiki":Ug,"system:autoresearch":Bg,"system:self-proposals":$g,"system:overview":Vg,"system:sessions":qg,"system:watch":Yg,"system:backup":Jg,"system:training":Zg,"system:recipes":em,"system:vram":sm,"system:teams":rm,"system:cron":om,"system:checkpoints":lm,"system:organism":dm,"system:fleet":hm,"system:browser":pm,"system:paperclip":mm,"system:eval":wm},Cm={lg:12,md:10,sm:6,xs:4,xxs:2},Tm=60,Am={lg:1200,md:996,sm:768,xs:480,xxs:0},Rm=[12,12],Lm=["se","sw","ne","nw","e","w","n","s"],Ja=te.forwardRef(({widget:t,space:e,onRemove:s,style:n,className:i,onMouseDown:a,onMouseUp:c,onTouchStart:l,onTouchEnd:d,children:p},w)=>{const u=S.useCallback(()=>s(t.id),[t.id,s]);return r.jsxs("div",{ref:w,style:n,className:i,onMouseDown:a,onMouseUp:c,onTouchStart:l,onTouchEnd:d,children:[r.jsx(Mm,{widget:t,space:e,onRemove:u}),p]})});Ja.displayName="MemoWidgetItem";const Im=te.memo(Ja);function Dm({widget:t,space:e,onRemove:s}){const n=S.useRef(null),i=S.useRef(null),a=S.useRef(e),[c,l]=S.useState(null),[d,p]=S.useState(!0);if(S.useEffect(()=>{a.current=e},[e]),S.useEffect(()=>{if(t.format==="system"||!n.current)return;if(!t.source||t.source.trim()===""){l("Empty widget — no source code"),p(!1);return}p(!0),l(null),i.current=new Wa(n.current,{onLog:u=>console.log(`[Widget ${t.id}]`,u)}),i.current.setMessageHandler(u=>{var g,y,v,A;const f=a.current;if(u.type==="canvas"&&((g=u.payload)==null?void 0:g.action)==="createWidget"){const C=u.payload.def;if(!C)return{ok:!1,error:"createWidget requires a `def` object"};const M=Number.isFinite(C.w)?C.w:4,b=Number.isFinite(C.h)?C.h:4,x=Number.isFinite(C.x)&&Number.isFinite(C.y)?{x:C.x,y:C.y}:Ps(f.widgets||[],M,b);try{const E=_e.addWidget(f.id,{name:C.name||"Agent Widget",format:C.format||"react",source:C.source||"",x:x.x,y:x.y,w:M,h:b});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0,widgetId:E.id}}catch(E){return{ok:!1,error:E.message}}}if(u.type==="canvas"&&((y=u.payload)==null?void 0:y.action)==="updateWidget"){const{id:C,patch:M}=u.payload;return C?(_e.updateWidget(f.id,C,M||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0,id:C}):{ok:!1,error:"updateWidget requires an `id`"}}if(u.type==="canvas"&&((v=u.payload)==null?void 0:v.action)==="listWidgets")return{ok:!0,widgets:f.widgets||[]};if(u.type==="canvas"&&((A=u.payload)==null?void 0:A.action)==="removeWidget"){const C=u.payload.id;return C?(_e.removeWidget(f.id,C),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 w=setTimeout(()=>{p(!1),l("Sandbox timeout: widget took longer than 30s to render. Babel (~2MB) or React may be slow to load from unpkg.com. Check network tab in DevTools (F12).")},3e4);return i.current.render(t.format,t.source).then(()=>{clearTimeout(w),p(!1)}).catch(u=>{clearTimeout(w),p(!1),l(String(u))}),()=>{var u;clearTimeout(w),(u=i.current)==null||u.destroy()}},[t.format,t.source,t.id]),t.format==="system"){const w=Nm[t.source];return w?r.jsxs("div",{className:"w-full h-full rounded-xl bg-[#18181b]/90 border border-[#27272a]/60 overflow-hidden flex flex-col group hover:border-[#6366f1]/30 transition-colors shadow-lg shadow-black/20",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-[#27272a]/40 panel-drag-handle cursor-move",children:[r.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-[#6366f1]/70",children:t.name}),r.jsx("button",{onClick:s,className:"opacity-0 group-hover:opacity-100 text-[#3f3f46] hover:text-red-400 text-xs px-1 transition-opacity",children:"×"})]}),r.jsx("div",{className:"flex-1 overflow-auto relative",children:r.jsx(Sm,{name:t.name,children:r.jsx(w,{space:e,widget:t,onRemove:s})})})]}):r.jsxs("div",{className:"w-full h-full flex items-center justify-center text-xs text-red-400",children:["Unknown system widget: ",t.source]})}return r.jsxs("div",{className:"w-full h-full rounded-xl bg-[#18181b]/90 border border-[#27272a]/60 overflow-hidden flex flex-col",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-[#27272a]/40 panel-drag-handle cursor-move",children:[r.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-[#6366f1]/70",children:t.name}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("button",{onClick:w=>{w.stopPropagation(),window.dispatchEvent(new CustomEvent("titan:widget:edit",{detail:{spaceId:e.id,widgetId:t.id}}))},onMouseDown:w=>w.stopPropagation(),className:"text-[#52525b] hover:text-[#a5b4fc] px-1",title:"Edit widget",children:r.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"m18 2 4 4-14 14H4v-4L18 2z"})})}),r.jsx("button",{onClick:s,className:"text-[#3f3f46] hover:text-red-400 text-xs px-1",children:"×"})]})]}),r.jsx("div",{className:"flex-1 relative",children:c?r.jsx("div",{className:"p-3 text-xs text-red-400 font-mono whitespace-pre-wrap",children:c}):r.jsxs(r.Fragment,{children:[r.jsx("iframe",{ref:n,className:"w-full h-full border-0",sandbox:"allow-scripts",title:t.name}),d&&r.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-[#0a0a0f]/80 text-xs text-[#52525b]",children:r.jsx("span",{className:"animate-pulse",children:"Loading widget…"})})]})})]})}const Mm=te.memo(Dm);function Om({children:t,position:e}){const s={"bottom-left":"left-4 bottom-4","bottom-right":"right-4 bottom-4","top-left":"left-4 top-4","top-right":"right-4 top-4"}[e];return r.jsx("div",{className:`fixed ${s} z-50`,children:t})}function Pm(){const{spaceId:t}=al(),e=ll(),[s,n]=S.useState(null),[i]=S.useState(!0),[a,c]=S.useState(!1),[l,d]=S.useState(null),[p,w]=S.useState(!1),[u,f]=S.useState(!1),[g,y]=S.useState(!1),[v,A]=S.useState(1200),C=S.useRef(null),M=S.useRef(null),{info:b,triggerUpdate:x}=Rf(),[E,j]=S.useState(!1);S.useEffect(()=>{const B=t||"home",H=_e.get(B);H?n(H):e("/space/home",{replace:!0})},[t,e]),S.useEffect(()=>{const B=()=>{const ge=M.current;if(!ge)return null;const fe=new ResizeObserver(be=>{for(const ce of be)A(ce.contentRect.width)});return fe.observe(ge),A(ge.getBoundingClientRect().width||1200),fe};let H=B();const $=setInterval(()=>{H||(H=B()),H&&clearInterval($)},200);return()=>{H==null||H.disconnect(),clearInterval($)}},[s==null?void 0:s.id]),S.useEffect(()=>{const B=H=>{(H.metaKey||H.ctrlKey)&&H.key==="k"&&(H.preventDefault(),f($=>!$)),(H.metaKey||H.ctrlKey)&&H.key==="j"&&(H.preventDefault(),window.dispatchEvent(new CustomEvent("titan:chat:toggle")))};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[]),Lf([{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 k=S.useCallback(()=>{},[]),R=S.useRef(null),O=S.useRef(null),N=S.useCallback(B=>{s&&(O.current=B,R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{const H=O.current;!H||!s||(_e.updateLayout(s.id,H.map($=>({i:$.i,x:$.x,y:$.y,w:$.w,h:$.h}))),O.current=null,R.current=null)},50))},[s]),L=S.useCallback(B=>{var ge;if(!s)return;const H=(ge=s.widgets)==null?void 0:ge.find(fe=>fe.id===B);Sn("canvas_panel_removed",{widgetId:B,format:H==null?void 0:H.format,source:H==null?void 0:H.source}),_e.removeWidget(s.id,B);const $=Array.isArray(s.widgets)?s.widgets:[];n({...s,widgets:$.filter(fe=>fe.id!==B)})},[s]),W=S.useCallback(B=>{if(!s)return;const H=_e.addWidget(s.id,B),$=Array.isArray(s.widgets)?s.widgets:[];return n({...s,widgets:[...$,H]}),Sn(B.format==="system"?"canvas_system_panel_created":"canvas_panel_created",{source:B.source,name:B.name,format:B.format}),H},[s]),F=S.useCallback((B,H)=>{if(!s||!Array.isArray(s.widgets)||s.widgets.length===0)return{x:0,y:0};const $=12,ge=new Set;for(const fe of s.widgets)for(let be=0;be<fe.w;be++)for(let ce=0;ce<fe.h;ce++)ge.add(`${fe.x+be},${fe.y+ce}`);for(let fe=0;fe<200;fe++)for(let be=0;be<=$-B;be++){let ce=!0;for(let ee=0;ee<B;ee++){for(let Ee=0;Ee<H;Ee++)if(ge.has(`${be+ee},${fe+Ee}`)){ce=!1;break}if(!ce)break}if(ce)return{x:be,y:fe}}return{x:0,y:0}},[s]),V=S.useCallback((B,H,$=4,ge=4)=>{const fe=F($,ge);W({name:H,format:"system",source:B,x:fe.x,y:fe.y,w:$,h:ge})},[W,F]);S.useEffect(()=>{const B=H=>{const $=H.detail;if(console.log("[TitanCanvas] titan:space:refresh received:",$),!!s&&($==null?void 0:$.spaceId)===s.id){const ge=_e.get(s.id);ge&&(console.log("[TitanCanvas] Refreshing space, widget count:",ge.widgets.length),n(ge))}};return window.addEventListener("titan:space:refresh",B),()=>window.removeEventListener("titan:space:refresh",B)},[s]),S.useEffect(()=>{const B=H=>{const $=H.detail;if(s&&$!=null&&$.source){const ge=$.source.replace("system:","").replace(/-/g," ");V($.source,ge,$.w||4,$.h||4)}};return window.addEventListener("titan:widget:add",B),()=>window.removeEventListener("titan:widget:add",B)},[s,V]),S.useEffect(()=>{const B=H=>{const $=H.detail;s&&($==null?void 0:$.spaceId)===s.id&&typeof($==null?void 0:$.widgetId)=="string"&&d($.widgetId)};return window.addEventListener("titan:widget:edit",B),()=>window.removeEventListener("titan:widget:edit",B)},[s]),S.useEffect(()=>s?_e.observe(s.id,H=>{console.log("[TitanCanvas] CRDT observer fired, widgets:",H.length),n($=>$&&{...$,widgets:H})}):void 0,[s==null?void 0:s.id]);const G=S.useMemo(()=>{const B=s==null?void 0:s.widgets;return Array.isArray(B)?B.filter(Boolean):[]},[s]),Z=S.useMemo(()=>G.map((B,H)=>({i:B.id,x:Number.isFinite(B.x)?B.x:H%3*4,y:Number.isFinite(B.y)?B.y:Math.floor(H/3)*4,w:Number.isFinite(B.w)?B.w:4,h:Number.isFinite(B.h)?B.h:4,minW:2,minH:2,maxW:12,maxH:40})),[G]);return s?r.jsxs("div",{ref:C,className:"h-screen w-screen bg-[#0a0a0f] relative overflow-auto",children:[r.jsx("style",{children:`
1018
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle {
1019
+ background: none;
1020
+ padding: 0;
1021
+ opacity: 0.35;
1022
+ z-index: 10;
1023
+ transition: opacity 120ms ease, background-color 120ms ease;
1024
+ }
1025
+ .titan-canvas-grid .react-grid-item:hover > .react-resizable-handle { opacity: 0.85; }
1026
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle:hover,
1027
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle:active { opacity: 1; }
1028
+ /* Corner handles: 22x22 with a ring-coloured chevron */
1029
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-se,
1030
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw,
1031
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne,
1032
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw {
1033
+ width: 22px;
1034
+ height: 22px;
1035
+ background-image: none;
1036
+ transform: none;
1037
+ }
1038
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-se::after,
1039
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw::after,
1040
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne::after,
1041
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw::after {
1042
+ content: "";
1043
+ position: absolute;
1044
+ width: 12px; height: 12px;
1045
+ border: 2px solid #6366f1;
1046
+ border-radius: 3px;
1047
+ }
1048
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-se::after { right: 3px; bottom: 3px; border-top: none; border-left: none; }
1049
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-sw::after { left: 3px; bottom: 3px; border-top: none; border-right: none; }
1050
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-ne::after { right: 3px; top: 3px; border-bottom: none; border-left: none; }
1051
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-nw::after { left: 3px; top: 3px; border-bottom: none; border-right: none; }
1052
+ /* Edge handles: full-edge strips with a centre grip */
1053
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-e,
1054
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-w {
1055
+ top: 8px; bottom: 8px; height: auto; margin-top: 0;
1056
+ width: 8px; background-image: none; transform: none;
1057
+ }
1058
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-n,
1059
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-s {
1060
+ left: 8px; right: 8px; width: auto; margin-left: 0;
1061
+ height: 8px; background-image: none; transform: none;
1062
+ }
1063
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after,
1064
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after,
1065
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after,
1066
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after {
1067
+ content: ""; position: absolute; background: #6366f1; border-radius: 2px;
1068
+ }
1069
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after,
1070
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after {
1071
+ top: 50%; transform: translateY(-50%);
1072
+ width: 3px; height: 32px;
1073
+ }
1074
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-e::after { right: 2px; }
1075
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-w::after { left: 2px; }
1076
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after,
1077
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after {
1078
+ left: 50%; transform: translateX(-50%);
1079
+ height: 3px; width: 32px;
1080
+ }
1081
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-n::after { top: 2px; }
1082
+ .titan-canvas-grid .react-grid-item > .react-resizable-handle-s::after { bottom: 2px; }
1083
+ /* Allow resizing and dragging freely — placeholder turns accent blue */
1084
+ .titan-canvas-grid .react-grid-placeholder {
1085
+ background: rgba(99, 102, 241, 0.14) !important;
1086
+ border: 1px dashed rgba(99, 102, 241, 0.55) !important;
1087
+ border-radius: 12px;
1088
+ opacity: 1 !important;
1089
+ }
1090
+ `}),r.jsx("div",{className:"fixed inset-0 opacity-[0.03] pointer-events-none",style:{backgroundImage:"radial-gradient(circle at 1px 1px, rgba(99,102,241,0.5) 1px, transparent 0)",backgroundSize:"24px 24px"}}),r.jsxs("div",{className:"absolute top-0 left-0 right-0 h-10 flex items-center justify-between px-4 z-40 border-b border-[#27272a]/30 bg-[#0a0a0f]/80 backdrop-blur-sm",children:[r.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[r.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",style:{color:s.color||"#6366f1"},children:s.name}),r.jsxs("button",{onClick:()=>c(!0),className:"flex items-center gap-1.5 text-[10px] text-[#52525b] hover:text-[#a5b4fc] truncate max-w-md transition-colors",title:"Edit agent instructions for this space",children:[r.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:r.jsx("path",{d:"m18 2 4 4-14 14H4v-4L18 2z"})}),s.agentInstructions?r.jsx("span",{className:"truncate",children:s.agentInstructions}):r.jsx("span",{className:"italic",children:"add agent instructions"})]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs("span",{className:"text-[10px] text-[#52525b]",children:[G.length," panel",G.length!==1?"s":""]}),r.jsx("button",{onClick:()=>V("system:nav","Nav",3,4),className:"text-[10px] px-2 py-1 rounded-md bg-[#6366f1]/5 border border-[#6366f1]/10 text-[#818cf8]/70 hover:bg-[#6366f1]/10 transition-colors",title:"Add Navigation",children:"Nav"}),r.jsx("button",{onClick:()=>V("system:agents","Agents",3,4),className:"text-[10px] px-2 py-1 rounded-md bg-[#6366f1]/5 border border-[#6366f1]/10 text-[#818cf8]/70 hover:bg-[#6366f1]/10 transition-colors",title:"Add Agents",children:"Agents"}),r.jsx("button",{onClick:()=>V("system:health","Health",3,3),className:"text-[10px] px-2 py-1 rounded-md bg-[#6366f1]/5 border border-[#6366f1]/10 text-[#818cf8]/70 hover:bg-[#6366f1]/10 transition-colors",title:"Add Health",children:"Health"}),r.jsx("button",{onClick:()=>V("system:stats","Stats",3,4),className:"text-[10px] px-2 py-1 rounded-md bg-[#6366f1]/5 border border-[#6366f1]/10 text-[#818cf8]/70 hover:bg-[#6366f1]/10 transition-colors",title:"Add Stats",children:"Stats"}),r.jsx("button",{onClick:()=>V("system:quick-links","Quick Links",3,4),className:"text-[10px] px-2 py-1 rounded-md bg-[#6366f1]/5 border border-[#6366f1]/10 text-[#818cf8]/70 hover:bg-[#6366f1]/10 transition-colors",title:"Add Quick Links",children:"Links"}),r.jsx("button",{onClick:()=>V("system:chat","Chat",4,5),className:"text-[10px] px-2 py-1 rounded-md bg-[#6366f1]/5 border border-[#6366f1]/10 text-[#818cf8]/70 hover:bg-[#6366f1]/10 transition-colors",title:"Add Chat",children:"Chat"}),G.length>0&&r.jsx("button",{onClick:async()=>{Sn("canvas_clear_all",{panelCount:G.length}),s&&(await _e.clearSpace(s.id),n({...s,widgets:[]}))},className:"text-[10px] px-2 py-1 rounded-md bg-[#ef4444]/5 border border-[#ef4444]/10 text-[#ef4444]/70 hover:bg-[#ef4444]/10 transition-colors",children:"Clear"}),r.jsx("button",{disabled:E,className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${b!=null&&b.isNewer?"bg-[#f59e0b]/10 border-[#f59e0b]/30 text-[#f59e0b] hover:bg-[#f59e0b]/20 cursor-pointer":"bg-[#18181b] border-[#27272a] text-[#52525b]"}`,title:b!=null&&b.isNewer?`Update available: ${b.current} → ${b.latest}`:`TITAN ${(b==null?void 0:b.current)||""}`,onClick:async()=>{if(!(b!=null&&b.isNewer)||E||!confirm(`Update TITAN from ${b.current} → ${b.latest}?
1091
+
1092
+ Your data in ~/.titan/ will be preserved. The gateway will restart after the update.`))return;j(!0);const B=await x(!0);j(!1),B.ok?alert("Update initiated. The gateway will restart shortly. Please refresh the page in 10-15 seconds."):alert(`Update failed: ${B.error||"Unknown error"}`)},children:E?"…":b!=null&&b.isNewer?`↑ ${b.latest}`:`v${(b==null?void 0:b.current)||""}`}),r.jsxs("button",{onClick:()=>w(!0),className:"text-[10px] px-2 py-1 rounded-md bg-[#18181b] border border-[#27272a] text-[#a78bfa] hover:bg-[#a78bfa]/10 transition-colors flex items-center gap-1.5",title:"Widget gallery",children:[r.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M12 3l1.9 5.8L20 10l-5 3.6 1.5 6L12 16l-4.5 3.6L9 13.6 4 10l6.1-1.2L12 3z"})}),"Gallery"]}),r.jsx("button",{onClick:()=>f(!0),className:"text-[10px] px-2 py-1 rounded-md bg-[#18181b] border border-[#27272a] text-[#52525b] hover:text-[#a1a1aa] transition-colors",children:"⌘K"}),r.jsx("button",{onClick:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle")),className:"text-[10px] px-2 py-1 rounded-md bg-[#18181b] border border-[#27272a] text-[#52525b] hover:text-[#a1a1aa] transition-colors",children:"⌘J"})]})]}),r.jsx("div",{ref:M,className:"relative pt-10 min-h-[5000px]",children:G.length===0?r.jsx(Um,{space:s,onAddWidget:V,onOpenChat:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle",{detail:{open:!0}}))}):r.jsx(S.Suspense,{fallback:r.jsx("div",{className:"text-[#52525b] text-sm",children:"Loading grid..."}),children:r.jsx(jm,{className:"layout titan-canvas-grid",width:v,layouts:{lg:Z},breakpoints:Am,cols:Cm,rowHeight:Tm,margin:Rm,containerPadding:[12,12],isDraggable:!0,isResizable:!0,draggableHandle:".panel-drag-handle",resizeHandles:Lm,compactType:null,preventCollision:!1,allowOverlap:!0,useCSSTransforms:!0,onLayoutChange:k,onDragStop:B=>{N(B)},onResizeStop:B=>{N(B)},children:G.map(B=>r.jsx(Im,{widget:B,space:s,onRemove:L},B.id))})})}),r.jsx(Om,{position:"bottom-left",children:r.jsx(Ba,{currentSpaceId:s.id,onSpaceSelect:B=>e(`/space/${B}`)})}),r.jsx(vp,{space:s,defaultExpanded:i}),r.jsx(kp,{space:s,open:a,onClose:()=>c(!1),onSaved:B=>{n(H=>H&&{...H,agentInstructions:B||void 0})}}),l&&(()=>{const B=G.find(H=>H.id===l);return!B||B.format==="system"?(d(null),null):r.jsx(jp,{widget:B,spaceId:s.id,open:!0,onClose:()=>d(null)})})(),r.jsx(Ap,{open:p,onClose:()=>w(!1)}),r.jsx(Mp,{}),u&&r.jsx(Ya,{currentSpaceId:s.id,onSpaceSelect:B=>{e(`/space/${B}`),f(!1)},onAction:B=>{B.type==="widget"&&V(B.source,B.name,B.w,B.h),f(!1)},onClose:()=>f(!1)}),r.jsx(Df,{open:g,onClose:()=>y(!1)})]}):r.jsx("div",{className:"h-screen w-screen bg-[#0a0a0f] flex items-center justify-center",children:r.jsx("div",{className:"text-[#52525b] text-sm",children:"Loading space..."})})}function Um({space:t,onAddWidget:e,onOpenChat:s}){const n=[{label:"SOMA",source:"system:soma",w:6,h:6},{label:"Command Post",source:"system:command-post",w:8,h:6},{label:"Intelligence",source:"system:intelligence",w:6,h:5},{label:"Memory Graph",source:"system:memory-graph",w:8,h:7},{label:"Voice",source:"system:voice",w:5,h:5},{label:"Files",source:"system:files",w:4,h:6},{label:"Infra",source:"system:infra",w:6,h:4},{label:"Tools",source:"system:tools",w:5,h:4},{label:"Daemon",source:"system:daemon",w:6,h:6},{label:"Memory Wiki",source:"system:memory-wiki",w:6,h:6},{label:"Autoresearch",source:"system:autoresearch",w:6,h:6},{label:"Self-Proposals",source:"system:self-proposals",w:6,h:6},{label:"Overview",source:"system:overview",w:6,h:5},{label:"Sessions",source:"system:sessions",w:6,h:5},{label:"Watch",source:"system:watch",w:8,h:7},{label:"Backup",source:"system:backup",w:6,h:6},{label:"Training",source:"system:training",w:6,h:6},{label:"Recipes",source:"system:recipes",w:6,h:6},{label:"VRAM",source:"system:vram",w:6,h:6},{label:"Teams",source:"system:teams",w:6,h:6},{label:"Cron",source:"system:cron",w:6,h:6},{label:"Checkpoints",source:"system:checkpoints",w:6,h:5},{label:"Organism",source:"system:organism",w:6,h:6},{label:"Fleet",source:"system:fleet",w:6,h:5},{label:"Browser",source:"system:browser",w:6,h:5},{label:"Paperclip",source:"system:paperclip",w:6,h:5},{label:"Eval",source:"system:eval",w:6,h:6}];return r.jsx("div",{className:"h-full flex items-center justify-center",children:r.jsxs("div",{className:"text-center max-w-lg",children:[r.jsx("div",{className:"w-16 h-16 rounded-2xl bg-[#6366f1]/5 border border-[#6366f1]/10 flex items-center justify-center mx-auto mb-5",children:r.jsx("svg",{className:"w-7 h-7 text-[#6366f1]/40",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r.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"})})}),r.jsx("h2",{className:"text-xl font-bold text-[#fafafa] mb-2",children:t.name}),r.jsx("p",{className:"text-sm text-[#52525b] mb-6",children:"This space is empty. Ask the agent to create widgets, or add system widgets below."}),r.jsx("div",{className:"flex gap-2 justify-center mb-6 flex-wrap",children:r.jsx("button",{onClick:s,className:"px-4 py-2 rounded-xl bg-[#6366f1]/10 border border-[#6366f1]/20 text-[#818cf8] text-sm font-medium hover:bg-[#6366f1]/20 transition-all",children:"Ask Agent"})}),r.jsx("div",{className:"flex gap-2 justify-center flex-wrap",children:n.map(i=>r.jsxs("button",{onClick:()=>e(i.source,i.label,i.w,i.h),className:"px-3 py-1.5 rounded-lg bg-[#18181b] border border-[#27272a] text-[11px] text-[#52525b] hover:text-[#a1a1aa] hover:border-[#3f3f46] transition-all",children:["+ ",i.label]},i.source))})]})})}const $m=Object.freeze(Object.defineProperty({__proto__:null,default:Pm},Symbol.toStringTag,{value:"Module"}));export{Mi as A,Oi as B,as as C,kl as D,Xr as E,rn as F,Wi as G,Ul as H,Fi as L,$i as M,zi as N,Gl as P,on as R,Gi as S,Yi as T,yr as U,wr as W,ec as a,dc as b,an as c,os as d,mt as e,mr as f,Hi as g,gr as h,Pi as i,Hl as j,ml as k,Ki as l,Zr as m,ic as n,Ui as o,Vi as p,qi as q,wl as r,Tl as s,$m as t};