titan-agent 6.3.2 → 6.3.4

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 (144) hide show
  1. package/dist/utils/constants.js +1 -1
  2. package/dist/utils/constants.js.map +1 -1
  3. package/package.json +1 -1
  4. package/ui/dist/assets/{AuditPanel-6hTX-30T.js → AuditPanel-C7rrUHBM.js} +1 -1
  5. package/ui/dist/assets/{AutonomyPanel-bEolzW0c.js → AutonomyPanel-CcOxsveF.js} +1 -1
  6. package/ui/dist/assets/{AutopilotPanel-BBhP6EEw.js → AutopilotPanel-CjrYEF2s.js} +1 -1
  7. package/ui/dist/assets/{AutoresearchPanel-CmSoFu9c.js → AutoresearchPanel-CBdGRAdZ.js} +1 -1
  8. package/ui/dist/assets/{BackupPanel-BMqXOM64.js → BackupPanel-BhU-utCn.js} +1 -1
  9. package/ui/dist/assets/{BrowserPanel-DqpJBtZO.js → BrowserPanel-Dr-B5Kva.js} +1 -1
  10. package/ui/dist/assets/{CPActivity-kjPVmtna.js → CPActivity-C5kJWqWc.js} +1 -1
  11. package/ui/dist/assets/{CPAgentDetail-DJVqWbIz.js → CPAgentDetail-BVE3LoLA.js} +1 -1
  12. package/ui/dist/assets/{CPAgents-DvoKU7K3.js → CPAgents-BKBSyXHs.js} +1 -1
  13. package/ui/dist/assets/{CPApprovals-CgkIcjKy.js → CPApprovals-AkRGu05y.js} +1 -1
  14. package/ui/dist/assets/{CPCosts-Dh2-rKBQ.js → CPCosts-DC5mPwVm.js} +1 -1
  15. package/ui/dist/assets/{CPDashboard-Bk5ehnOo.js → CPDashboard-C7G-H6HW.js} +1 -1
  16. package/ui/dist/assets/{CPFiles-85DnmiZ9.js → CPFiles-IhcbsdvY.js} +1 -1
  17. package/ui/dist/assets/{CPGoals-CmaEWa0s.js → CPGoals-BL0rrvT5.js} +1 -1
  18. package/ui/dist/assets/{CPInbox-DyrwUxsn.js → CPInbox-CBUkqu4i.js} +1 -1
  19. package/ui/dist/assets/{CPIssueDetail-tuKkMZU0.js → CPIssueDetail-HuI9tPu4.js} +1 -1
  20. package/ui/dist/assets/{CPIssues-CRkGwoU7.js → CPIssues-Do9d-evH.js} +1 -1
  21. package/ui/dist/assets/CPLayout-DlpdPzBu.js +2 -0
  22. package/ui/dist/assets/{CPOrg-BiYIRMSl.js → CPOrg-WHkSBNGU.js} +1 -1
  23. package/ui/dist/assets/{CPRuns-_2GvItJv.js → CPRuns-B4Pz5QkG.js} +1 -1
  24. package/ui/dist/assets/{CPSocial-BBdyKNyq.js → CPSocial-DayQlwZL.js} +1 -1
  25. package/ui/dist/assets/{CPVoice-BnYo-G04.js → CPVoice-C2ry-Muk.js} +1 -1
  26. package/ui/dist/assets/{ChannelsPanel-e1nT5QcW.js → ChannelsPanel-CeIEB9Es.js} +1 -1
  27. package/ui/dist/assets/{CheckpointsPanel-BixKyU53.js → CheckpointsPanel-BkqqvLDL.js} +1 -1
  28. package/ui/dist/assets/{CommandPostHub-Ckh7LlWG.js → CommandPostHub-Jd5_PAh3.js} +3 -3
  29. package/ui/dist/assets/{CronPanel-BMneWRHA.js → CronPanel-COkBBcTV.js} +1 -1
  30. package/ui/dist/assets/{DataTable-CEjOtKUe.js → DataTable-YQ9l5Xab.js} +1 -1
  31. package/ui/dist/assets/{DreamPanel-BJO5hRUh.js → DreamPanel-B5M--_sB.js} +1 -1
  32. package/ui/dist/assets/{EmptyState-CB9me2NW.js → EmptyState-DtSIPEVv.js} +1 -1
  33. package/ui/dist/assets/{EvalHarnessPanel-Dg_ghVTz.js → EvalHarnessPanel-DXU9jNmm.js} +1 -1
  34. package/ui/dist/assets/{EvalPanel-j3fHE-k4.js → EvalPanel-CY1kmmoG.js} +1 -1
  35. package/ui/dist/assets/{FileViewer-C7fgbngf.js → FileViewer-BPLxBXEr.js} +1 -1
  36. package/ui/dist/assets/{FilesPanel-Cimj2Z8k.js → FilesPanel-B5RpGquX.js} +1 -1
  37. package/ui/dist/assets/{FleetPanel-zzprw7Ro.js → FleetPanel-1g-MrF81.js} +1 -1
  38. package/ui/dist/assets/{HomelabPanel-C658fL2z.js → HomelabPanel-CxkWfeeN.js} +1 -1
  39. package/ui/dist/assets/InfraView-CYH3ieie.js +2 -0
  40. package/ui/dist/assets/{InlineEditableField-ChiCaepw.js → InlineEditableField-BuXVLQiL.js} +1 -1
  41. package/ui/dist/assets/{Input-DoWIY9i3.js → Input-C6OxbFDH.js} +1 -1
  42. package/ui/dist/assets/{IntegrationsPanel-Xy3HlXti.js → IntegrationsPanel-CPZclot5.js} +1 -1
  43. package/ui/dist/assets/IntelligenceView-DqwlFo91.js +2 -0
  44. package/ui/dist/assets/{LearningPanel-Ka17sHxK.js → LearningPanel-DHQSZZGb.js} +1 -1
  45. package/ui/dist/assets/{LogsPanel-BiELvlMC.js → LogsPanel-XfC4fyQ6.js} +1 -1
  46. package/ui/dist/assets/{McpPanel-BW2r8V3m.js → McpPanel-CBN7xizL.js} +1 -1
  47. package/ui/dist/assets/{MemoryGraphPanel-DZTQIsys.js → MemoryGraphPanel-BBxgK2Lo.js} +1 -1
  48. package/ui/dist/assets/{MemoryWikiPanel-BSbG8c80.js → MemoryWikiPanel-BNv9ycwr.js} +1 -1
  49. package/ui/dist/assets/{MeshPanel-Ch_uGo4a.js → MeshPanel-GFPkWStS.js} +1 -1
  50. package/ui/dist/assets/{MissionCanvas-BMv0c-RX.js → MissionCanvas-BR9tT-Vs.js} +1 -1
  51. package/ui/dist/assets/{MissionChat-CFwKDVc8.js → MissionChat-B_fuBUn5.js} +1 -1
  52. package/ui/dist/assets/{MissionLibrary-D2LfLlm2.js → MissionLibrary-C9fCMdpu.js} +1 -1
  53. package/ui/dist/assets/{MissionStart-CTyqZWBT.js → MissionStart-Bb2fCB2u.js} +1 -1
  54. package/ui/dist/assets/{Modal-BS3rireW.js → Modal-9_l_CYE2.js} +1 -1
  55. package/ui/dist/assets/{NvidiaPanel-53CiSPrh.js → NvidiaPanel-CiB9Nlbq.js} +1 -1
  56. package/ui/dist/assets/{OrganismPanel-BRbiiY5k.js → OrganismPanel-d6mPFcBq.js} +1 -1
  57. package/ui/dist/assets/{OverviewPanel-CmRVwkE7.js → OverviewPanel-DF7eBJCF.js} +1 -1
  58. package/ui/dist/assets/{PageHeader-Cx4DHJXy.js → PageHeader-BQEb_uAl.js} +1 -1
  59. package/ui/dist/assets/{PersonaProfilesPanel-hmUdUabW.js → PersonaProfilesPanel-qAgZyu1B.js} +1 -1
  60. package/ui/dist/assets/{PersonasPanel-VfvknF9L.js → PersonasPanel-CxDpp_3j.js} +1 -1
  61. package/ui/dist/assets/{PhoneDeskPanel-DX_6zrt5.js → PhoneDeskPanel-CLp3E_Ry.js} +1 -1
  62. package/ui/dist/assets/{RecipesPanel-B7NygJvl.js → RecipesPanel-DqMMQnyc.js} +1 -1
  63. package/ui/dist/assets/{SecurityPanel-DRZu6PRV.js → SecurityPanel-BQ3-aMmO.js} +1 -1
  64. package/ui/dist/assets/{SelfImprovePanel-CgJG9v1W.js → SelfImprovePanel-C-ylXP-k.js} +1 -1
  65. package/ui/dist/assets/{SelfProposalsPanel-BenuzEGo.js → SelfProposalsPanel-d5W-0A3P.js} +1 -1
  66. package/ui/dist/assets/{SessionsPanel-CFdsWt2W.js → SessionsPanel-DzbNc8iW.js} +1 -1
  67. package/ui/dist/assets/{SessionsTab-8Qtu9BMv.js → SessionsTab-CuRh8SAw.js} +1 -1
  68. package/ui/dist/assets/{SettingsPanel-CmIAAw_T.js → SettingsPanel-C1FbNM3W.js} +1 -1
  69. package/ui/dist/assets/SettingsView-ZTklN8Q3.js +2 -0
  70. package/ui/dist/assets/{SkeletonLoader-crWOfBFq.js → SkeletonLoader-CrZUFaIM.js} +1 -1
  71. package/ui/dist/assets/{SkillsPanel-BINP41r2.js → SkillsPanel-eyCYqSuP.js} +1 -1
  72. package/ui/dist/assets/{SomaView-CzZ6SCuw.js → SomaView-CvHD2r-j.js} +1 -1
  73. package/ui/dist/assets/{StatCard-DfoksLmM.js → StatCard-_MlD8k-5.js} +1 -1
  74. package/ui/dist/assets/{StatusBadge-FyqmZDG0.js → StatusBadge-MIQ4EfQR.js} +1 -1
  75. package/ui/dist/assets/{Tabs-BMzVMYab.js → Tabs-DkooY-W7.js} +1 -1
  76. package/ui/dist/assets/{TeamsPanel-CwVNzD77.js → TeamsPanel-fa--osWi.js} +1 -1
  77. package/ui/dist/assets/{TelemetryPanel-C3JTWWQO.js → TelemetryPanel-BEEWcoNE.js} +1 -1
  78. package/ui/dist/assets/{TitanCanvas-CmVs4TFr.js → TitanCanvas-LWyPGpf5.js} +27 -27
  79. package/ui/dist/assets/{ToolsView-C3m7TbnX.js → ToolsView-UCDMsvb1.js} +2 -2
  80. package/ui/dist/assets/{Tooltip-DZJl8UaT.js → Tooltip-DrpHNalN.js} +1 -1
  81. package/ui/dist/assets/{TraceViewer-CfFZQJ3K.js → TraceViewer-XsmYbc0e.js} +1 -1
  82. package/ui/dist/assets/{TrainingPanel-BMunX3EV.js → TrainingPanel-CmJXLn4n.js} +1 -1
  83. package/ui/dist/assets/{VoiceOverlay-DRjTeQgq.js → VoiceOverlay-D2N-c76K.js} +1 -1
  84. package/ui/dist/assets/{VramPanel-C4nG82nu.js → VramPanel-h6zjNx-6.js} +1 -1
  85. package/ui/dist/assets/{WatchView-Cflz1FfL.js → WatchView-DDNt13KH.js} +1 -1
  86. package/ui/dist/assets/{WorkTab-BglKN8Uf.js → WorkTab-CLXkjuee.js} +1 -1
  87. package/ui/dist/assets/{WorkflowsPanel-BZQu93gE.js → WorkflowsPanel-BYtLGQVm.js} +1 -1
  88. package/ui/dist/assets/{archive-C10aphzL.js → archive-BSupLPZM.js} +1 -1
  89. package/ui/dist/assets/{arrow-left-CLTerrT5.js → arrow-left-BaVVZjqf.js} +1 -1
  90. package/ui/dist/assets/{book-open-DQ4VpfMq.js → book-open-CZxMkLs8.js} +1 -1
  91. package/ui/dist/assets/{bot-DNI_W-iH.js → bot-Cv-edYov.js} +1 -1
  92. package/ui/dist/assets/{chart-column-COymYluE.js → chart-column-BSVdQ9RP.js} +1 -1
  93. package/ui/dist/assets/{check-Dq1bBdnM.js → check-DbgTEg8O.js} +1 -1
  94. package/ui/dist/assets/{chevron-right-Dz0EiJIX.js → chevron-right-DfToq0aQ.js} +1 -1
  95. package/ui/dist/assets/{chevron-up-CaJdgiQv.js → chevron-up-DMS2Tjip.js} +1 -1
  96. package/ui/dist/assets/{circle-check-big-Bi688_yD.js → circle-check-big-BBQqeCVt.js} +1 -1
  97. package/ui/dist/assets/{circle-stop-BKeZMLyT.js → circle-stop-CZNS3Uri.js} +1 -1
  98. package/ui/dist/assets/{clipboard-list-BvhH8UZ-.js → clipboard-list-CzMXlUCb.js} +1 -1
  99. package/ui/dist/assets/{clock-BiDhhRG4.js → clock-BvWNugZo.js} +1 -1
  100. package/ui/dist/assets/{dollar-sign-XvC0BdrI.js → dollar-sign-pghzkByE.js} +1 -1
  101. package/ui/dist/assets/{download-BUv-3ow-.js → download-CupMD2Qi.js} +1 -1
  102. package/ui/dist/assets/{external-link-6i_dEGHo.js → external-link-8Pnd2MvS.js} +1 -1
  103. package/ui/dist/assets/{file-text-CMteaHPb.js → file-text-rkojc4Uq.js} +1 -1
  104. package/ui/dist/assets/{flask-conical-DOupoJs-.js → flask-conical-BtbE3rIA.js} +1 -1
  105. package/ui/dist/assets/{folder-Heg9X62R.js → folder-65U1Euur.js} +1 -1
  106. package/ui/dist/assets/{funnel-C1qSeehb.js → funnel-D9FpWHn9.js} +1 -1
  107. package/ui/dist/assets/{git-branch-BgrSzLGu.js → git-branch-D6YV_OC1.js} +1 -1
  108. package/ui/dist/assets/{index-CfeeNofL.js → index-BslUQuVl.js} +61 -61
  109. package/ui/dist/assets/{layers-BXjHgthV.js → layers-rc37Q5yX.js} +1 -1
  110. package/ui/dist/assets/{legacy-CMWeVEm-.js → legacy-BydeSW77.js} +1 -1
  111. package/ui/dist/assets/{lightbulb-CaU3yf0V.js → lightbulb-BEx7BdxD.js} +1 -1
  112. package/ui/dist/assets/{list-todo-DIH1DDut.js → list-todo-6N1AZe4i.js} +1 -1
  113. package/ui/dist/assets/{message-square-CAJnwIi8.js → message-square-BEGY8pHF.js} +1 -1
  114. package/ui/dist/assets/{mic-a150MaF_.js → mic-CGj6cLoV.js} +1 -1
  115. package/ui/dist/assets/{missions-BCmxIqis.js → missions-BohoEPZo.js} +1 -1
  116. package/ui/dist/assets/{network-DpJozzT9.js → network-DxIkmFJR.js} +1 -1
  117. package/ui/dist/assets/{pause-B7pXF6wS.js → pause-CxvyFedA.js} +1 -1
  118. package/ui/dist/assets/{pencil-DNQZmkMU.js → pencil-D5LooNFk.js} +1 -1
  119. package/ui/dist/assets/{play-CB_hciEJ.js → play-6W8amqUG.js} +1 -1
  120. package/ui/dist/assets/{plug-UdiCBZ6I.js → plug-C3Ecy-Ji.js} +1 -1
  121. package/ui/dist/assets/{plus-BNliIo_L.js → plus-BtmCDNeU.js} +1 -1
  122. package/ui/dist/assets/{proxy-tgCU20-X.js → proxy-BD29vUSb.js} +1 -1
  123. package/ui/dist/assets/{radio-KEVgfxWk.js → radio-Bl9Tibea.js} +1 -1
  124. package/ui/dist/assets/{refresh-cw-C4BAymqq.js → refresh-cw-BHphkMjv.js} +1 -1
  125. package/ui/dist/assets/{rotate-ccw-CyT1wcCY.js → rotate-ccw-DQzGCkVc.js} +1 -1
  126. package/ui/dist/assets/{save-ICOKiEQf.js → save-Bk90yLic.js} +1 -1
  127. package/ui/dist/assets/{search-qz2VMyBQ.js → search-DxM6zcDJ.js} +1 -1
  128. package/ui/dist/assets/{send-AYGyxY6d.js → send-ChZ5Hsne.js} +1 -1
  129. package/ui/dist/assets/{server-DMkFokTU.js → server-CSOB40Ah.js} +1 -1
  130. package/ui/dist/assets/{shield-check-Dtr3ujKk.js → shield-check-uMK1alGs.js} +1 -1
  131. package/ui/dist/assets/{terminal-ucriUmF-.js → terminal-lIpm0q0K.js} +1 -1
  132. package/ui/dist/assets/{test-tube-Co4Kjj0G.js → test-tube-DuTInDo7.js} +1 -1
  133. package/ui/dist/assets/{toggle-right-NKDEGJdm.js → toggle-right-j4jgj1NQ.js} +1 -1
  134. package/ui/dist/assets/{trash-2-CJjOlqMp.js → trash-2-2Qmp8Fyr.js} +1 -1
  135. package/ui/dist/assets/{trending-up-CC4itzlz.js → trending-up-BydxQces.js} +1 -1
  136. package/ui/dist/assets/{trophy-BP9FY35i.js → trophy-B8Fq83wO.js} +1 -1
  137. package/ui/dist/assets/{volume-2-CAQ1nA-B.js → volume-2-B6qThcBF.js} +1 -1
  138. package/ui/dist/assets/{wifi-off-jrnDcc0y.js → wifi-off-BX5XYuML.js} +1 -1
  139. package/ui/dist/index.html +1 -1
  140. package/ui/dist/sw.js +1 -1
  141. package/ui/dist/assets/CPLayout-BUN7FasU.js +0 -2
  142. package/ui/dist/assets/InfraView-DAwJClAs.js +0 -2
  143. package/ui/dist/assets/IntelligenceView-CJ2r76hu.js +0 -2
  144. package/ui/dist/assets/SettingsView-ByyjhwLz.js +0 -2
@@ -1,40 +1,40 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SomaView-CzZ6SCuw.js","assets/index-CfeeNofL.js","assets/index-DmgXt1oB.css","assets/Input-DoWIY9i3.js","assets/clsx-B-dksMZM.js","assets/Tooltip-DZJl8UaT.js","assets/SomaView-BtCkeWfZ.css","assets/CommandPostHub-Ckh7LlWG.js","assets/Modal-BS3rireW.js","assets/proxy-tgCU20-X.js","assets/InlineEditableField-ChiCaepw.js","assets/check-Dq1bBdnM.js","assets/pencil-DNQZmkMU.js","assets/approvalHeadline-DB9SgR-9.js","assets/chevron-right-Dz0EiJIX.js","assets/bot-DNI_W-iH.js","assets/pause-B7pXF6wS.js","assets/dollar-sign-XvC0BdrI.js","assets/git-branch-BgrSzLGu.js","assets/chart-column-COymYluE.js","assets/clock-BiDhhRG4.js","assets/message-square-CAJnwIi8.js","assets/file-text-CMteaHPb.js","assets/terminal-ucriUmF-.js","assets/refresh-cw-C4BAymqq.js","assets/circle-stop-BKeZMLyT.js","assets/send-AYGyxY6d.js","assets/plus-BNliIo_L.js","assets/trash-2-CJjOlqMp.js","assets/IntelligenceView-CJ2r76hu.js","assets/MemoryGraphPanel-DZTQIsys.js","assets/network-DpJozzT9.js","assets/search-qz2VMyBQ.js","assets/InfraView-DAwJClAs.js","assets/ToolsView-C3m7TbnX.js","assets/SettingsView-ByyjhwLz.js","assets/SettingsPanel-CmIAAw_T.js","assets/PageHeader-Cx4DHJXy.js","assets/circle-check-big-Bi688_yD.js","assets/mic-a150MaF_.js","assets/wifi-off-jrnDcc0y.js","assets/download-BUv-3ow-.js","assets/play-CB_hciEJ.js","assets/save-ICOKiEQf.js","assets/SecurityPanel-DRZu6PRV.js","assets/AuditPanel-6hTX-30T.js","assets/clipboard-list-BvhH8UZ-.js","assets/funnel-C1qSeehb.js","assets/AutopilotPanel-BBhP6EEw.js","assets/WorkflowsPanel-BZQu93gE.js","assets/toggle-right-NKDEGJdm.js","assets/book-open-DQ4VpfMq.js","assets/LearningPanel-Ka17sHxK.js","assets/lightbulb-CaU3yf0V.js","assets/trending-up-CC4itzlz.js","assets/chevron-up-CaJdgiQv.js","assets/server-DMkFokTU.js","assets/rotate-ccw-CyT1wcCY.js","assets/flask-conical-DOupoJs-.js","assets/archive-C10aphzL.js","assets/radio-KEVgfxWk.js","assets/test-tube-Co4Kjj0G.js","assets/VoiceOverlay-DRjTeQgq.js","assets/volume-2-CAQ1nA-B.js","assets/folder-Heg9X62R.js","assets/shield-check-Dtr3ujKk.js","assets/external-link-6i_dEGHo.js","assets/SelfImprovePanel-CgJG9v1W.js","assets/trophy-BP9FY35i.js","assets/PersonasPanel-VfvknF9L.js","assets/PersonaProfilesPanel-hmUdUabW.js","assets/DreamPanel-BJO5hRUh.js","assets/HomelabPanel-C658fL2z.js","assets/StatCard-DfoksLmM.js","assets/SkeletonLoader-crWOfBFq.js","assets/NvidiaPanel-53CiSPrh.js","assets/FilesPanel-Cimj2Z8k.js","assets/arrow-left-CLTerrT5.js","assets/LogsPanel-BiELvlMC.js","assets/TelemetryPanel-C3JTWWQO.js","assets/SkillsPanel-BINP41r2.js","assets/McpPanel-BW2r8V3m.js","assets/plug-UdiCBZ6I.js","assets/IntegrationsPanel-Xy3HlXti.js","assets/ChannelsPanel-e1nT5QcW.js","assets/MeshPanel-Ch_uGo4a.js","assets/DataTable-CEjOtKUe.js","assets/MemoryWikiPanel-BSbG8c80.js","assets/AutoresearchPanel-CmSoFu9c.js","assets/SelfProposalsPanel-BenuzEGo.js","assets/OverviewPanel-CmRVwkE7.js","assets/layers-BXjHgthV.js","assets/SessionsPanel-CFdsWt2W.js","assets/WatchView-Cflz1FfL.js","assets/BackupPanel-BMqXOM64.js","assets/TrainingPanel-BMunX3EV.js","assets/RecipesPanel-B7NygJvl.js","assets/VramPanel-C4nG82nu.js","assets/TeamsPanel-CwVNzD77.js","assets/CronPanel-BMneWRHA.js","assets/CheckpointsPanel-BixKyU53.js","assets/OrganismPanel-BRbiiY5k.js","assets/FleetPanel-zzprw7Ro.js","assets/BrowserPanel-DqpJBtZO.js","assets/EvalPanel-j3fHE-k4.js","assets/legacy-CMWeVEm-.js"])))=>i.map(i=>d[i]);
2
- var vl=Object.defineProperty;var _l=(t,e,s)=>e in t?vl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var $e=(t,e,s)=>_l(t,typeof e!="symbol"?e+"":e,s);import{c as ts,a as et,g as kl,r as w,b as ge,j as n,S as Sr,W as jr,B as yt,H as Sl,s as jl,u as Zi,d as El,e as Nl,X as js,f as Er,E as eo,A as Vt,C as Nr,U as Cr,h as Tr,G as to,R as oe,_ as le,Z as Cl,i as fn,I as ci,k as Tl,l as Rl,L as so,m as Al,M as Ll,n as Il,o as Dl,p as Ml,t as Dn}from"./index-CfeeNofL.js";import{C as Ol}from"./chevron-up-CaJdgiQv.js";import{P as Pl}from"./plus-BNliIo_L.js";import{F as pn}from"./file-text-CMteaHPb.js";import{S as Rr}from"./server-DMkFokTU.js";import{N as no}from"./network-DpJozzT9.js";import{T as ro}from"./terminal-ucriUmF-.js";import{B as fs}from"./book-open-DQ4VpfMq.js";import{S as mn}from"./save-ICOKiEQf.js";import{P as Wl}from"./pencil-DNQZmkMU.js";import{R as io}from"./rotate-ccw-CyT1wcCY.js";import{S as oo}from"./search-qz2VMyBQ.js";import{S as ao}from"./send-AYGyxY6d.js";import{M as lo}from"./message-square-CAJnwIi8.js";import{M as co}from"./mic-a150MaF_.js";import{F as uo}from"./flask-conical-DOupoJs-.js";import{C as ps}from"./clock-BiDhhRG4.js";import{A as ho}from"./archive-C10aphzL.js";import{R as fo}from"./radio-KEVgfxWk.js";import{T as po,P as di}from"./test-tube-Co4Kjj0G.js";import{VoiceOverlay as Bl}from"./VoiceOverlay-DRjTeQgq.js";import{C as Ul}from"./chevron-right-Dz0EiJIX.js";import{R as gn}from"./refresh-cw-C4BAymqq.js";import{F as Fl}from"./folder-Heg9X62R.js";import{C as ui}from"./check-Dq1bBdnM.js";import{S as $l}from"./shield-check-Dtr3ujKk.js";import{E as hi}from"./external-link-6i_dEGHo.js";import{B as mo}from"./bot-DNI_W-iH.js";import{W as zl}from"./wifi-off-jrnDcc0y.js";/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SomaView-CvHD2r-j.js","assets/index-BslUQuVl.js","assets/index-DmgXt1oB.css","assets/Input-C6OxbFDH.js","assets/clsx-B-dksMZM.js","assets/Tooltip-DrpHNalN.js","assets/SomaView-BtCkeWfZ.css","assets/CommandPostHub-Jd5_PAh3.js","assets/Modal-9_l_CYE2.js","assets/proxy-BD29vUSb.js","assets/InlineEditableField-BuXVLQiL.js","assets/check-DbgTEg8O.js","assets/pencil-D5LooNFk.js","assets/approvalHeadline-DB9SgR-9.js","assets/chevron-right-DfToq0aQ.js","assets/bot-Cv-edYov.js","assets/pause-CxvyFedA.js","assets/dollar-sign-pghzkByE.js","assets/git-branch-D6YV_OC1.js","assets/chart-column-BSVdQ9RP.js","assets/clock-BvWNugZo.js","assets/message-square-BEGY8pHF.js","assets/file-text-rkojc4Uq.js","assets/terminal-lIpm0q0K.js","assets/refresh-cw-BHphkMjv.js","assets/circle-stop-CZNS3Uri.js","assets/send-ChZ5Hsne.js","assets/plus-BtmCDNeU.js","assets/trash-2-2Qmp8Fyr.js","assets/IntelligenceView-DqwlFo91.js","assets/MemoryGraphPanel-BBxgK2Lo.js","assets/network-DxIkmFJR.js","assets/search-DxM6zcDJ.js","assets/InfraView-CYH3ieie.js","assets/ToolsView-UCDMsvb1.js","assets/SettingsView-ZTklN8Q3.js","assets/SettingsPanel-C1FbNM3W.js","assets/PageHeader-BQEb_uAl.js","assets/circle-check-big-BBQqeCVt.js","assets/mic-CGj6cLoV.js","assets/wifi-off-BX5XYuML.js","assets/download-CupMD2Qi.js","assets/play-6W8amqUG.js","assets/save-Bk90yLic.js","assets/SecurityPanel-BQ3-aMmO.js","assets/AuditPanel-C7rrUHBM.js","assets/clipboard-list-CzMXlUCb.js","assets/funnel-D9FpWHn9.js","assets/AutopilotPanel-CjrYEF2s.js","assets/WorkflowsPanel-BYtLGQVm.js","assets/toggle-right-j4jgj1NQ.js","assets/book-open-CZxMkLs8.js","assets/LearningPanel-DHQSZZGb.js","assets/lightbulb-BEx7BdxD.js","assets/trending-up-BydxQces.js","assets/chevron-up-DMS2Tjip.js","assets/server-CSOB40Ah.js","assets/rotate-ccw-DQzGCkVc.js","assets/flask-conical-BtbE3rIA.js","assets/archive-BSupLPZM.js","assets/radio-Bl9Tibea.js","assets/test-tube-DuTInDo7.js","assets/VoiceOverlay-D2N-c76K.js","assets/volume-2-B6qThcBF.js","assets/folder-65U1Euur.js","assets/shield-check-uMK1alGs.js","assets/external-link-8Pnd2MvS.js","assets/SelfImprovePanel-C-ylXP-k.js","assets/trophy-B8Fq83wO.js","assets/PersonasPanel-CxDpp_3j.js","assets/PersonaProfilesPanel-qAgZyu1B.js","assets/DreamPanel-B5M--_sB.js","assets/HomelabPanel-CxkWfeeN.js","assets/StatCard-_MlD8k-5.js","assets/SkeletonLoader-CrZUFaIM.js","assets/NvidiaPanel-CiB9Nlbq.js","assets/FilesPanel-B5RpGquX.js","assets/arrow-left-BaVVZjqf.js","assets/LogsPanel-XfC4fyQ6.js","assets/TelemetryPanel-BEEWcoNE.js","assets/SkillsPanel-eyCYqSuP.js","assets/McpPanel-CBN7xizL.js","assets/plug-C3Ecy-Ji.js","assets/IntegrationsPanel-CPZclot5.js","assets/ChannelsPanel-CeIEB9Es.js","assets/MeshPanel-GFPkWStS.js","assets/DataTable-YQ9l5Xab.js","assets/MemoryWikiPanel-BNv9ycwr.js","assets/AutoresearchPanel-CBdGRAdZ.js","assets/SelfProposalsPanel-d5W-0A3P.js","assets/OverviewPanel-DF7eBJCF.js","assets/layers-rc37Q5yX.js","assets/SessionsPanel-DzbNc8iW.js","assets/WatchView-DDNt13KH.js","assets/BackupPanel-BhU-utCn.js","assets/TrainingPanel-CmJXLn4n.js","assets/RecipesPanel-DqMMQnyc.js","assets/VramPanel-h6zjNx-6.js","assets/TeamsPanel-fa--osWi.js","assets/CronPanel-COkBBcTV.js","assets/CheckpointsPanel-BkqqvLDL.js","assets/OrganismPanel-d6mPFcBq.js","assets/FleetPanel-1g-MrF81.js","assets/BrowserPanel-Dr-B5Kva.js","assets/EvalPanel-CY1kmmoG.js","assets/legacy-BydeSW77.js"])))=>i.map(i=>d[i]);
2
+ var Sl=Object.defineProperty;var jl=(t,e,s)=>e in t?Sl(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var $e=(t,e,s)=>jl(t,typeof e!="symbol"?e+"":e,s);import{c as ts,a as et,g as El,r as w,b as ge,j as n,S as Sr,W as jr,B as yt,H as Nl,s as Cl,u as eo,d as Tl,e as Rl,X as js,f as Er,E as to,A as Vt,C as Nr,U as Cr,h as Tr,G as so,R as oe,_ as le,Z as Al,i as fn,I as ci,k as Ll,l as Il,L as no,m as Dl,M as Ml,n as Ol,o as Pl,p as Wl,t as Dn}from"./index-BslUQuVl.js";import{C as Bl}from"./chevron-up-DMS2Tjip.js";import{P as Ul}from"./plus-BtmCDNeU.js";import{F as pn}from"./file-text-rkojc4Uq.js";import{S as Rr}from"./server-CSOB40Ah.js";import{N as ro}from"./network-DxIkmFJR.js";import{T as io}from"./terminal-lIpm0q0K.js";import{B as fs}from"./book-open-CZxMkLs8.js";import{S as mn}from"./save-Bk90yLic.js";import{P as Fl}from"./pencil-D5LooNFk.js";import{R as oo}from"./rotate-ccw-DQzGCkVc.js";import{S as ao}from"./search-DxM6zcDJ.js";import{S as lo}from"./send-ChZ5Hsne.js";import{M as co}from"./message-square-BEGY8pHF.js";import{M as uo}from"./mic-CGj6cLoV.js";import{F as ho}from"./flask-conical-BtbE3rIA.js";import{C as ps}from"./clock-BvWNugZo.js";import{A as fo}from"./archive-BSupLPZM.js";import{R as po}from"./radio-Bl9Tibea.js";import{T as mo,P as di}from"./test-tube-DuTInDo7.js";import{VoiceOverlay as $l}from"./VoiceOverlay-D2N-c76K.js";import{C as zl}from"./chevron-right-DfToq0aQ.js";import{R as gn}from"./refresh-cw-BHphkMjv.js";import{F as Hl}from"./folder-65U1Euur.js";import{C as ui}from"./check-DbgTEg8O.js";import{S as Vl}from"./shield-check-uMK1alGs.js";import{E as hi}from"./external-link-8Pnd2MvS.js";import{B as go}from"./bot-Cv-edYov.js";import{W as Gl}from"./wifi-off-BX5XYuML.js";/**
3
3
  * @license lucide-react v0.513.0 - ISC
4
4
  *
5
5
  * This source code is licensed under the ISC license.
6
6
  * See the LICENSE file in the root directory of this source tree.
7
- */const Hl=[["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=ts("compass",Hl);/**
7
+ */const ql=[["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"}]],Yl=ts("compass",ql);/**
8
8
  * @license lucide-react v0.513.0 - ISC
9
9
  *
10
10
  * This source code is licensed under the ISC license.
11
11
  * See the LICENSE file in the root directory of this source tree.
12
- */const Gl=[["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"}]],ql=ts("database",Gl);/**
12
+ */const Kl=[["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"}]],Jl=ts("database",Kl);/**
13
13
  * @license lucide-react v0.513.0 - ISC
14
14
  *
15
15
  * This source code is licensed under the ISC license.
16
16
  * See the LICENSE file in the root directory of this source tree.
17
- */const Yl=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Kl=ts("gauge",Yl);/**
17
+ */const Xl=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Ql=ts("gauge",Xl);/**
18
18
  * @license lucide-react v0.513.0 - ISC
19
19
  *
20
20
  * This source code is licensed under the ISC license.
21
21
  * See the LICENSE file in the root directory of this source tree.
22
- */const Jl=[["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"}]],go=ts("git-pull-request",Jl);/**
22
+ */const Zl=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],yo=ts("git-pull-request",Zl);/**
23
23
  * @license lucide-react v0.513.0 - ISC
24
24
  *
25
25
  * This source code is licensed under the ISC license.
26
26
  * See the LICENSE file in the root directory of this source tree.
27
- */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"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Ql=ts("history",Xl);/**
27
+ */const ec=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],tc=ts("history",ec);/**
28
28
  * @license lucide-react v0.513.0 - ISC
29
29
  *
30
30
  * This source code is licensed under the ISC license.
31
31
  * See the LICENSE file in the root directory of this source tree.
32
- */const Zl=[["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"}]],yo=ts("layout-grid",Zl),Fe=()=>new Map,rr=t=>{const e=Fe();return t.forEach((s,r)=>{e.set(r,s)}),e},Ve=(t,e,s)=>{let r=t.get(e);return r===void 0&&t.set(e,r=s()),r},ec=(t,e)=>{const s=[];for(const[r,i]of t)s.push(e(i,r));return s},tc=(t,e)=>{for(const[s,r]of t)if(e(r,s))return!0;return!1},bt=()=>new Set,Mn=t=>t[t.length-1],sc=(t,e)=>{for(let s=0;s<e.length;s++)t.push(e[s])},ct=Array.from,Ar=(t,e)=>{for(let s=0;s<t.length;s++)if(!e(t[s],s,t))return!1;return!0},bo=(t,e)=>{for(let s=0;s<t.length;s++)if(e(t[s],s,t))return!0;return!1},nc=(t,e)=>{const s=new Array(t);for(let r=0;r<t;r++)s[r]=e(r,s);return s},yn=Array.isArray;class xo{constructor(){this._observers=Fe()}on(e,s){return Ve(this._observers,e,bt).add(s),s}once(e,s){const r=(...i)=>{this.off(e,r),s(...i)};this.on(e,r)}off(e,s){const r=this._observers.get(e);r!==void 0&&(r.delete(s),r.size===0&&this._observers.delete(e))}emit(e,s){return ct((this._observers.get(e)||Fe()).values()).forEach(r=>r(...s))}destroy(){this._observers=Fe()}}class Lr{constructor(){this._observers=Fe()}on(e,s){Ve(this._observers,e,bt).add(s)}once(e,s){const r=(...i)=>{this.off(e,r),s(...i)};this.on(e,r)}off(e,s){const r=this._observers.get(e);r!==void 0&&(r.delete(s),r.size===0&&this._observers.delete(e))}emit(e,s){return ct((this._observers.get(e)||Fe()).values()).forEach(r=>r(...s))}destroy(){this._observers=Fe()}}const Xe=Math.floor,$s=Math.abs,rc=Math.log10,Ir=(t,e)=>t<e?t:e,Lt=(t,e)=>t>e?t:e,wo=t=>t!==0?t<0:1/t<0,fi=1,pi=2,On=4,Pn=8,ms=32,at=64,He=128,bn=31,ir=63,St=127,ic=2147483647,qs=Number.MAX_SAFE_INTEGER,mi=Number.MIN_SAFE_INTEGER,oc=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Xe(t)===t),vo=String.fromCharCode,ac=t=>t.toLowerCase(),lc=/^\s*/g,cc=t=>t.replace(lc,""),dc=/([A-Z])/g,gi=(t,e)=>cc(t.replace(dc,s=>`${e}${ac(s)}`)),uc=t=>{const e=unescape(encodeURIComponent(t)),s=e.length,r=new Uint8Array(s);for(let i=0;i<s;i++)r[i]=e.codePointAt(i);return r},gs=typeof TextEncoder<"u"?new TextEncoder:null,hc=t=>gs.encode(t),or=gs?hc:uc;let ds=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ds&&ds.decode(new Uint8Array).length===1&&(ds=null);const fc=(t,e)=>nc(e,()=>t).join("");class Es{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const De=()=>new Es,pc=t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e},Se=t=>{const e=new Uint8Array(pc(t));let s=0;for(let r=0;r<t.bufs.length;r++){const i=t.bufs[r];e.set(i,s),s+=i.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},mc=(t,e)=>{const s=t.cbuf.length;s-t.cpos<e&&(t.bufs.push(new Uint8Array(t.cbuf.buffer,0,t.cpos)),t.cbuf=new Uint8Array(Lt(s,e)*2),t.cpos=0)},Le=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(s*2),t.cpos=0),t.cbuf[t.cpos++]=e},ys=Le,ie=(t,e)=>{for(;e>St;)Le(t,He|St&e),e=Xe(e/128);Le(t,St&e)},Dr=(t,e)=>{const s=wo(e);for(s&&(e=-e),Le(t,(e>ir?He:0)|(s?at:0)|ir&e),e=Xe(e/64);e>0;)Le(t,(e>St?He:0)|St&e),e=Xe(e/128)},ar=new Uint8Array(3e4),gc=ar.length/3,yc=(t,e)=>{if(e.length<gc){const s=gs.encodeInto(e,ar).written||0;ie(t,s);for(let r=0;r<s;r++)Le(t,ar[r])}else je(t,or(e))},bc=(t,e)=>{const s=unescape(encodeURIComponent(e)),r=s.length;ie(t,r);for(let i=0;i<r;i++)Le(t,s.codePointAt(i))},st=gs&&gs.encodeInto?yc:bc,xn=(t,e)=>{const s=t.cbuf.length,r=t.cpos,i=Ir(s-r,e.length),o=e.length-i;t.cbuf.set(e.subarray(0,i),r),t.cpos+=i,o>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(Lt(s*2,o)),t.cbuf.set(e.subarray(i)),t.cpos=o)},je=(t,e)=>{ie(t,e.byteLength),xn(t,e)},Mr=(t,e)=>{mc(t,e);const s=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,s},xc=(t,e)=>Mr(t,4).setFloat32(0,e,!1),wc=(t,e)=>Mr(t,8).setFloat64(0,e,!1),vc=(t,e)=>Mr(t,8).setBigInt64(0,e,!1),yi=new DataView(new ArrayBuffer(4)),_c=t=>(yi.setFloat32(0,t),yi.getFloat32(0)===t),Gt=(t,e)=>{switch(typeof e){case"string":Le(t,119),st(t,e);break;case"number":oc(e)&&$s(e)<=ic?(Le(t,125),Dr(t,e)):_c(e)?(Le(t,124),xc(t,e)):(Le(t,123),wc(t,e));break;case"bigint":Le(t,122),vc(t,e);break;case"object":if(e===null)Le(t,126);else if(yn(e)){Le(t,117),ie(t,e.length);for(let s=0;s<e.length;s++)Gt(t,e[s])}else if(e instanceof Uint8Array)Le(t,116),je(t,e);else{Le(t,118);const s=Object.keys(e);ie(t,s.length);for(let r=0;r<s.length;r++){const i=s[r];st(t,i),Gt(t,e[i])}}break;case"boolean":Le(t,e?120:121);break;default:Le(t,127)}};class bi extends Es{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&ie(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const xi=t=>{t.count>0&&(Dr(t.encoder,t.count===1?t.s:-t.s),t.count>1&&ie(t.encoder,t.count-2))};class zs{constructor(){this.encoder=new Es,this.s=0,this.count=0}write(e){this.s===e?this.count++:(xi(this),this.count=1,this.s=e)}toUint8Array(){return xi(this),Se(this.encoder)}}const wi=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Dr(t.encoder,e),t.count>1&&ie(t.encoder,t.count-2)}};class Wn{constructor(){this.encoder=new Es,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(wi(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return wi(this),Se(this.encoder)}}class kc{constructor(){this.sarr=[],this.s="",this.lensE=new zs}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 Es;return this.sarr.push(this.s),this.s="",st(e,this.sarr.join("")),xn(e,this.lensE.toUint8Array()),Se(e)}}const Ge=t=>new Error(t),Ze=()=>{throw Ge("Method unimplemented")},Qe=()=>{throw Ge("Unexpected case")},_o=Ge("Unexpected end of array"),ko=Ge("Integer out of Range");class wn{constructor(e){this.arr=e,this.pos=0}}const it=t=>new wn(t),Sc=t=>t.pos!==t.arr.length,jc=(t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s},Ie=t=>jc(t,de(t)),Et=t=>t.arr[t.pos++],de=t=>{let e=0,s=1;const r=t.arr.length;for(;t.pos<r;){const i=t.arr[t.pos++];if(e=e+(i&St)*s,s*=128,i<He)return e;if(e>qs)throw ko}throw _o},Or=t=>{let e=t.arr[t.pos++],s=e&ir,r=64;const i=(e&at)>0?-1:1;if((e&He)===0)return i*s;const o=t.arr.length;for(;t.pos<o;){if(e=t.arr[t.pos++],s=s+(e&St)*r,r*=128,e<He)return i*s;if(s>qs)throw ko}throw _o},Ec=t=>{let e=de(t);if(e===0)return"";{let s=String.fromCodePoint(Et(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(Et(t));else for(;e>0;){const r=e<1e4?e:1e4,i=t.arr.subarray(t.pos,t.pos+r);t.pos+=r,s+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(s))}},Nc=t=>ds.decode(Ie(t)),lt=ds?Nc:Ec,Pr=(t,e)=>{const s=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,s},Cc=t=>Pr(t,4).getFloat32(0,!1),Tc=t=>Pr(t,8).getFloat64(0,!1),Rc=t=>Pr(t,8).getBigInt64(0,!1),Ac=[t=>{},t=>null,Or,Cc,Tc,Rc,t=>!1,t=>!0,lt,t=>{const e=de(t),s={};for(let r=0;r<e;r++){const i=lt(t);s[i]=qt(t)}return s},t=>{const e=de(t),s=[];for(let r=0;r<e;r++)s.push(qt(t));return s},Ie],qt=t=>Ac[127-Et(t)](t);class vi extends wn{constructor(e,s){super(e),this.reader=s,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Sc(this)?this.count=de(this)+1:this.count=-1),this.count--,this.s}}class Hs extends wn{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Or(this);const e=wo(this.s);this.count=1,e&&(this.s=-this.s,this.count=de(this)+2)}return this.count--,this.s}}class Bn extends wn{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Or(this),s=e&1;this.diff=Xe(e/2),this.count=1,s&&(this.count=de(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Lc{constructor(e){this.decoder=new Hs(e),this.str=lt(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 Ic=crypto.getRandomValues.bind(crypto),Dc=Math.random,So=()=>Ic(new Uint32Array(1))[0],Mc="10000000-1000-4000-8000"+-1e11,jo=()=>Mc.replace(/[018]/g,t=>(t^So()&15>>t/4).toString(16)),dt=Date.now,Yt=t=>new Promise(t);Promise.all.bind(Promise);const Oc=t=>Promise.reject(t),Wr=t=>Promise.resolve(t),_i=t=>t===void 0?null:t;class Pc{constructor(){this.map=new Map}setItem(e,s){this.map.set(e,s)}getItem(e){return this.map.get(e)}}let Eo=new Pc,Br=!0;try{typeof localStorage<"u"&&localStorage&&(Eo=localStorage,Br=!1)}catch{}const No=Eo,Wc=t=>Br||addEventListener("storage",t),Bc=t=>Br||removeEventListener("storage",t),bs=Symbol("Equality"),Co=(t,e)=>{var s;return t===e||!!((s=t==null?void 0:t[bs])!=null&&s.call(t,e))||!1},Uc=t=>typeof t=="object",Fc=Object.assign,$c=Object.keys,zc=(t,e)=>{for(const s in t)e(t[s],s)},Ys=t=>$c(t).length,Hc=t=>{for(const e in t)return!1;return!0},Ns=(t,e)=>{for(const s in t)if(!e(t[s],s))return!1;return!0},Ur=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Vc=(t,e)=>t===e||Ys(t)===Ys(e)&&Ns(t,(s,r)=>(s!==void 0||Ur(e,r))&&Co(e[r],s)),Gc=Object.freeze,To=t=>{for(const e in t){const s=t[e];(typeof s=="object"||typeof s=="function")&&To(t[e])}return Gc(t)},Fr=(t,e,s=0)=>{try{for(;s<t.length;s++)t[s](...e)}finally{s<t.length&&Fr(t,e,s+1)}},qc=()=>{},Yc=t=>t,Ut=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[bs]!=null)return t[bs](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;break}case Set:{if(t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;break}case Map:{if(t.size!==e.size)return!1;for(const s of t.keys())if(!e.has(s)||!Ut(t.get(s),e.get(s)))return!1;break}case void 0:case Object:if(Ys(t)!==Ys(e))return!1;for(const s in t)if(!Ur(t,s)||!Ut(t[s],e[s]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Ut(t[s],e[s]))return!1;break;default:return!1}return!0},Kc=(t,e)=>e.includes(t);var Ro={};const Kt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Ao=typeof window<"u"&&typeof document<"u"&&!Kt;let tt;const Jc=()=>{if(tt===void 0)if(Kt){tt=Fe();const t=process.argv;let e=null;for(let s=0;s<t.length;s++){const r=t[s];r[0]==="-"?(e!==null&&tt.set(e,""),e=r):e!==null&&(tt.set(e,r),e=null)}e!==null&&tt.set(e,"")}else typeof location=="object"?(tt=Fe(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,s]=t.split("=");tt.set(`--${gi(e,"-")}`,s),tt.set(`-${gi(e,"-")}`,s)}})):tt=Fe();return tt},lr=t=>Jc().has(t),xs=t=>_i(Kt?Ro[t.toUpperCase().replaceAll("-","_")]:No.getItem(t)),Lo=t=>lr("--"+t)||xs(t)!==null,Xc=Lo("production"),Qc=Kt&&Kc(Ro.FORCE_COLOR,["true","1","2"]),Zc=Qc||!lr("--no-colors")&&!Lo("no-color")&&(!Kt||process.stdout.isTTY)&&(!Kt||lr("--color")||xs("COLORTERM")!==null||(xs("TERM")||"").includes("color")),Io=t=>new Uint8Array(t),ed=(t,e,s)=>new Uint8Array(t,e,s),td=t=>new Uint8Array(t),sd=t=>{let e="";for(let s=0;s<t.byteLength;s++)e+=vo(t[s]);return btoa(e)},nd=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),rd=t=>{const e=atob(t),s=Io(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s},id=t=>{const e=Buffer.from(t,"base64");return ed(e.buffer,e.byteOffset,e.byteLength)},Do=Ao?sd:nd,Mo=Ao?rd:id,od=t=>{const e=Io(t.byteLength);return e.set(t),e};class ad{constructor(e,s){this.left=e,this.right=s}}const ot=(t,e)=>new ad(t,e),ki=t=>t.next()>=.5,Un=(t,e,s)=>Xe(t.next()*(s+1-e)+e),Oo=(t,e,s)=>Xe(t.next()*(s+1-e)+e),$r=(t,e,s)=>Oo(t,e,s),ld=t=>vo($r(t,97,122)),cd=(t,e=0,s=20)=>{const r=$r(t,e,s);let i="";for(let o=0;o<r;o++)i+=ld(t);return i},Fn=(t,e)=>e[$r(t,0,e.length-1)],dd=Symbol("0schema");class ud{constructor(){this._rerrs=[]}extend(e,s,r,i=null){this._rerrs.push({path:e,expected:s,has:r,message:i})}toString(){const e=[];for(let s=this._rerrs.length-1;s>0;s--){const r=this._rerrs[s];e.push(fc(" ",(this._rerrs.length-s)*2)+`${r.path!=null?`[${r.path}] `:""}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(`
33
- `)}}const cr=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[bs]?Co(t,e):yn(t)?Ar(t,s=>bo(e,r=>cr(s,r))):Uc(t)?Ns(t,(s,r)=>cr(s,e[r])):!1;class Ue{extends(e){let[s,r]=[this.shape,e.shape];return this.constructor._dilutes&&([r,s]=[s,r]),cr(s,r)}equals(e){return this.constructor===e.constructor&&Ut(this.shape,e.shape)}[dd](){return!0}[bs](e){return this.equals(e)}validate(e){return this.check(e)}check(e,s){Ze()}get nullable(){return ss(this,jn)}get optional(){return new Bo(this)}cast(e){return Si(e,this),e}expect(e){return Si(e,this),e}}$e(Ue,"_dilutes",!1);class zr extends Ue{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s=void 0){const r=(e==null?void 0:e.constructor)===this.shape&&(this._c==null||this._c(e));return!r&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name,(e==null?void 0:e.constructor)!==this.shape?"Constructor match failed":"Check failed")),r}}const Ne=(t,e=null)=>new zr(t,e);Ne(zr);class Hr extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=this.shape(e);return!r&&(s==null||s.extend(null,"custom prop",e==null?void 0:e.constructor.name,"failed to check custom prop")),r}}const Oe=t=>new Hr(t);Ne(Hr);class vn extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=this.shape.some(i=>i===e);return!r&&(s==null||s.extend(null,this.shape.join(" | "),e.toString())),r}}const _n=(...t)=>new vn(t),Po=Ne(vn),hd=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Wo=t=>{if(Jt.check(t))return[hd(t)];if(Po.check(t))return t.shape.map(e=>e+"");if(Yo.check(t))return["[+-]?\\d+.?\\d*"];if(Ko.check(t))return[".*"];if(Js.check(t))return t.shape.map(Wo).flat(1);Qe()};class fd extends Ue{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Wo).map(s=>`(${s.join("|")})`).join("")+"$")}check(e,s){const r=this._r.exec(e)!=null;return!r&&(s==null||s.extend(null,this._r.toString(),e.toString(),"String doesn't match string template.")),r}}Ne(fd);const pd=Symbol("optional");class Bo extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=e===void 0||this.shape.check(e);return!r&&(s==null||s.extend(null,"undefined (optional)","()")),r}get[pd](){return!0}}const md=Ne(Bo);class gd extends Ue{check(e,s){return s==null||s.extend(null,"never",typeof e),!1}}Ne(gd);const hn=class hn extends Ue{constructor(e,s=!1){super(),this.shape=e,this._isPartial=s}get partial(){return new hn(this.shape,!0)}check(e,s){return e==null?(s==null||s.extend(null,"object","null"),!1):Ns(this.shape,(r,i)=>{const o=this._isPartial&&!Ur(e,i)||r.check(e[i],s);return!o&&(s==null||s.extend(i.toString(),r.toString(),typeof e[i],"Object property does not match")),o})}};$e(hn,"_dilutes",!0);let Ks=hn;const yd=t=>new Ks(t),bd=Ne(Ks),xd=Oe(t=>t!=null&&(t.constructor===Object||t.constructor==null));class Uo extends Ue{constructor(e,s){super(),this.shape={keys:e,values:s}}check(e,s){return e!=null&&Ns(e,(r,i)=>{const o=this.shape.keys.check(i,s);return!o&&(s==null||s.extend(i+"","Record",typeof e,o?"Key doesn't match schema":"Value doesn't match value")),o&&this.shape.values.check(r,s)})}}const Fo=(t,e)=>new Uo(t,e),wd=Ne(Uo);class $o extends Ue{constructor(e){super(),this.shape=e}check(e,s){return e!=null&&Ns(this.shape,(r,i)=>{const o=r.check(e[i],s);return!o&&(s==null||s.extend(i.toString(),"Tuple",typeof r)),o})}}const vd=(...t)=>new $o(t);Ne($o);class zo extends Ue{constructor(e){super(),this.shape=e.length===1?e[0]:new kn(e)}check(e,s){const r=yn(e)&&Ar(e,i=>this.shape.check(i));return!r&&(s==null||s.extend(null,"Array","")),r}}const Ho=(...t)=>new zo(t),_d=Ne(zo),kd=Oe(t=>yn(t));class Vo extends Ue{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s){const r=e instanceof this.shape&&(this._c==null||this._c(e));return!r&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name)),r}}const Sd=(t,e=null)=>new Vo(t,e);Ne(Vo);const jd=Sd(Ue);class Ed extends Ue{constructor(e){super(),this.len=e.length-1,this.args=vd(...e.slice(-1)),this.res=e[this.len]}check(e,s){const r=e.constructor===Function&&e.length<=this.len;return!r&&(s==null||s.extend(null,"function",typeof e)),r}}const Nd=Ne(Ed),Cd=Oe(t=>typeof t=="function");class Td extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=Ar(this.shape,i=>i.check(e,s));return!r&&(s==null||s.extend(null,"Intersectinon",typeof e)),r}}Ne(Td,t=>t.shape.length>0);class kn extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=bo(this.shape,i=>i.check(e,s));return s==null||s.extend(null,"Union",typeof e),r}}$e(kn,"_dilutes",!0);const ss=(...t)=>t.findIndex(e=>Js.check(e))>=0?ss(...t.map(e=>ws(e)).map(e=>Js.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new kn(t),Js=Ne(kn),Go=()=>!0,Xs=Oe(Go),Rd=Ne(Hr,t=>t.shape===Go),Vr=Oe(t=>typeof t=="bigint"),Ad=Oe(t=>t===Vr),qo=Oe(t=>typeof t=="symbol");Oe(t=>t===qo);const Ft=Oe(t=>typeof t=="number"),Yo=Oe(t=>t===Ft),Jt=Oe(t=>typeof t=="string"),Ko=Oe(t=>t===Jt),Sn=Oe(t=>typeof t=="boolean"),Ld=Oe(t=>t===Sn),Jo=_n(void 0);Ne(vn,t=>t.shape.length===1&&t.shape[0]===void 0);_n(void 0);const jn=_n(null),Id=Ne(vn,t=>t.shape.length===1&&t.shape[0]===null);Ne(Uint8Array);Ne(zr,t=>t.shape===Uint8Array);const Dd=ss(Ft,Jt,jn,Jo,Vr,Sn,qo);(()=>{const t=Ho(Xs),e=Fo(Jt,Xs),s=ss(Ft,Jt,jn,Sn,t,e);return t.shape=s,e.shape.values=s,s})();const ws=t=>{if(jd.check(t))return t;if(xd.check(t)){const e={};for(const s in t)e[s]=ws(t[s]);return yd(e)}else{if(kd.check(t))return ss(...t.map(ws));if(Dd.check(t))return _n(t);if(Cd.check(t))return Ne(t)}Qe()},Si=Xc?()=>{}:(t,e)=>{const s=new ud;if(!e.check(t,s))throw Ge(`Expected value to be of type ${e.constructor.name}.
34
- ${s.toString()}`)};class Md{constructor(e){this.patterns=[],this.$state=e}if(e,s){return this.patterns.push({if:ws(e),h:s}),this}else(e){return this.if(Xs,e)}done(){return(e,s)=>{for(let r=0;r<this.patterns.length;r++){const i=this.patterns[r];if(i.if.check(e))return i.h(e,s)}throw Ge("Unhandled pattern")}}}const Od=t=>new Md(t),Xo=Od(Xs).if(Yo,(t,e)=>Un(e,mi,qs)).if(Ko,(t,e)=>cd(e)).if(Ld,(t,e)=>ki(e)).if(Ad,(t,e)=>BigInt(Un(e,mi,qs))).if(Js,(t,e)=>Wt(e,Fn(e,t.shape))).if(bd,(t,e)=>{const s={};for(const r in t.shape){let i=t.shape[r];if(md.check(i)){if(ki(e))continue;i=i.shape}s[r]=Xo(i,e)}return s}).if(_d,(t,e)=>{const s=[],r=Oo(e,0,42);for(let i=0;i<r;i++)s.push(Wt(e,t.shape));return s}).if(Po,(t,e)=>Fn(e,t.shape)).if(Id,(t,e)=>null).if(Nd,(t,e)=>{const s=Wt(e,t.res);return()=>s}).if(Rd,(t,e)=>Wt(e,Fn(e,[Ft,Jt,jn,Jo,Vr,Sn,Ho(Ft),Fo(ss("a","b","c"),Ft)]))).if(wd,(t,e)=>{const s={},r=Un(e,0,3);for(let i=0;i<r;i++){const o=Wt(e,t.shape.keys),c=Wt(e,t.shape.values);s[o]=c}return s}).done(),Wt=(t,e)=>Xo(ws(e),t),En=typeof document<"u"?document:{};Oe(t=>t.nodeType===Fd);typeof DOMParser<"u"&&new DOMParser;Oe(t=>t.nodeType===Wd);Oe(t=>t.nodeType===Bd);const Pd=t=>ec(t,(e,s)=>`${s}:${e};`).join(""),Wd=En.ELEMENT_NODE,Bd=En.TEXT_NODE,Ud=En.DOCUMENT_NODE,Fd=En.DOCUMENT_FRAGMENT_NODE;Oe(t=>t.nodeType===Ud);const $d=JSON.stringify,ht=Symbol,Je=ht(),Nt=ht(),Qo=ht(),Gr=ht(),Zo=ht(),ea=ht(),ta=ht(),Nn=ht(),Cn=ht(),zd=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],s=[];let r=0;for(;r<t.length;r++){const o=t[r];if(o===void 0)break;if(o.constructor===String||o.constructor===Number)e.push(o);else if(o.constructor===Object)break}for(r>0&&s.push(e.join(""));r<t.length;r++){const o=t[r];o instanceof Symbol||s.push(o)}return s},ji=[Zo,ta,Nn,Qo];let $n=0,Ei=dt();const Hd=(t,e)=>{const s=ji[$n],r=xs("log"),i=r!==null&&(r==="*"||r==="true"||new RegExp(r,"gi").test(e));return $n=($n+1)%ji.length,e+=": ",i?(...o)=>{var l;o.length===1&&((l=o[0])==null?void 0:l.constructor)===Function&&(o=o[0]());const c=dt(),d=c-Ei;Ei=c,t(s,e,Cn,...o.map(p=>{switch(p!=null&&p.constructor===Uint8Array&&(p=Array.from(p)),typeof p){case"string":case"symbol":return p;default:return $d(p)}}),s," +"+d+"ms")}:qc},Vd={[Je]:ot("font-weight","bold"),[Nt]:ot("font-weight","normal"),[Qo]:ot("color","blue"),[Zo]:ot("color","green"),[Gr]:ot("color","grey"),[ea]:ot("color","red"),[ta]:ot("color","purple"),[Nn]:ot("color","orange"),[Cn]:ot("color","black")},Gd=t=>{var c;t.length===1&&((c=t[0])==null?void 0:c.constructor)===Function&&(t=t[0]());const e=[],s=[],r=Fe();let i=[],o=0;for(;o<t.length;o++){const d=t[o],l=Vd[d];if(l!==void 0)r.set(l.left,l.right);else{if(d===void 0)break;if(d.constructor===String||d.constructor===Number){const p=Pd(r);o>0||p.length>0?(e.push("%c"+d),s.push(p)):e.push(d)}else break}}for(o>0&&(i=s,i.unshift(e.join("")));o<t.length;o++){const d=t[o];d instanceof Symbol||i.push(d)}return i},sa=Zc?Gd:zd,na=(...t)=>{console.log(...sa(t)),ra.forEach(e=>e.print(t))},qd=(...t)=>{console.warn(...sa(t)),t.unshift(Nn),ra.forEach(e=>e.print(t))},ra=bt(),Yd=t=>Hd(na,t),ia=t=>({[Symbol.iterator](){return this},next:t}),Kd=(t,e)=>ia(()=>{let s;do s=t.next();while(!s.done&&!e(s.value));return s}),zn=(t,e)=>ia(()=>{const{done:s,value:r}=t.next();return{done:s,value:s?void 0:e(r)}});class Tn{constructor(e,s){this.clock=e,this.len=s}}class Cs{constructor(){this.clients=new Map}}const oa=(t,e,s)=>e.clients.forEach((r,i)=>{const o=t.doc.store.clients.get(i);if(o!=null){const c=o[o.length-1],d=c.id.clock+c.length;for(let l=0,p=r[l];l<r.length&&p.clock<d;p=r[++l])wa(t,o,p.clock,p.len,s)}}),Jd=(t,e)=>{let s=0,r=t.length-1;for(;s<=r;){const i=Xe((s+r)/2),o=t[i],c=o.clock;if(c<=e){if(e<c+o.len)return i;s=i+1}else r=i-1}return null},aa=(t,e)=>{const s=t.clients.get(e.client);return s!==void 0&&Jd(s,e.clock)!==null},qr=t=>{t.clients.forEach(e=>{e.sort((i,o)=>i.clock-o.clock);let s,r;for(s=1,r=1;s<e.length;s++){const i=e[r-1],o=e[s];i.clock+i.len>=o.clock?e[r-1]=new Tn(i.clock,Lt(i.len,o.clock+o.len-i.clock)):(r<s&&(e[r]=o),r++)}e.length=r})},Xd=t=>{const e=new Cs;for(let s=0;s<t.length;s++)t[s].clients.forEach((r,i)=>{if(!e.clients.has(i)){const o=r.slice();for(let c=s+1;c<t.length;c++)sc(o,t[c].clients.get(i)||[]);e.clients.set(i,o)}});return qr(e),e},Qs=(t,e,s,r)=>{Ve(t.clients,e,()=>[]).push(new Tn(s,r))},Qd=()=>new Cs,Zd=t=>{const e=Qd();return t.clients.forEach((s,r)=>{const i=[];for(let o=0;o<s.length;o++){const c=s[o];if(c.deleted){const d=c.id.clock;let l=c.length;if(o+1<s.length)for(let p=s[o+1];o+1<s.length&&p.deleted;p=s[++o+1])l+=p.length;i.push(new Tn(d,l))}}i.length>0&&e.clients.set(r,i)}),e},ns=(t,e)=>{ie(t.restEncoder,e.clients.size),ct(e.clients.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{t.resetDsCurVal(),ie(t.restEncoder,s);const i=r.length;ie(t.restEncoder,i);for(let o=0;o<i;o++){const c=r[o];t.writeDsClock(c.clock),t.writeDsLen(c.len)}})},Yr=t=>{const e=new Cs,s=de(t.restDecoder);for(let r=0;r<s;r++){t.resetDsCurVal();const i=de(t.restDecoder),o=de(t.restDecoder);if(o>0){const c=Ve(e.clients,i,()=>[]);for(let d=0;d<o;d++)c.push(new Tn(t.readDsClock(),t.readDsLen()))}}return e},Ni=(t,e,s)=>{const r=new Cs,i=de(t.restDecoder);for(let o=0;o<i;o++){t.resetDsCurVal();const c=de(t.restDecoder),d=de(t.restDecoder),l=s.clients.get(c)||[],p=Me(s,c);for(let g=0;g<d;g++){const u=t.readDsClock(),f=u+t.readDsLen();if(u<p){p<f&&Qs(r,c,p,f-p);let x=nt(l,u),y=l[x];for(!y.deleted&&y.id.clock<u&&(l.splice(x+1,0,on(e,y,u-y.id.clock)),x++);x<l.length&&(y=l[x++],y.id.clock<f);)y.deleted||(f<y.id.clock+y.length&&l.splice(x,0,on(e,y,f-y.id.clock)),y.delete(e))}else Qs(r,c,u,f-u)}}if(r.clients.size>0){const o=new Ct;return ie(o.restEncoder,0),ns(o,r),o.toUint8Array()}return null},la=So;class rs extends xo{constructor({guid:e=jo(),collectionid:s=null,gc:r=!0,gcFilter:i=()=>!0,meta:o=null,autoLoad:c=!1,shouldLoad:d=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=la(),this.guid=e,this.collectionid=s,this.share=new Map,this.store=new ba,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=d,this.autoLoad=c,this.meta=o,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Yt(p=>{this.on("load",()=>{this.isLoaded=!0,p(this)})});const l=()=>Yt(p=>{const g=u=>{(u===void 0||u===!0)&&(this.off("sync",g),p())};this.on("sync",g)});this.on("sync",p=>{p===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=p===void 0||p===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;e!==null&&!this.shouldLoad&&we(e.parent.doc,s=>{s.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(ct(this.subdocs).map(e=>e.guid))}transact(e,s=null){return we(this,e,s)}get(e,s=We){const r=Ve(this.share,e,()=>{const o=new s;return o._integrate(this,null),o}),i=r.constructor;if(s!==We&&i!==s)if(i===We){const o=new s;o._map=r._map,r._map.forEach(c=>{for(;c!==null;c=c.left)c.parent=o}),o._start=r._start;for(let c=o._start;c!==null;c=c.right)c.parent=o;return o._length=r._length,this.share.set(e,o),o._integrate(this,null),o}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,zt)}getText(e=""){return this.get(e,Qt)}getMap(e=""){return this.get(e,Tt)}getXmlElement(e=""){return this.get(e,Zt)}getXmlFragment(e=""){return this.get(e,Rt)}toJSON(){const e={};return this.share.forEach((s,r)=>{e[r]=s.toJSON()}),e}destroy(){this.isDestroyed=!0,ct(this.subdocs).forEach(s=>s.destroy());const e=this._item;if(e!==null){this._item=null;const s=e.content;s.doc=new rs({guid:this.guid,...s.opts,shouldLoad:!1}),s.doc._item=e,we(e.parent.doc,r=>{const i=s.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class ca{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return de(this.restDecoder)}readDsLen(){return de(this.restDecoder)}}class da extends ca{readLeftID(){return me(de(this.restDecoder),de(this.restDecoder))}readRightID(){return me(de(this.restDecoder),de(this.restDecoder))}readClient(){return de(this.restDecoder)}readInfo(){return Et(this.restDecoder)}readString(){return lt(this.restDecoder)}readParentInfo(){return de(this.restDecoder)===1}readTypeRef(){return de(this.restDecoder)}readLen(){return de(this.restDecoder)}readAny(){return qt(this.restDecoder)}readBuf(){return od(Ie(this.restDecoder))}readJSON(){return JSON.parse(lt(this.restDecoder))}readKey(){return lt(this.restDecoder)}}class eu{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=de(this.restDecoder),this.dsCurrVal}readDsLen(){const e=de(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Xt extends eu{constructor(e){super(e),this.keys=[],de(e),this.keyClockDecoder=new Bn(Ie(e)),this.clientDecoder=new Hs(Ie(e)),this.leftClockDecoder=new Bn(Ie(e)),this.rightClockDecoder=new Bn(Ie(e)),this.infoDecoder=new vi(Ie(e),Et),this.stringDecoder=new Lc(Ie(e)),this.parentInfoDecoder=new vi(Ie(e),Et),this.typeRefDecoder=new Hs(Ie(e)),this.lenDecoder=new Hs(Ie(e))}readLeftID(){return new $t(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new $t(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 qt(this.restDecoder)}readBuf(){return Ie(this.restDecoder)}readJSON(){return qt(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 ua{constructor(){this.restEncoder=De()}toUint8Array(){return Se(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ie(this.restEncoder,e)}writeDsLen(e){ie(this.restEncoder,e)}}class Ts extends ua{writeLeftID(e){ie(this.restEncoder,e.client),ie(this.restEncoder,e.clock)}writeRightID(e){ie(this.restEncoder,e.client),ie(this.restEncoder,e.clock)}writeClient(e){ie(this.restEncoder,e)}writeInfo(e){ys(this.restEncoder,e)}writeString(e){st(this.restEncoder,e)}writeParentInfo(e){ie(this.restEncoder,e?1:0)}writeTypeRef(e){ie(this.restEncoder,e)}writeLen(e){ie(this.restEncoder,e)}writeAny(e){Gt(this.restEncoder,e)}writeBuf(e){je(this.restEncoder,e)}writeJSON(e){st(this.restEncoder,JSON.stringify(e))}writeKey(e){st(this.restEncoder,e)}}class ha{constructor(){this.restEncoder=De(),this.dsCurrVal=0}toUint8Array(){return Se(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const s=e-this.dsCurrVal;this.dsCurrVal=e,ie(this.restEncoder,s)}writeDsLen(e){e===0&&Qe(),ie(this.restEncoder,e-1),this.dsCurrVal+=e}}class Ct extends ha{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Wn,this.clientEncoder=new zs,this.leftClockEncoder=new Wn,this.rightClockEncoder=new Wn,this.infoEncoder=new bi(ys),this.stringEncoder=new kc,this.parentInfoEncoder=new bi(ys),this.typeRefEncoder=new zs,this.lenEncoder=new zs}toUint8Array(){const e=De();return ie(e,0),je(e,this.keyClockEncoder.toUint8Array()),je(e,this.clientEncoder.toUint8Array()),je(e,this.leftClockEncoder.toUint8Array()),je(e,this.rightClockEncoder.toUint8Array()),je(e,Se(this.infoEncoder)),je(e,this.stringEncoder.toUint8Array()),je(e,Se(this.parentInfoEncoder)),je(e,this.typeRefEncoder.toUint8Array()),je(e,this.lenEncoder.toUint8Array()),xn(e,Se(this.restEncoder)),Se(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Gt(this.restEncoder,e)}writeBuf(e){je(this.restEncoder,e)}writeJSON(e){Gt(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 tu=(t,e,s,r)=>{r=Lt(r,e[0].id.clock);const i=nt(e,r);ie(t.restEncoder,e.length-i),t.writeClient(s),ie(t.restEncoder,r);const o=e[i];o.write(t,r-o.id.clock);for(let c=i+1;c<e.length;c++)e[c].write(t,0)},Kr=(t,e,s)=>{const r=new Map;s.forEach((i,o)=>{Me(e,o)>i&&r.set(o,i)}),Rn(e).forEach((i,o)=>{s.has(o)||r.set(o,0)}),ie(t.restEncoder,r.size),ct(r.entries()).sort((i,o)=>o[0]-i[0]).forEach(([i,o])=>{tu(t,e.clients.get(i),i,o)})},su=(t,e)=>{const s=Fe(),r=de(t.restDecoder);for(let i=0;i<r;i++){const o=de(t.restDecoder),c=new Array(o),d=t.readClient();let l=de(t.restDecoder);s.set(d,{i:0,refs:c});for(let p=0;p<o;p++){const g=t.readInfo();switch(bn&g){case 0:{const u=t.readLen();c[p]=new Ye(me(d,l),u),l+=u;break}case 10:{const u=de(t.restDecoder);c[p]=new Ke(me(d,l),u),l+=u;break}default:{const u=(g&(at|He))===0,f=new Te(me(d,l),null,(g&He)===He?t.readLeftID():null,null,(g&at)===at?t.readRightID():null,u?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,u&&(g&ms)===ms?t.readString():null,Ba(t,g));c[p]=f,l+=f.length}}}}return s},nu=(t,e,s)=>{const r=[];let i=ct(s.keys()).sort((x,y)=>x-y);if(i.length===0)return null;const o=()=>{if(i.length===0)return null;let x=s.get(i[i.length-1]);for(;x.refs.length===x.i;)if(i.pop(),i.length>0)x=s.get(i[i.length-1]);else return null;return x};let c=o();if(c===null)return null;const d=new ba,l=new Map,p=(x,y)=>{const E=l.get(x);(E==null||E>y)&&l.set(x,y)};let g=c.refs[c.i++];const u=new Map,f=()=>{for(const x of r){const y=x.id.client,E=s.get(y);E?(E.i--,d.clients.set(y,E.refs.slice(E.i)),s.delete(y),E.i=0,E.refs=[]):d.clients.set(y,[x]),i=i.filter(I=>I!==y)}r.length=0};for(;;){if(g.constructor!==Ke){const y=Ve(u,g.id.client,()=>Me(e,g.id.client))-g.id.clock;if(y<0)r.push(g),p(g.id.client,g.id.clock-1),f();else{const E=g.getMissing(t,e);if(E!==null){r.push(g);const I=s.get(E)||{refs:[],i:0};if(I.refs.length===I.i)p(E,Me(e,E)),f();else{g=I.refs[I.i++];continue}}else(y===0||y<g.length)&&(g.integrate(t,y),u.set(g.id.client,g.id.clock+g.length))}}if(r.length>0)g=r.pop();else if(c!==null&&c.i<c.refs.length)g=c.refs[c.i++];else{if(c=o(),c===null)break;g=c.refs[c.i++]}}if(d.clients.size>0){const x=new Ct;return Kr(x,d,new Map),ie(x.restEncoder,0),{missing:l,update:x.toUint8Array()}}return null},ru=(t,e)=>Kr(t,e.doc.store,e.beforeState),iu=(t,e,s,r=new Xt(t))=>we(e,i=>{i.local=!1;let o=!1;const c=i.doc,d=c.store,l=su(r,c),p=nu(i,d,l),g=d.pendingStructs;if(g){for(const[f,x]of g.missing)if(x<Me(d,f)){o=!0;break}if(p){for(const[f,x]of p.missing){const y=g.missing.get(f);(y==null||y>x)&&g.missing.set(f,x)}g.update=Zs([g.update,p.update])}}else d.pendingStructs=p;const u=Ni(r,i,d);if(d.pendingDs){const f=new Xt(it(d.pendingDs));de(f.restDecoder);const x=Ni(f,i,d);u&&x?d.pendingDs=Zs([u,x]):d.pendingDs=u||x}else d.pendingDs=u;if(o){const f=d.pendingStructs.update;d.pendingStructs=null,fa(i.doc,f)}},s,!1),fa=(t,e,s,r=Xt)=>{const i=it(e);iu(i,t,s,new r(i))},pa=(t,e,s)=>fa(t,e,s,da),ou=(t,e,s=new Map)=>{Kr(t,e.store,s),ns(t,Zd(e.store))},au=(t,e=new Uint8Array([0]),s=new Ct)=>{const r=ma(e);ou(s,t,r);const i=[s.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(_u(t.store.pendingStructs.update,e)),i.length>1){if(s.constructor===Ts)return wu(i.map((o,c)=>c===0?o:Su(o)));if(s.constructor===Ct)return Zs(i)}return i[0]},Jr=(t,e)=>au(t,e,new Ts),lu=t=>{const e=new Map,s=de(t.restDecoder);for(let r=0;r<s;r++){const i=de(t.restDecoder),o=de(t.restDecoder);e.set(i,o)}return e},ma=t=>lu(new ca(it(t))),ga=(t,e)=>(ie(t.restEncoder,e.size),ct(e.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{ie(t.restEncoder,s),ie(t.restEncoder,r)}),t),cu=(t,e)=>ga(t,Rn(e.store)),du=(t,e=new ha)=>(t instanceof Map?ga(e,t):cu(e,t),e.toUint8Array()),uu=t=>du(t,new ua);class hu{constructor(){this.l=[]}}const Ci=()=>new hu,Ti=(t,e)=>t.l.push(e),Ri=(t,e)=>{const s=t.l,r=s.length;t.l=s.filter(i=>e!==i),r===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},ya=(t,e,s)=>Fr(t.l,[e,s]);class $t{constructor(e,s){this.client=e,this.clock=s}}const Ls=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,me=(t,e)=>new $t(t,e),fu=t=>{for(const[e,s]of t.doc.share.entries())if(s===t)return e;throw Qe()},Bt=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!aa(e.ds,t.id),dr=(t,e)=>{const s=Ve(t.meta,dr,bt),r=t.doc.store;s.has(e)||(e.sv.forEach((i,o)=>{i<Me(r,o)&&xt(t,me(o,i))}),oa(t,e.ds,i=>{}),s.add(e))};class ba{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Rn=t=>{const e=new Map;return t.clients.forEach((s,r)=>{const i=s[s.length-1];e.set(r,i.id.clock+i.length)}),e},Me=(t,e)=>{const s=t.clients.get(e);if(s===void 0)return 0;const r=s[s.length-1];return r.id.clock+r.length},xa=(t,e)=>{let s=t.clients.get(e.id.client);if(s===void 0)s=[],t.clients.set(e.id.client,s);else{const r=s[s.length-1];if(r.id.clock+r.length!==e.id.clock)throw Qe()}s.push(e)},nt=(t,e)=>{let s=0,r=t.length-1,i=t[r],o=i.id.clock;if(o===e)return r;let c=Xe(e/(o+i.length-1)*r);for(;s<=r;){if(i=t[c],o=i.id.clock,o<=e){if(e<o+i.length)return c;s=c+1}else r=c-1;c=Xe((s+r)/2)}throw Qe()},pu=(t,e)=>{const s=t.clients.get(e.client);return s[nt(s,e.clock)]},Hn=pu,ur=(t,e,s)=>{const r=nt(e,s),i=e[r];return i.id.clock<s&&i instanceof Te?(e.splice(r+1,0,on(t,i,s-i.id.clock)),r+1):r},xt=(t,e)=>{const s=t.doc.store.clients.get(e.client);return s[ur(t,s,e.clock)]},Ai=(t,e,s)=>{const r=e.clients.get(s.client),i=nt(r,s.clock),o=r[i];return s.clock!==o.id.clock+o.length-1&&o.constructor!==Ye&&r.splice(i+1,0,on(t,o,s.clock-o.id.clock+1)),o},mu=(t,e,s)=>{const r=t.clients.get(e.id.client);r[nt(r,e.id.clock)]=s},wa=(t,e,s,r,i)=>{if(r===0)return;const o=s+r;let c=ur(t,e,s),d;do d=e[c++],o<d.id.clock+d.length&&ur(t,e,o),i(d);while(c<e.length&&e[c].id.clock<o)};class gu{constructor(e,s,r){this.doc=e,this.deleteSet=new Cs,this.beforeState=Rn(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=s,this.meta=new Map,this.local=r,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Li=(t,e)=>e.deleteSet.clients.size===0&&!tc(e.afterState,(s,r)=>e.beforeState.get(r)!==s)?!1:(qr(e.deleteSet),ru(t,e),ns(t,e.deleteSet),!0),Ii=(t,e,s)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&Ve(t.changed,e,bt).add(s)},Vs=(t,e)=>{let s=t[e],r=t[e-1],i=e;for(;i>0;s=r,r=t[--i-1]){if(r.deleted===s.deleted&&r.constructor===s.constructor&&r.mergeWith(s)){s instanceof Te&&s.parentSub!==null&&s.parent._map.get(s.parentSub)===s&&s.parent._map.set(s.parentSub,r);continue}break}const o=e-i;return o&&t.splice(e+1-o,o),o},yu=(t,e,s)=>{for(const[r,i]of t.clients.entries()){const o=e.clients.get(r);for(let c=i.length-1;c>=0;c--){const d=i[c],l=d.clock+d.len;for(let p=nt(o,d.clock),g=o[p];p<o.length&&g.id.clock<l;g=o[++p]){const u=o[p];if(d.clock+d.len<=u.id.clock)break;u instanceof Te&&u.deleted&&!u.keep&&s(u)&&u.gc(e,!1)}}}},bu=(t,e)=>{t.clients.forEach((s,r)=>{const i=e.clients.get(r);for(let o=s.length-1;o>=0;o--){const c=s[o],d=Ir(i.length-1,1+nt(i,c.clock+c.len-1));for(let l=d,p=i[l];l>0&&p.id.clock>=c.clock;p=i[l])l-=1+Vs(i,l)}})},va=(t,e)=>{if(e<t.length){const s=t[e],r=s.doc,i=r.store,o=s.deleteSet,c=s._mergeStructs;try{qr(o),s.afterState=Rn(s.doc.store),r.emit("beforeObserverCalls",[s,r]);const d=[];s.changed.forEach((l,p)=>d.push(()=>{(p._item===null||!p._item.deleted)&&p._callObserver(s,l)})),d.push(()=>{s.changedParentTypes.forEach((l,p)=>{p._dEH.l.length>0&&(p._item===null||!p._item.deleted)&&(l=l.filter(g=>g.target._item===null||!g.target._item.deleted),l.forEach(g=>{g.currentTarget=p,g._path=null}),l.sort((g,u)=>g.path.length-u.path.length),d.push(()=>{ya(p._dEH,l,s)}))}),d.push(()=>r.emit("afterTransaction",[s,r])),d.push(()=>{s._needFormattingCleanup&&Wu(s)})}),Fr(d,[])}finally{r.gc&&yu(o,i,r.gcFilter),bu(o,i),s.afterState.forEach((g,u)=>{const f=s.beforeState.get(u)||0;if(f!==g){const x=i.clients.get(u),y=Lt(nt(x,f),1);for(let E=x.length-1;E>=y;)E-=1+Vs(x,E)}});for(let g=c.length-1;g>=0;g--){const{client:u,clock:f}=c[g].id,x=i.clients.get(u),y=nt(x,f);y+1<x.length&&Vs(x,y+1)>1||y>0&&Vs(x,y)}if(!s.local&&s.afterState.get(r.clientID)!==s.beforeState.get(r.clientID)&&(na(Nn,Je,"[yjs] ",Nt,ea,"Changed the client-id because another client seems to be using it."),r.clientID=la()),r.emit("afterTransactionCleanup",[s,r]),r._observers.has("update")){const g=new Ts;Li(g,s)&&r.emit("update",[g.toUint8Array(),s.origin,r,s])}if(r._observers.has("updateV2")){const g=new Ct;Li(g,s)&&r.emit("updateV2",[g.toUint8Array(),s.origin,r,s])}const{subdocsAdded:d,subdocsLoaded:l,subdocsRemoved:p}=s;(d.size>0||p.size>0||l.size>0)&&(d.forEach(g=>{g.clientID=r.clientID,g.collectionid==null&&(g.collectionid=r.collectionid),r.subdocs.add(g)}),p.forEach(g=>r.subdocs.delete(g)),r.emit("subdocs",[{loaded:l,added:d,removed:p},r,s]),p.forEach(g=>g.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):va(t,e+1)}}},we=(t,e,s=null,r=!0)=>{const i=t._transactionCleanups;let o=!1,c=null;t._transaction===null&&(o=!0,t._transaction=new gu(t,s,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{c=e(t._transaction)}finally{if(o){const d=t._transaction===i[0];t._transaction=null,d&&va(i,0)}}return c};function*xu(t){const e=de(t.restDecoder);for(let s=0;s<e;s++){const r=de(t.restDecoder),i=t.readClient();let o=de(t.restDecoder);for(let c=0;c<r;c++){const d=t.readInfo();if(d===10){const l=de(t.restDecoder);yield new Ke(me(i,o),l),o+=l}else if((bn&d)!==0){const l=(d&(at|He))===0,p=new Te(me(i,o),null,(d&He)===He?t.readLeftID():null,null,(d&at)===at?t.readRightID():null,l?t.readParentInfo()?t.readString():t.readLeftID():null,l&&(d&ms)===ms?t.readString():null,Ba(t,d));yield p,o+=p.length}else{const l=t.readLen();yield new Ye(me(i,o),l),o+=l}}}}class Xr{constructor(e,s){this.gen=xu(e),this.curr=null,this.done=!1,this.filterSkips=s,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Ke);return this.curr}}class Qr{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const wu=t=>Zs(t,da,Ts),vu=(t,e)=>{if(t.constructor===Ye){const{client:s,clock:r}=t.id;return new Ye(me(s,r+e),t.length-e)}else if(t.constructor===Ke){const{client:s,clock:r}=t.id;return new Ke(me(s,r+e),t.length-e)}else{const s=t,{client:r,clock:i}=s.id;return new Te(me(r,i+e),null,me(r,i+e-1),null,s.rightOrigin,s.parent,s.parentSub,s.content.splice(e))}},Zs=(t,e=Xt,s=Ct)=>{if(t.length===1)return t[0];const r=t.map(g=>new e(it(g)));let i=r.map(g=>new Xr(g,!0)),o=null;const c=new s,d=new Qr(c);for(;i=i.filter(f=>f.curr!==null),i.sort((f,x)=>{if(f.curr.id.client===x.curr.id.client){const y=f.curr.id.clock-x.curr.id.clock;return y===0?f.curr.constructor===x.curr.constructor?0:f.curr.constructor===Ke?1:-1:y}else return x.curr.id.client-f.curr.id.client}),i.length!==0;){const g=i[0],u=g.curr.id.client;if(o!==null){let f=g.curr,x=!1;for(;f!==null&&f.id.clock+f.length<=o.struct.id.clock+o.struct.length&&f.id.client>=o.struct.id.client;)f=g.next(),x=!0;if(f===null||f.id.client!==u||x&&f.id.clock>o.struct.id.clock+o.struct.length)continue;if(u!==o.struct.id.client)mt(d,o.struct,o.offset),o={struct:f,offset:0},g.next();else if(o.struct.id.clock+o.struct.length<f.id.clock)if(o.struct.constructor===Ke)o.struct.length=f.id.clock+f.length-o.struct.id.clock;else{mt(d,o.struct,o.offset);const y=f.id.clock-o.struct.id.clock-o.struct.length;o={struct:new Ke(me(u,o.struct.id.clock+o.struct.length),y),offset:0}}else{const y=o.struct.id.clock+o.struct.length-f.id.clock;y>0&&(o.struct.constructor===Ke?o.struct.length-=y:f=vu(f,y)),o.struct.mergeWith(f)||(mt(d,o.struct,o.offset),o={struct:f,offset:0},g.next())}}else o={struct:g.curr,offset:0},g.next();for(let f=g.curr;f!==null&&f.id.client===u&&f.id.clock===o.struct.id.clock+o.struct.length&&f.constructor!==Ke;f=g.next())mt(d,o.struct,o.offset),o={struct:f,offset:0}}o!==null&&(mt(d,o.struct,o.offset),o=null),Zr(d);const l=r.map(g=>Yr(g)),p=Xd(l);return ns(c,p),c.toUint8Array()},_u=(t,e,s=Xt,r=Ct)=>{const i=ma(e),o=new r,c=new Qr(o),d=new s(it(t)),l=new Xr(d,!1);for(;l.curr;){const g=l.curr,u=g.id.client,f=i.get(u)||0;if(l.curr.constructor===Ke){l.next();continue}if(g.id.clock+g.length>f)for(mt(c,g,Lt(f-g.id.clock,0)),l.next();l.curr&&l.curr.id.client===u;)mt(c,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===u&&l.curr.id.clock+l.curr.length<=f;)l.next()}Zr(c);const p=Yr(d);return ns(o,p),o.toUint8Array()},_a=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Se(t.encoder.restEncoder)}),t.encoder.restEncoder=De(),t.written=0)},mt=(t,e,s)=>{t.written>0&&t.currClient!==e.id.client&&_a(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),ie(t.encoder.restEncoder,e.id.clock+s)),e.write(t.encoder,s),t.written++},Zr=t=>{_a(t);const e=t.encoder.restEncoder;ie(e,t.clientStructs.length);for(let s=0;s<t.clientStructs.length;s++){const r=t.clientStructs[s];ie(e,r.written),xn(e,r.restEncoder)}},ku=(t,e,s,r)=>{const i=new s(it(t)),o=new Xr(i,!1),c=new r,d=new Qr(c);for(let p=o.curr;p!==null;p=o.next())mt(d,e(p),0);Zr(d);const l=Yr(i);return ns(c,l),c.toUint8Array()},Su=t=>ku(t,Yc,Xt,Ts),Di="You must not compute changes after the event-handler fired.";class An{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=ju(this.currentTarget,this.target))}deletes(e){return aa(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ge(Di);const e=new Map,s=this.target;this.transaction.changed.get(s).forEach(i=>{if(i!==null){const o=s._map.get(i);let c,d;if(this.adds(o)){let l=o.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(o))if(l!==null&&this.deletes(l))c="delete",d=Mn(l.content.getContent());else return;else l!==null&&this.deletes(l)?(c="update",d=Mn(l.content.getContent())):(c="add",d=void 0)}else if(this.deletes(o))c="delete",d=Mn(o.content.getContent());else return;e.set(i,{action:c,oldValue:d})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ge(Di);const s=this.target,r=bt(),i=bt(),o=[];if(e={added:r,deleted:i,delta:o,keys:this.keys},this.transaction.changed.get(s).has(null)){let d=null;const l=()=>{d&&o.push(d)};for(let p=s._start;p!==null;p=p.right)p.deleted?this.deletes(p)&&!this.adds(p)&&((d===null||d.delete===void 0)&&(l(),d={delete:0}),d.delete+=p.length,i.add(p)):this.adds(p)?((d===null||d.insert===void 0)&&(l(),d={insert:[]}),d.insert=d.insert.concat(p.content.getContent()),r.add(p)):((d===null||d.retain===void 0)&&(l(),d={retain:0}),d.retain+=p.length);d!==null&&d.retain===void 0&&l()}this._changes=e}return e}}const ju=(t,e)=>{const s=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)s.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;s.unshift(r)}e=e._item.parent}return s},Be=()=>{qd("Invalid access: Add Yjs type to a document before reading data.")},ka=80;let ei=0;class Eu{constructor(e,s){e.marker=!0,this.p=e,this.index=s,this.timestamp=ei++}}const Nu=t=>{t.timestamp=ei++},Sa=(t,e,s)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=s,t.timestamp=ei++},Cu=(t,e,s)=>{if(t.length>=ka){const r=t.reduce((i,o)=>i.timestamp<o.timestamp?i:o);return Sa(r,e,s),r}else{const r=new Eu(e,s);return t.push(r),r}},Ln=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const s=t._searchMarker.length===0?null:t._searchMarker.reduce((o,c)=>$s(e-o.index)<$s(e-c.index)?o:c);let r=t._start,i=0;for(s!==null&&(r=s.p,i=s.index,Nu(s));r.right!==null&&i<e;){if(!r.deleted&&r.countable){if(e<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return s!==null&&$s(s.index-i)<r.parent.length/ka?(Sa(s,r,i),s):Cu(t._searchMarker,r,i)},vs=(t,e,s)=>{for(let r=t.length-1;r>=0;r--){const i=t[r];if(s>0){let o=i.p;for(o.marker=!1;o&&(o.deleted||!o.countable);)o=o.left,o&&!o.deleted&&o.countable&&(i.index-=o.length);if(o===null||o.marker===!0){t.splice(r,1);continue}i.p=o,o.marker=!0}(e<i.index||s>0&&e===i.index)&&(i.index=Lt(e,i.index+s))}},In=(t,e,s)=>{const r=t,i=e.changedParentTypes;for(;Ve(i,t,()=>[]).push(s),t._item!==null;)t=t._item.parent;ya(r._eH,s,e)};class We{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Ci(),this._dEH=Ci(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,s){this.doc=e,this._item=s}_copy(){throw Ze()}clone(){throw Ze()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,s){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Ti(this._eH,e)}observeDeep(e){Ti(this._dEH,e)}unobserve(e){Ri(this._eH,e)}unobserveDeep(e){Ri(this._dEH,e)}toJSON(){}}const ja=(t,e,s)=>{t.doc??Be(),e<0&&(e=t._length+e),s<0&&(s=t._length+s);let r=s-e;const i=[];let o=t._start;for(;o!==null&&r>0;){if(o.countable&&!o.deleted){const c=o.content.getContent();if(c.length<=e)e-=c.length;else{for(let d=e;d<c.length&&r>0;d++)i.push(c[d]),r--;e=0}}o=o.right}return i},Ea=t=>{t.doc??Be();const e=[];let s=t._start;for(;s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i<r.length;i++)e.push(r[i])}s=s.right}return e},_s=(t,e)=>{let s=0,r=t._start;for(t.doc??Be();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let o=0;o<i.length;o++)e(i[o],s++,t)}r=r.right}},Na=(t,e)=>{const s=[];return _s(t,(r,i)=>{s.push(e(r,i,t))}),s},Tu=t=>{let e=t._start,s=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(s===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};s=e.content.getContent(),r=0,e=e.right}const i=s[r++];return s.length<=r&&(s=null),{done:!1,value:i}}}},Ca=(t,e)=>{t.doc??Be();const s=Ln(t,e);let r=t._start;for(s!==null&&(r=s.p,e-=s.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e<r.length)return r.content.getContent()[e];e-=r.length}},en=(t,e,s,r)=>{let i=s;const o=t.doc,c=o.clientID,d=o.store,l=s===null?e._start:s.right;let p=[];const g=()=>{p.length>0&&(i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new At(p)),i.integrate(t,0),p=[])};r.forEach(u=>{if(u===null)p.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:p.push(u);break;default:switch(g(),u.constructor){case Uint8Array:case ArrayBuffer:i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new Rs(new Uint8Array(u))),i.integrate(t,0);break;case rs:i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new As(u)),i.integrate(t,0);break;default:if(u instanceof We)i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new ft(u)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),g()},Ta=()=>Ge("Length exceeded!"),Ra=(t,e,s,r)=>{if(s>e._length)throw Ta();if(s===0)return e._searchMarker&&vs(e._searchMarker,s,r.length),en(t,e,null,r);const i=s,o=Ln(e,s);let c=e._start;for(o!==null&&(c=o.p,s-=o.index,s===0&&(c=c.prev,s+=c&&c.countable&&!c.deleted?c.length:0));c!==null;c=c.right)if(!c.deleted&&c.countable){if(s<=c.length){s<c.length&&xt(t,me(c.id.client,c.id.clock+s));break}s-=c.length}return e._searchMarker&&vs(e._searchMarker,i,r.length),en(t,e,c,r)},Ru=(t,e,s)=>{let i=(e._searchMarker||[]).reduce((o,c)=>c.index>o.index?c:o,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return en(t,e,i,s)},Aa=(t,e,s,r)=>{if(r===0)return;const i=s,o=r,c=Ln(e,s);let d=e._start;for(c!==null&&(d=c.p,s-=c.index);d!==null&&s>0;d=d.right)!d.deleted&&d.countable&&(s<d.length&&xt(t,me(d.id.client,d.id.clock+s)),s-=d.length);for(;r>0&&d!==null;)d.deleted||(r<d.length&&xt(t,me(d.id.client,d.id.clock+r)),d.delete(t),r-=d.length),d=d.right;if(r>0)throw Ta();e._searchMarker&&vs(e._searchMarker,i,-o+r)},tn=(t,e,s)=>{const r=e._map.get(s);r!==void 0&&r.delete(t)},ti=(t,e,s,r)=>{const i=e._map.get(s)||null,o=t.doc,c=o.clientID;let d;if(r==null)d=new At([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:d=new At([r]);break;case Uint8Array:d=new Rs(r);break;case rs:d=new As(r);break;default:if(r instanceof We)d=new ft(r);else throw new Error("Unexpected content type")}new Te(me(c,Me(o.store,c)),i,i&&i.lastId,null,null,e,s,d).integrate(t,0)},si=(t,e)=>{t.doc??Be();const s=t._map.get(e);return s!==void 0&&!s.deleted?s.content.getContent()[s.length-1]:void 0},La=t=>{const e={};return t.doc??Be(),t._map.forEach((s,r)=>{s.deleted||(e[r]=s.content.getContent()[s.length-1])}),e},Ia=(t,e)=>{t.doc??Be();const s=t._map.get(e);return s!==void 0&&!s.deleted},Au=(t,e)=>{const s={};return t._map.forEach((r,i)=>{let o=r;for(;o!==null&&(!e.sv.has(o.id.client)||o.id.clock>=(e.sv.get(o.id.client)||0));)o=o.left;o!==null&&Bt(o,e)&&(s[i]=o.content.getContent()[o.length-1])}),s},Is=t=>(t.doc??Be(),Kd(t._map.entries(),e=>!e[1].deleted));class Lu extends An{}class zt extends We{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const s=new zt;return s.push(e),s}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new zt}clone(){const e=new zt;return e.insert(0,this.toArray().map(s=>s instanceof We?s.clone():s)),e}get length(){return this.doc??Be(),this._length}_callObserver(e,s){super._callObserver(e,s),In(this,e,new Lu(this,e))}insert(e,s){this.doc!==null?we(this.doc,r=>{Ra(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}push(e){this.doc!==null?we(this.doc,s=>{Ru(s,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,s=1){this.doc!==null?we(this.doc,r=>{Aa(r,this,e,s)}):this._prelimContent.splice(e,s)}get(e){return Ca(this,e)}toArray(){return Ea(this)}slice(e=0,s=this.length){return ja(this,e,s)}toJSON(){return this.map(e=>e instanceof We?e.toJSON():e)}map(e){return Na(this,e)}forEach(e){_s(this,e)}[Symbol.iterator](){return Tu(this)}_write(e){e.writeTypeRef(nh)}}const Iu=t=>new zt;class Du extends An{constructor(e,s,r){super(e,s),this.keysChanged=r}}class Tt extends We{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,s){super._integrate(e,s),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new Tt}clone(){const e=new Tt;return this.forEach((s,r)=>{e.set(r,s instanceof We?s.clone():s)}),e}_callObserver(e,s){In(this,e,new Du(this,e,s))}toJSON(){this.doc??Be();const e={};return this._map.forEach((s,r)=>{if(!s.deleted){const i=s.content.getContent()[s.length-1];e[r]=i instanceof We?i.toJSON():i}}),e}get size(){return[...Is(this)].length}keys(){return zn(Is(this),e=>e[0])}values(){return zn(Is(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return zn(Is(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Be(),this._map.forEach((s,r)=>{s.deleted||e(s.content.getContent()[s.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?we(this.doc,s=>{tn(s,this,e)}):this._prelimContent.delete(e)}set(e,s){return this.doc!==null?we(this.doc,r=>{ti(r,this,e,s)}):this._prelimContent.set(e,s),s}get(e){return si(this,e)}has(e){return Ia(this,e)}clear(){this.doc!==null?we(this.doc,e=>{this.forEach(function(s,r,i){tn(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(rh)}}const Mu=t=>new Tt,gt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Vc(t,e);class hr{constructor(e,s,r,i){this.left=e,this.right=s,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Qe(),this.right.content.constructor){case Re:this.right.deleted||is(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 Mi=(t,e,s)=>{for(;e.right!==null&&s>0;){switch(e.right.content.constructor){case Re:e.right.deleted||is(e.currentAttributes,e.right.content);break;default:e.right.deleted||(s<e.right.length&&xt(t,me(e.right.id.client,e.right.id.clock+s)),e.index+=e.right.length,s-=e.right.length);break}e.left=e.right,e.right=e.right.right}return e},Ds=(t,e,s,r)=>{const i=new Map,o=r?Ln(e,s):null;if(o){const c=new hr(o.p.left,o.p,o.index,i);return Mi(t,c,s-o.index)}else{const c=new hr(null,e._start,0,i);return Mi(t,c,s)}},Da=(t,e,s,r)=>{for(;s.right!==null&&(s.right.deleted===!0||s.right.content.constructor===Re&&gt(r.get(s.right.content.key),s.right.content.value));)s.right.deleted||r.delete(s.right.content.key),s.forward();const i=t.doc,o=i.clientID;r.forEach((c,d)=>{const l=s.left,p=s.right,g=new Te(me(o,Me(i.store,o)),l,l&&l.lastId,p,p&&p.id,e,null,new Re(d,c));g.integrate(t,0),s.right=g,s.forward()})},is=(t,e)=>{const{key:s,value:r}=e;r===null?t.delete(s):t.set(s,r)},Ma=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Re&&gt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Oa=(t,e,s,r)=>{const i=t.doc,o=i.clientID,c=new Map;for(const d in r){const l=r[d],p=s.currentAttributes.get(d)??null;if(!gt(p,l)){c.set(d,p);const{left:g,right:u}=s;s.right=new Te(me(o,Me(i.store,o)),g,g&&g.lastId,u,u&&u.id,e,null,new Re(d,l)),s.right.integrate(t,0),s.forward()}}return c},Vn=(t,e,s,r,i)=>{s.currentAttributes.forEach((f,x)=>{i[x]===void 0&&(i[x]=null)});const o=t.doc,c=o.clientID;Ma(s,i);const d=Oa(t,e,s,i),l=r.constructor===String?new rt(r):r instanceof We?new ft(r):new It(r);let{left:p,right:g,index:u}=s;e._searchMarker&&vs(e._searchMarker,s.index,l.getLength()),g=new Te(me(c,Me(o.store,c)),p,p&&p.lastId,g,g&&g.id,e,null,l),g.integrate(t,0),s.right=g,s.index=u,s.forward(),Da(t,e,s,d)},Oi=(t,e,s,r,i)=>{const o=t.doc,c=o.clientID;Ma(s,i);const d=Oa(t,e,s,i);e:for(;s.right!==null&&(r>0||d.size>0&&(s.right.deleted||s.right.content.constructor===Re));){if(!s.right.deleted)switch(s.right.content.constructor){case Re:{const{key:l,value:p}=s.right.content,g=i[l];if(g!==void 0){if(gt(g,p))d.delete(l);else{if(r===0)break e;d.set(l,p)}s.right.delete(t)}else s.currentAttributes.set(l,p);break}default:r<s.right.length&&xt(t,me(s.right.id.client,s.right.id.clock+r)),r-=s.right.length;break}s.forward()}if(r>0){let l="";for(;r>0;r--)l+=`
35
- `;s.right=new Te(me(c,Me(o.store,c)),s.left,s.left&&s.left.lastId,s.right,s.right&&s.right.id,e,null,new rt(l)),s.right.integrate(t,0),s.forward()}Da(t,e,s,d)},Pa=(t,e,s,r,i)=>{let o=e;const c=Fe();for(;o&&(!o.countable||o.deleted);){if(!o.deleted&&o.content.constructor===Re){const p=o.content;c.set(p.key,p)}o=o.right}let d=0,l=!1;for(;e!==o;){if(s===e&&(l=!0),!e.deleted){const p=e.content;switch(p.constructor){case Re:{const{key:g,value:u}=p,f=r.get(g)??null;(c.get(g)!==p||f===u)&&(e.delete(t),d++,!l&&(i.get(g)??null)===u&&f!==u&&(f===null?i.delete(g):i.set(g,f))),!l&&!e.deleted&&is(i,p);break}}}e=e.right}return d},Ou=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const s=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Re){const r=e.content.key;s.has(r)?e.delete(t):s.add(r)}e=e.left}},Pu=t=>{let e=0;return we(t.doc,s=>{let r=t._start,i=t._start,o=Fe();const c=rr(o);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Re:is(c,i.content);break;default:e+=Pa(s,r,i,o,c),o=rr(c),r=i;break}i=i.right}}),e},Wu=t=>{const e=new Set,s=t.doc;for(const[r,i]of t.afterState.entries()){const o=t.beforeState.get(r)||0;i!==o&&wa(t,s.store.clients.get(r),o,i,c=>{!c.deleted&&c.content.constructor===Re&&c.constructor!==Ye&&e.add(c.parent)})}we(s,r=>{oa(t,t.deleteSet,i=>{if(i instanceof Ye||!i.parent._hasFormatting||e.has(i.parent))return;const o=i.parent;i.content.constructor===Re?e.add(o):Ou(r,i)});for(const i of e)Pu(i)})},Pi=(t,e,s)=>{const r=s,i=rr(e.currentAttributes),o=e.right;for(;s>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case ft:case It:case rt:s<e.right.length&&xt(t,me(e.right.id.client,e.right.id.clock+s)),s-=e.right.length,e.right.delete(t);break}e.forward()}o&&Pa(t,o,e.right,i,e.currentAttributes);const c=(e.left||e.right).parent;return c._searchMarker&&vs(c._searchMarker,e.index,-r+s),e};class Bu extends An{constructor(e,s,r){super(e,s),this.childListChanged=!1,this.keysChanged=new Set,r.forEach(i=>{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,s=[];we(e,r=>{const i=new Map,o=new Map;let c=this.target._start,d=null;const l={};let p="",g=0,u=0;const f=()=>{if(d!==null){let x=null;switch(d){case"delete":u>0&&(x={delete:u}),u=0;break;case"insert":(typeof p=="object"||p.length>0)&&(x={insert:p},i.size>0&&(x.attributes={},i.forEach((y,E)=>{y!==null&&(x.attributes[E]=y)}))),p="";break;case"retain":g>0&&(x={retain:g},Hc(l)||(x.attributes=Fc({},l))),g=0;break}x&&s.push(x),d=null}};for(;c!==null;){switch(c.content.constructor){case ft:case It:this.adds(c)?this.deletes(c)||(f(),d="insert",p=c.content.getContent()[0],f()):this.deletes(c)?(d!=="delete"&&(f(),d="delete"),u+=1):c.deleted||(d!=="retain"&&(f(),d="retain"),g+=1);break;case rt:this.adds(c)?this.deletes(c)||(d!=="insert"&&(f(),d="insert"),p+=c.content.str):this.deletes(c)?(d!=="delete"&&(f(),d="delete"),u+=c.length):c.deleted||(d!=="retain"&&(f(),d="retain"),g+=c.length);break;case Re:{const{key:x,value:y}=c.content;if(this.adds(c)){if(!this.deletes(c)){const E=i.get(x)??null;gt(E,y)?y!==null&&c.delete(r):(d==="retain"&&f(),gt(y,o.get(x)??null)?delete l[x]:l[x]=y)}}else if(this.deletes(c)){o.set(x,y);const E=i.get(x)??null;gt(E,y)||(d==="retain"&&f(),l[x]=E)}else if(!c.deleted){o.set(x,y);const E=l[x];E!==void 0&&(gt(E,y)?E!==null&&c.delete(r):(d==="retain"&&f(),y===null?delete l[x]:l[x]=y))}c.deleted||(d==="insert"&&f(),is(i,c.content));break}}c=c.right}for(f();s.length>0;){const x=s[s.length-1];if(x.retain!==void 0&&x.attributes===void 0)s.pop();else break}}),this._delta=s}return this._delta}}class Qt extends We{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Be(),this._length}_integrate(e,s){super._integrate(e,s);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Qt}clone(){const e=new Qt;return e.applyDelta(this.toDelta()),e}_callObserver(e,s){super._callObserver(e,s);const r=new Bu(this,e,s);In(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Be();let e="",s=this._start;for(;s!==null;)!s.deleted&&s.countable&&s.content.constructor===rt&&(e+=s.content.str),s=s.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:s=!0}={}){this.doc!==null?we(this.doc,r=>{const i=new hr(null,this._start,0,new Map);for(let o=0;o<e.length;o++){const c=e[o];if(c.insert!==void 0){const d=!s&&typeof c.insert=="string"&&o===e.length-1&&i.right===null&&c.insert.slice(-1)===`
36
- `?c.insert.slice(0,-1):c.insert;(typeof d!="string"||d.length>0)&&Vn(r,this,i,d,c.attributes||{})}else c.retain!==void 0?Oi(r,this,i,c.retain,c.attributes||{}):c.delete!==void 0&&Pi(r,i,c.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,s,r){this.doc??Be();const i=[],o=new Map,c=this.doc;let d="",l=this._start;function p(){if(d.length>0){const u={};let f=!1;o.forEach((y,E)=>{f=!0,u[E]=y});const x={insert:d};f&&(x.attributes=u),i.push(x),d=""}}const g=()=>{for(;l!==null;){if(Bt(l,e)||s!==void 0&&Bt(l,s))switch(l.content.constructor){case rt:{const u=o.get("ychange");e!==void 0&&!Bt(l,e)?(u===void 0||u.user!==l.id.client||u.type!=="removed")&&(p(),o.set("ychange",r?r("removed",l.id):{type:"removed"})):s!==void 0&&!Bt(l,s)?(u===void 0||u.user!==l.id.client||u.type!=="added")&&(p(),o.set("ychange",r?r("added",l.id):{type:"added"})):u!==void 0&&(p(),o.delete("ychange")),d+=l.content.str;break}case ft:case It:{p();const u={insert:l.content.getContent()[0]};if(o.size>0){const f={};u.attributes=f,o.forEach((x,y)=>{f[y]=x})}i.push(u);break}case Re:Bt(l,e)&&(p(),is(o,l.content));break}l=l.right}p()};return e||s?we(c,u=>{e&&dr(u,e),s&&dr(u,s),g()},"cleanup"):g(),i}insert(e,s,r){if(s.length<=0)return;const i=this.doc;i!==null?we(i,o=>{const c=Ds(o,this,e,!r);r||(r={},c.currentAttributes.forEach((d,l)=>{r[l]=d})),Vn(o,this,c,s,r)}):this._pending.push(()=>this.insert(e,s,r))}insertEmbed(e,s,r){const i=this.doc;i!==null?we(i,o=>{const c=Ds(o,this,e,!r);Vn(o,this,c,s,r||{})}):this._pending.push(()=>this.insertEmbed(e,s,r||{}))}delete(e,s){if(s===0)return;const r=this.doc;r!==null?we(r,i=>{Pi(i,Ds(i,this,e,!0),s)}):this._pending.push(()=>this.delete(e,s))}format(e,s,r){if(s===0)return;const i=this.doc;i!==null?we(i,o=>{const c=Ds(o,this,e,!1);c.right!==null&&Oi(o,this,c,s,r)}):this._pending.push(()=>this.format(e,s,r))}removeAttribute(e){this.doc!==null?we(this.doc,s=>{tn(s,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,s){this.doc!==null?we(this.doc,r=>{ti(r,this,e,s)}):this._pending.push(()=>this.setAttribute(e,s))}getAttribute(e){return si(this,e)}getAttributes(){return La(this)}_write(e){e.writeTypeRef(ih)}}const Uu=t=>new Qt;class Gn{constructor(e,s=()=>!0){this._filter=s,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Be()}[Symbol.iterator](){return this}next(){let e=this._currentNode,s=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(s)))do if(s=e.content.type,!e.deleted&&(s.constructor===Zt||s.constructor===Rt)&&s._start!==null)e=s._start;else for(;e!==null;){const r=e.next;if(r!==null){e=r;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Rt extends We{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Rt}clone(){const e=new Rt;return e.insert(0,this.toArray().map(s=>s instanceof We?s.clone():s)),e}get length(){return this.doc??Be(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Gn(this,e)}querySelector(e){e=e.toUpperCase();const r=new Gn(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),ct(new Gn(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e))}_callObserver(e,s){In(this,e,new zu(this,s,e))}toString(){return Na(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,s={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),_s(this,o=>{i.insertBefore(o.toDOM(e,s,r),null)}),i}insert(e,s){this.doc!==null?we(this.doc,r=>{Ra(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}insertAfter(e,s){if(this.doc!==null)we(this.doc,r=>{const i=e&&e instanceof We?e._item:e;en(r,this,i,s)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(o=>o===e)+1;if(i===0&&e!==null)throw Ge("Reference item not found");r.splice(i,0,...s)}}delete(e,s=1){this.doc!==null?we(this.doc,r=>{Aa(r,this,e,s)}):this._prelimContent.splice(e,s)}toArray(){return Ea(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Ca(this,e)}slice(e=0,s=this.length){return ja(this,e,s)}forEach(e){_s(this,e)}_write(e){e.writeTypeRef(ah)}}const Fu=t=>new Rt;class Zt extends Rt{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,s){super._integrate(e,s),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new Zt(this.nodeName)}clone(){const e=new Zt(this.nodeName),s=this.getAttributes();return zc(s,(r,i)=>{e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof We?r.clone():r)),e}toString(){const e=this.getAttributes(),s=[],r=[];for(const d in e)r.push(d);r.sort();const i=r.length;for(let d=0;d<i;d++){const l=r[d];s.push(l+'="'+e[l]+'"')}const o=this.nodeName.toLocaleLowerCase(),c=s.length>0?" "+s.join(" "):"";return`<${o}${c}>${super.toString()}</${o}>`}removeAttribute(e){this.doc!==null?we(this.doc,s=>{tn(s,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,s){this.doc!==null?we(this.doc,r=>{ti(r,this,e,s)}):this._prelimAttrs.set(e,s)}getAttribute(e){return si(this,e)}hasAttribute(e){return Ia(this,e)}getAttributes(e){return e?Au(this,e):La(this)}toDOM(e=document,s={},r){const i=e.createElement(this.nodeName),o=this.getAttributes();for(const c in o){const d=o[c];typeof d=="string"&&i.setAttribute(c,d)}return _s(this,c=>{i.appendChild(c.toDOM(e,s,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(oh),e.writeKey(this.nodeName)}}const $u=t=>new Zt(t.readKey());class zu extends An{constructor(e,s,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,s.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class sn extends Tt{constructor(e){super(),this.hookName=e}_copy(){return new sn(this.hookName)}clone(){const e=new sn(this.hookName);return this.forEach((s,r)=>{e.set(r,s)}),e}toDOM(e=document,s={},r){const i=s[this.hookName];let o;return i!==void 0?o=i.createDom(this):o=document.createElement(this.hookName),o.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(o,this),o}_write(e){e.writeTypeRef(lh),e.writeKey(this.hookName)}}const Hu=t=>new sn(t.readKey());class nn extends Qt{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 nn}clone(){const e=new nn;return e.applyDelta(this.toDelta()),e}toDOM(e=document,s,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const s=[];for(const i in e.attributes){const o=[];for(const c in e.attributes[i])o.push({key:c,value:e.attributes[i][c]});o.sort((c,d)=>c.key<d.key?-1:1),s.push({nodeName:i,attrs:o})}s.sort((i,o)=>i.nodeName<o.nodeName?-1:1);let r="";for(let i=0;i<s.length;i++){const o=s[i];r+=`<${o.nodeName}`;for(let c=0;c<o.attrs.length;c++){const d=o.attrs[c];r+=` ${d.key}="${d.value}"`}r+=">"}r+=e.insert;for(let i=s.length-1;i>=0;i--)r+=`</${s[i].nodeName}>`;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(ch)}}const Vu=t=>new nn;class ni{constructor(e,s){this.id=e,this.length=s}get deleted(){throw Ze()}mergeWith(e){return!1}write(e,s,r){throw Ze()}integrate(e,s){throw Ze()}}const Gu=0;class Ye extends ni{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),xa(e.doc.store,this)}write(e,s){e.writeInfo(Gu),e.writeLen(this.length-s)}getMissing(e,s){return null}}class Rs{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Rs(this.content)}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeBuf(this.content)}getRef(){return 3}}const qu=t=>new Rs(t.readBuf());class ks{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new ks(this.len)}splice(e){const s=new ks(this.len-e);return this.len=e,s}mergeWith(e){return this.len+=e.len,!0}integrate(e,s){Qs(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 Yu=t=>new ks(t.readLen()),Wa=(t,e)=>new rs({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class As{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 As(Wa(this.doc.guid,this.opts))}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){this.doc._item=s,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,s){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const Ku=t=>new As(Wa(t.readString(),t.readAny()));class It{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new It(this.embed)}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeJSON(this.embed)}getRef(){return 5}}const Ju=t=>new It(t.readJSON());class Re{constructor(e,s){this.key=e,this.value=s}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Re(this.key,this.value)}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){const r=s.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,s){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const Xu=t=>new Re(t.readKey(),t.readJSON());class rn{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new rn(this.arr)}splice(e){const s=new rn(this.arr.slice(e));return this.arr=this.arr.slice(0,e),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){const r=this.arr.length;e.writeLen(r-s);for(let i=s;i<r;i++){const o=this.arr[i];e.writeString(o===void 0?"undefined":JSON.stringify(o))}}getRef(){return 2}}const Qu=t=>{const e=t.readLen(),s=[];for(let r=0;r<e;r++){const i=t.readString();i==="undefined"?s.push(void 0):s.push(JSON.parse(i))}return new rn(s)},Zu=xs("node_env")==="development";class At{constructor(e){this.arr=e,Zu&&To(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new At(this.arr)}splice(e){const s=new At(this.arr.slice(e));return this.arr=this.arr.slice(0,e),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){const r=this.arr.length;e.writeLen(r-s);for(let i=s;i<r;i++){const o=this.arr[i];e.writeAny(o)}}getRef(){return 8}}const eh=t=>{const e=t.readLen(),s=[];for(let r=0;r<e;r++)s.push(t.readAny());return new At(s)};class rt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new rt(this.str)}splice(e){const s=new rt(this.str.slice(e));this.str=this.str.slice(0,e);const r=this.str.charCodeAt(e-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",s.str="�"+s.str.slice(1)),s}mergeWith(e){return this.str+=e.str,!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeString(s===0?this.str:this.str.slice(s))}getRef(){return 4}}const th=t=>new rt(t.readString()),sh=[Iu,Mu,Uu,$u,Fu,Hu,Vu],nh=0,rh=1,ih=2,oh=3,ah=4,lh=5,ch=6;class ft{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new ft(this.type._copy())}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){this.type._integrate(e.doc,s)}delete(e){let s=this.type._start;for(;s!==null;)s.deleted?s.id.clock<(e.beforeState.get(s.id.client)||0)&&e._mergeStructs.push(s):s.delete(e),s=s.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let s=this.type._start;for(;s!==null;)s.gc(e,!0),s=s.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,s){this.type._write(e)}getRef(){return 7}}const dh=t=>new ft(sh[t.readTypeRef()](t)),on=(t,e,s)=>{const{client:r,clock:i}=e.id,o=new Te(me(r,i+s),e,me(r,i+s-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(s));return e.deleted&&o.markDeleted(),e.keep&&(o.keep=!0),e.redone!==null&&(o.redone=me(e.redone.client,e.redone.clock+s)),e.right=o,o.right!==null&&(o.right.left=o),t._mergeStructs.push(o),o.parentSub!==null&&o.right===null&&o.parent._map.set(o.parentSub,o),e.length=s,o};class Te extends ni{constructor(e,s,r,i,o,c,d,l){super(e,l.getLength()),this.origin=r,this.left=s,this.right=i,this.rightOrigin=o,this.parent=c,this.parentSub=d,this.redone=null,this.content=l,this.info=this.content.isCountable()?pi:0}set marker(e){(this.info&Pn)>0!==e&&(this.info^=Pn)}get marker(){return(this.info&Pn)>0}get keep(){return(this.info&fi)>0}set keep(e){this.keep!==e&&(this.info^=fi)}get countable(){return(this.info&pi)>0}get deleted(){return(this.info&On)>0}set deleted(e){this.deleted!==e&&(this.info^=On)}markDeleted(){this.info|=On}getMissing(e,s){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Me(s,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Me(s,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===$t&&this.id.client!==this.parent.client&&this.parent.clock>=Me(s,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Ai(e,s,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=xt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ye||this.right&&this.right.constructor===Ye)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Te?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Te&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===$t){const r=Hn(s,this.parent);r.constructor===Ye?this.parent=null:this.parent=r.content.type}return null}integrate(e,s){if(s>0&&(this.id.clock+=s,this.left=Ai(e,e.doc.store,me(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(s),this.length-=s),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const o=new Set,c=new Set;for(;i!==null&&i!==this.right;){if(c.add(i),o.add(i),Ls(this.origin,i.origin)){if(i.id.client<this.id.client)r=i,o.clear();else if(Ls(this.rightOrigin,i.rightOrigin))break}else if(i.origin!==null&&c.has(Hn(e.doc.store,i.origin)))o.has(Hn(e.doc.store,i.origin))||(r=i,o.clear());else break;i=i.right}this.left=r}if(this.left!==null){const r=this.left.right;this.right=r,this.left.right=this}else{let r;if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start,this.parent._start=this;this.right=r}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),xa(e.doc.store,this),this.content.integrate(e,this),Ii(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Ye(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:me(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ls(e.origin,this.lastId)&&this.right===e&&Ls(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const s=this.parent._searchMarker;return s&&s.forEach(r=>{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const s=this.parent;this.countable&&this.parentSub===null&&(s._length-=this.length),this.markDeleted(),Qs(e.deleteSet,this.id.client,this.id.clock,this.length),Ii(e,s,this.parentSub),this.content.delete(e)}}gc(e,s){if(!this.deleted)throw Qe();this.content.gc(e),s?mu(e,this,new Ye(this.id,this.length)):this.content=new ks(this.length)}write(e,s){const r=s>0?me(this.id.client,this.id.clock+s-1):this.origin,i=this.rightOrigin,o=this.parentSub,c=this.content.getRef()&bn|(r===null?0:He)|(i===null?0:at)|(o===null?0:ms);if(e.writeInfo(c),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const d=this.parent;if(d._item!==void 0){const l=d._item;if(l===null){const p=fu(d);e.writeParentInfo(!0),e.writeString(p)}else e.writeParentInfo(!1),e.writeLeftID(l.id)}else d.constructor===String?(e.writeParentInfo(!0),e.writeString(d)):d.constructor===$t?(e.writeParentInfo(!1),e.writeLeftID(d)):Qe();o!==null&&e.writeString(o)}this.content.write(e,s)}}const Ba=(t,e)=>uh[e&bn](t),uh=[()=>{Qe()},Yu,Qu,qu,th,Ju,Xu,dh,eh,Ku,()=>{Qe()}],hh=10;class Ke extends ni{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,s){Qe()}write(e,s){e.writeInfo(hh),ie(e.restEncoder,this.length-s)}getMissing(e,s){return null}}const Ua=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Fa="__ $YJS$ __";Ua[Fa]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Ua[Fa]=!0;const Dt=t=>Yt((e,s)=>{t.onerror=r=>s(new Error(r.target.error)),t.onsuccess=r=>e(r.target.result)}),fh=(t,e)=>Yt((s,r)=>{const i=indexedDB.open(t);i.onupgradeneeded=o=>e(o.target.result),i.onerror=o=>r(Ge(o.target.error)),i.onsuccess=o=>{const c=o.target.result;c.onversionchange=()=>{c.close()},s(c)}}),ph=t=>Dt(indexedDB.deleteDatabase(t)),mh=(t,e)=>e.forEach(s=>t.createObjectStore.apply(t,s)),cs=(t,e,s="readwrite")=>{const r=t.transaction(e,s);return e.map(i=>kh(r,i))},$a=(t,e)=>Dt(t.count(e)),gh=(t,e)=>Dt(t.get(e)),za=(t,e)=>Dt(t.delete(e)),yh=(t,e,s)=>Dt(t.put(e,s)),fr=(t,e)=>Dt(t.add(e)),bh=(t,e,s)=>Dt(t.getAll(e,s)),xh=(t,e,s)=>{let r=null;return _h(t,e,i=>(r=i,!1),s).then(()=>r)},wh=(t,e=null)=>xh(t,e,"prev"),vh=(t,e)=>Yt((s,r)=>{t.onerror=r,t.onsuccess=async i=>{const o=i.target.result;if(o===null||await e(o)===!1)return s();o.continue()}}),_h=(t,e,s,r="next")=>vh(t.openKeyCursor(e,r),i=>s(i.key)),kh=(t,e)=>t.objectStore(e),Sh=(t,e)=>IDBKeyRange.upperBound(t,e),jh=(t,e)=>IDBKeyRange.lowerBound(t,e),qn="custom",Ha="updates",Va=500,Ga=(t,e=()=>{},s=()=>{})=>{const[r]=cs(t.db,[Ha]);return bh(r,jh(t._dbref,!1)).then(i=>{t._destroyed||(e(r),we(t.doc,()=>{i.forEach(o=>pa(t.doc,o))},t,!1),s(r))}).then(()=>wh(r).then(i=>{t._dbref=i+1})).then(()=>$a(r).then(i=>{t._dbsize=i})).then(()=>r)},Eh=(t,e=!0)=>Ga(t).then(s=>{(e||t._dbsize>=Va)&&fr(s,Jr(t.doc)).then(()=>za(s,Sh(t._dbref,!0))).then(()=>$a(s).then(r=>{t._dbsize=r}))});class Nh extends Lr{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=fh(e,r=>mh(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Yt(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,Ga(this,c=>fr(c,Jr(s)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,i)=>{if(this.db&&i!==this){const[o]=cs(this.db,[Ha]);fr(o,r),++this._dbsize>=Va&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Eh(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(()=>{ph(this.name)})}get(e){return this._db.then(s=>{const[r]=cs(s,[qn],"readonly");return gh(r,e)})}set(e,s){return this._db.then(r=>{const[i]=cs(r,[qn]);return yh(i,s,e)})}del(e){return this._db.then(s=>{const[r]=cs(s,[qn]);return za(r,e)})}}const Ch=1200,Th=2500,an=3e4,pr=t=>{if(t.shouldConnect&&t.ws===null){const e=new WebSocket(t.url),s=t.binaryType;let r=null;s&&(e.binaryType=s),t.ws=e,t.connecting=!0,t.connected=!1,e.onmessage=c=>{t.lastMessageReceived=dt();const d=c.data,l=typeof d=="string"?JSON.parse(d):d;l&&l.type==="pong"&&(clearTimeout(r),r=setTimeout(o,an/2)),t.emit("message",[l,t])};const i=c=>{t.ws!==null&&(t.ws=null,t.connecting=!1,t.connected?(t.connected=!1,t.emit("disconnect",[{type:"disconnect",error:c},t])):t.unsuccessfulReconnects++,setTimeout(pr,Ir(rc(t.unsuccessfulReconnects+1)*Ch,Th),t)),clearTimeout(r)},o=()=>{t.ws===e&&t.send({type:"ping"})};e.onclose=()=>i(null),e.onerror=c=>i(c),e.onopen=()=>{t.lastMessageReceived=dt(),t.connecting=!1,t.connected=!0,t.unsuccessfulReconnects=0,t.emit("connect",[{type:"connect"},t]),r=setTimeout(o,an/2)}}};class Rh extends Lr{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&&an<dt()-this.lastMessageReceived&&this.ws.close()},an/2),pr(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&&pr(this)}}const qa=new Map;class Ah{constructor(e){this.room=e,this.onmessage=null,this._onChange=s=>s.key===e&&this.onmessage!==null&&this.onmessage({data:Mo(s.newValue||"")}),Wc(this._onChange)}postMessage(e){No.setItem(this.room,Do(td(e)))}close(){Bc(this._onChange)}}const Lh=typeof BroadcastChannel>"u"?Ah:BroadcastChannel,ri=t=>Ve(qa,t,()=>{const e=bt(),s=new Lh(t);return s.onmessage=r=>e.forEach(i=>i(r.data,"broadcastchannel")),{bc:s,subs:e}}),Ih=(t,e)=>(ri(t).subs.add(e),e),Dh=(t,e)=>{const s=ri(t),r=s.subs.delete(e);return r&&s.subs.size===0&&(s.bc.close(),qa.delete(t)),r},Mh=(t,e,s=null)=>{const r=ri(t);r.bc.postMessage(e),r.subs.forEach(i=>i(e,s))},Oh=()=>{let t=!0;return(e,s)=>{if(t){t=!1;try{e()}finally{t=!0}}else s!==void 0&&s()}};function Ms(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 Yn={exports:{}},Wi;function Ph(){return Wi||(Wi=1,(function(t,e){(function(s){t.exports=s()})(function(){var s=Math.floor,r=Math.abs,i=Math.pow;return(function(){function o(c,d,l){function p(f,x){if(!d[f]){if(!c[f]){var y=typeof Ms=="function"&&Ms;if(!x&&y)return y(f,!0);if(g)return g(f,!0);var E=new Error("Cannot find module '"+f+"'");throw E.code="MODULE_NOT_FOUND",E}var I=d[f]={exports:{}};c[f][0].call(I.exports,function(v){var A=c[f][1][v];return p(A||v)},I,I.exports,o,c,d,l)}return d[f].exports}for(var g=typeof Ms=="function"&&Ms,u=0;u<l.length;u++)p(l[u]);return p}return o})()({1:[function(o,c,d){function l(k){var _=k.length;if(0<_%4)throw new Error("Invalid string. Length must be a multiple of 4");var T=k.indexOf("=");T===-1&&(T=_);var S=T===_?0:4-T%4;return[T,S]}function p(k,_,T){return 3*(_+T)/4-T}function g(k){var _,T,S=l(k),C=S[0],D=S[1],j=new I(p(k,C,D)),R=0,P=0<D?C-4:C;for(T=0;T<P;T+=4)_=E[k.charCodeAt(T)]<<18|E[k.charCodeAt(T+1)]<<12|E[k.charCodeAt(T+2)]<<6|E[k.charCodeAt(T+3)],j[R++]=255&_>>16,j[R++]=255&_>>8,j[R++]=255&_;return D===2&&(_=E[k.charCodeAt(T)]<<2|E[k.charCodeAt(T+1)]>>4,j[R++]=255&_),D===1&&(_=E[k.charCodeAt(T)]<<10|E[k.charCodeAt(T+1)]<<4|E[k.charCodeAt(T+2)]>>2,j[R++]=255&_>>8,j[R++]=255&_),j}function u(k){return y[63&k>>18]+y[63&k>>12]+y[63&k>>6]+y[63&k]}function f(k,_,T){for(var S,C=[],D=_;D<T;D+=3)S=(16711680&k[D]<<16)+(65280&k[D+1]<<8)+(255&k[D+2]),C.push(u(S));return C.join("")}function x(k){for(var _,T=k.length,S=T%3,C=[],D=16383,j=0,R=T-S;j<R;j+=D)C.push(f(k,j,j+D>R?R:j+D));return S===1?(_=k[T-1],C.push(y[_>>2]+y[63&_<<4]+"==")):S===2&&(_=(k[T-2]<<8)+k[T-1],C.push(y[_>>10]+y[63&_>>4]+y[63&_<<2]+"=")),C.join("")}d.byteLength=function(k){var _=l(k),T=_[0],S=_[1];return 3*(T+S)/4-S},d.toByteArray=g,d.fromByteArray=x;for(var y=[],E=[],I=typeof Uint8Array>"u"?Array:Uint8Array,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",A=0,m=v.length;A<m;++A)y[A]=v[A],E[v.charCodeAt(A)]=A;E[45]=62,E[95]=63},{}],2:[function(){},{}],3:[function(o,c,d){(function(){(function(){var l=String.fromCharCode,p=Math.min;function g(a){if(2147483647<a)throw new RangeError('The value "'+a+'" is invalid for option "size"');var h=new Uint8Array(a);return h.__proto__=u.prototype,h}function u(a,h,b){if(typeof a=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return E(a)}return f(a,h,b)}function f(a,h,b){if(typeof a=="string")return I(a,h);if(ArrayBuffer.isView(a))return v(a);if(a==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a);if(M(a,ArrayBuffer)||a&&M(a.buffer,ArrayBuffer))return A(a,h,b);if(typeof a=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var L=a.valueOf&&a.valueOf();if(L!=null&&L!==a)return u.from(L,h,b);var O=m(a);if(O)return O;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof a[Symbol.toPrimitive]=="function")return u.from(a[Symbol.toPrimitive]("string"),h,b);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a)}function x(a){if(typeof a!="number")throw new TypeError('"size" argument must be of type number');if(0>a)throw new RangeError('The value "'+a+'" is invalid for option "size"')}function y(a,h,b){return x(a),0>=a||h===void 0?g(a):typeof b=="string"?g(a).fill(h,b):g(a).fill(h)}function E(a){return x(a),g(0>a?0:0|k(a))}function I(a,h){if((typeof h!="string"||h==="")&&(h="utf8"),!u.isEncoding(h))throw new TypeError("Unknown encoding: "+h);var b=0|_(a,h),L=g(b),O=L.write(a,h);return O!==b&&(L=L.slice(0,O)),L}function v(a){for(var h=0>a.length?0:0|k(a.length),b=g(h),L=0;L<h;L+=1)b[L]=255&a[L];return b}function A(a,h,b){if(0>h||a.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(a.byteLength<h+(b||0))throw new RangeError('"length" is outside of buffer bounds');var L;return L=h===void 0&&b===void 0?new Uint8Array(a):b===void 0?new Uint8Array(a,h):new Uint8Array(a,h,b),L.__proto__=u.prototype,L}function m(a){if(u.isBuffer(a)){var h=0|k(a.length),b=g(h);return b.length===0||a.copy(b,0,0,h),b}return a.length===void 0?a.type==="Buffer"&&Array.isArray(a.data)?v(a.data):void 0:typeof a.length!="number"||W(a.length)?g(0):v(a)}function k(a){if(a>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|a}function _(a,h){if(u.isBuffer(a))return a.length;if(ArrayBuffer.isView(a)||M(a,ArrayBuffer))return a.byteLength;if(typeof a!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof a);var b=a.length,L=2<arguments.length&&arguments[2]===!0;if(!L&&b===0)return 0;for(var O=!1;;)switch(h){case"ascii":case"latin1":case"binary":return b;case"utf8":case"utf-8":return ve(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*b;case"hex":return b>>>1;case"base64":return ee(a).length;default:if(O)return L?-1:ve(a).length;h=(""+h).toLowerCase(),O=!0}}function T(a,h,b){var L=!1;if((h===void 0||0>h)&&(h=0),h>this.length||((b===void 0||b>this.length)&&(b=this.length),0>=b)||(b>>>=0,h>>>=0,b<=h))return"";for(a||(a="utf8");;)switch(a){case"hex":return se(this,h,b);case"utf8":case"utf-8":return J(this,h,b);case"ascii":return F(this,h,b);case"latin1":case"binary":return V(this,h,b);case"base64":return H(this,h,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Y(this,h,b);default:if(L)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),L=!0}}function S(a,h,b){var L=a[h];a[h]=a[b],a[b]=L}function C(a,h,b,L,O){if(a.length===0)return-1;if(typeof b=="string"?(L=b,b=0):2147483647<b?b=2147483647:-2147483648>b&&(b=-2147483648),b=+b,W(b)&&(b=O?0:a.length-1),0>b&&(b=a.length+b),b>=a.length){if(O)return-1;b=a.length-1}else if(0>b)if(O)b=0;else return-1;if(typeof h=="string"&&(h=u.from(h,L)),u.isBuffer(h))return h.length===0?-1:D(a,h,b,L,O);if(typeof h=="number")return h&=255,typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(a,h,b):Uint8Array.prototype.lastIndexOf.call(a,h,b):D(a,[h],b,L,O);throw new TypeError("val must be string, number or Buffer")}function D(a,h,b,L,O){function U(Mt,os){return re===1?Mt[os]:Mt.readUInt16BE(os*re)}var re=1,fe=a.length,_e=h.length;if(L!==void 0&&(L=(L+"").toLowerCase(),L==="ucs2"||L==="ucs-2"||L==="utf16le"||L==="utf-16le")){if(2>a.length||2>h.length)return-1;re=2,fe/=2,_e/=2,b/=2}var pe;if(O){var ue=-1;for(pe=b;pe<fe;pe++)if(U(a,pe)!==U(h,ue===-1?0:pe-ue))ue!==-1&&(pe-=pe-ue),ue=-1;else if(ue===-1&&(ue=pe),pe-ue+1===_e)return ue*re}else for(b+_e>fe&&(b=fe-_e),pe=b;0<=pe;pe--){for(var Pe=!0,vt=0;vt<_e;vt++)if(U(a,pe+vt)!==U(h,vt)){Pe=!1;break}if(Pe)return pe}return-1}function j(a,h,b,L){b=+b||0;var O=a.length-b;L?(L=+L,L>O&&(L=O)):L=O;var U=h.length;L>U/2&&(L=U/2);for(var re,fe=0;fe<L;++fe){if(re=parseInt(h.substr(2*fe,2),16),W(re))return fe;a[b+fe]=re}return fe}function R(a,h,b,L){return ae(ve(h,a.length-b),a,b,L)}function P(a,h,b,L){return ae(X(h),a,b,L)}function B(a,h,b,L){return P(a,h,b,L)}function z(a,h,b,L){return ae(ee(h),a,b,L)}function q(a,h,b,L){return ae(K(h,a.length-b),a,b,L)}function H(a,h,b){return h===0&&b===a.length?G.fromByteArray(a):G.fromByteArray(a.slice(h,b))}function J(a,h,b){b=p(a.length,b);for(var L=[],O=h;O<b;){var U=a[O],re=null,fe=239<U?4:223<U?3:191<U?2:1;if(O+fe<=b){var _e,pe,ue,Pe;fe===1?128>U&&(re=U):fe===2?(_e=a[O+1],(192&_e)==128&&(Pe=(31&U)<<6|63&_e,127<Pe&&(re=Pe))):fe===3?(_e=a[O+1],pe=a[O+2],(192&_e)==128&&(192&pe)==128&&(Pe=(15&U)<<12|(63&_e)<<6|63&pe,2047<Pe&&(55296>Pe||57343<Pe)&&(re=Pe))):fe===4&&(_e=a[O+1],pe=a[O+2],ue=a[O+3],(192&_e)==128&&(192&pe)==128&&(192&ue)==128&&(Pe=(15&U)<<18|(63&_e)<<12|(63&pe)<<6|63&ue,65535<Pe&&1114112>Pe&&(re=Pe)))}re===null?(re=65533,fe=1):65535<re&&(re-=65536,L.push(55296|1023&re>>>10),re=56320|1023&re),L.push(re),O+=fe}return $(L)}function $(a){var h=a.length;if(h<=4096)return l.apply(String,a);for(var b="",L=0;L<h;)b+=l.apply(String,a.slice(L,L+=4096));return b}function F(a,h,b){var L="";b=p(a.length,b);for(var O=h;O<b;++O)L+=l(127&a[O]);return L}function V(a,h,b){var L="";b=p(a.length,b);for(var O=h;O<b;++O)L+=l(a[O]);return L}function se(a,h,b){var L=a.length;(!h||0>h)&&(h=0),(!b||0>b||b>L)&&(b=L);for(var O="",U=h;U<b;++U)O+=xe(a[U]);return O}function Y(a,h,b){for(var L=a.slice(h,b),O="",U=0;U<L.length;U+=2)O+=l(L[U]+256*L[U+1]);return O}function te(a,h,b){if(a%1!=0||0>a)throw new RangeError("offset is not uint");if(a+h>b)throw new RangeError("Trying to access beyond buffer length")}function Q(a,h,b,L,O,U){if(!u.isBuffer(a))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>O||h<U)throw new RangeError('"value" argument is out of bounds');if(b+L>a.length)throw new RangeError("Index out of range")}function be(a,h,b,L){if(b+L>a.length)throw new RangeError("Index out of range");if(0>b)throw new RangeError("Index out of range")}function Ce(a,h,b,L,O){return h=+h,b>>>=0,O||be(a,h,b,4),ne.write(a,h,b,L,23,4),b+4}function ce(a,h,b,L,O){return h=+h,b>>>=0,O||be(a,h,b,8),ne.write(a,h,b,L,52,8),b+8}function ye(a){if(a=a.split("=")[0],a=a.trim().replace(N,""),2>a.length)return"";for(;a.length%4!=0;)a+="=";return a}function xe(a){return 16>a?"0"+a.toString(16):a.toString(16)}function ve(a,h){h=h||1/0;for(var b,L=a.length,O=null,U=[],re=0;re<L;++re){if(b=a.charCodeAt(re),55295<b&&57344>b){if(!O){if(56319<b){-1<(h-=3)&&U.push(239,191,189);continue}else if(re+1===L){-1<(h-=3)&&U.push(239,191,189);continue}O=b;continue}if(56320>b){-1<(h-=3)&&U.push(239,191,189),O=b;continue}b=(O-55296<<10|b-56320)+65536}else O&&-1<(h-=3)&&U.push(239,191,189);if(O=null,128>b){if(0>(h-=1))break;U.push(b)}else if(2048>b){if(0>(h-=2))break;U.push(192|b>>6,128|63&b)}else if(65536>b){if(0>(h-=3))break;U.push(224|b>>12,128|63&b>>6,128|63&b)}else if(1114112>b){if(0>(h-=4))break;U.push(240|b>>18,128|63&b>>12,128|63&b>>6,128|63&b)}else throw new Error("Invalid code point")}return U}function X(a){for(var h=[],b=0;b<a.length;++b)h.push(255&a.charCodeAt(b));return h}function K(a,h){for(var b,L,O,U=[],re=0;re<a.length&&!(0>(h-=2));++re)b=a.charCodeAt(re),L=b>>8,O=b%256,U.push(O),U.push(L);return U}function ee(a){return G.toByteArray(ye(a))}function ae(a,h,b,L){for(var O=0;O<L&&!(O+b>=h.length||O>=a.length);++O)h[O+b]=a[O];return O}function M(a,h){return a instanceof h||a!=null&&a.constructor!=null&&a.constructor.name!=null&&a.constructor.name===h.name}function W(a){return a!==a}var G=o("base64-js"),ne=o("ieee754");d.Buffer=u,d.SlowBuffer=function(a){return+a!=a&&(a=0),u.alloc(+a)},d.INSPECT_MAX_BYTES=50,d.kMaxLength=2147483647,u.TYPED_ARRAY_SUPPORT=(function(){try{var a=new Uint8Array(1);return a.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},a.foo()===42}catch{return!1}})(),u.TYPED_ARRAY_SUPPORT||typeof console>"u"||typeof console.error!="function"||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){return u.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){return u.isBuffer(this)?this.byteOffset:void 0}}),typeof Symbol<"u"&&Symbol.species!=null&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),u.poolSize=8192,u.from=function(a,h,b){return f(a,h,b)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(a,h,b){return y(a,h,b)},u.allocUnsafe=function(a){return E(a)},u.allocUnsafeSlow=function(a){return E(a)},u.isBuffer=function(a){return a!=null&&a._isBuffer===!0&&a!==u.prototype},u.compare=function(a,h){if(M(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),M(h,Uint8Array)&&(h=u.from(h,h.offset,h.byteLength)),!u.isBuffer(a)||!u.isBuffer(h))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===h)return 0;for(var b=a.length,L=h.length,O=0,U=p(b,L);O<U;++O)if(a[O]!==h[O]){b=a[O],L=h[O];break}return b<L?-1:L<b?1:0},u.isEncoding=function(a){switch((a+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(a,h){if(!Array.isArray(a))throw new TypeError('"list" argument must be an Array of Buffers');if(a.length===0)return u.alloc(0);var b;if(h===void 0)for(h=0,b=0;b<a.length;++b)h+=a[b].length;var L=u.allocUnsafe(h),O=0;for(b=0;b<a.length;++b){var U=a[b];if(M(U,Uint8Array)&&(U=u.from(U)),!u.isBuffer(U))throw new TypeError('"list" argument must be an Array of Buffers');U.copy(L,O),O+=U.length}return L},u.byteLength=_,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var a=this.length;if(a%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var h=0;h<a;h+=2)S(this,h,h+1);return this},u.prototype.swap32=function(){var a=this.length;if(a%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var h=0;h<a;h+=4)S(this,h,h+3),S(this,h+1,h+2);return this},u.prototype.swap64=function(){var a=this.length;if(a%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var h=0;h<a;h+=8)S(this,h,h+7),S(this,h+1,h+6),S(this,h+2,h+5),S(this,h+3,h+4);return this},u.prototype.toString=function(){var a=this.length;return a===0?"":arguments.length===0?J(this,0,a):T.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(a){if(!u.isBuffer(a))throw new TypeError("Argument must be a Buffer");return this===a||u.compare(this,a)===0},u.prototype.inspect=function(){var a="",h=d.INSPECT_MAX_BYTES;return a=this.toString("hex",0,h).replace(/(.{2})/g,"$1 ").trim(),this.length>h&&(a+=" ... "),"<Buffer "+a+">"},u.prototype.compare=function(a,h,b,L,O){if(M(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),!u.isBuffer(a))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof a);if(h===void 0&&(h=0),b===void 0&&(b=a?a.length:0),L===void 0&&(L=0),O===void 0&&(O=this.length),0>h||b>a.length||0>L||O>this.length)throw new RangeError("out of range index");if(L>=O&&h>=b)return 0;if(L>=O)return-1;if(h>=b)return 1;if(h>>>=0,b>>>=0,L>>>=0,O>>>=0,this===a)return 0;for(var U=O-L,re=b-h,fe=p(U,re),_e=this.slice(L,O),pe=a.slice(h,b),ue=0;ue<fe;++ue)if(_e[ue]!==pe[ue]){U=_e[ue],re=pe[ue];break}return U<re?-1:re<U?1:0},u.prototype.includes=function(a,h,b){return this.indexOf(a,h,b)!==-1},u.prototype.indexOf=function(a,h,b){return C(this,a,h,b,!0)},u.prototype.lastIndexOf=function(a,h,b){return C(this,a,h,b,!1)},u.prototype.write=function(a,h,b,L){if(h===void 0)L="utf8",b=this.length,h=0;else if(b===void 0&&typeof h=="string")L=h,b=this.length,h=0;else if(isFinite(h))h>>>=0,isFinite(b)?(b>>>=0,L===void 0&&(L="utf8")):(L=b,b=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var O=this.length-h;if((b===void 0||b>O)&&(b=O),0<a.length&&(0>b||0>h)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");L||(L="utf8");for(var U=!1;;)switch(L){case"hex":return j(this,a,h,b);case"utf8":case"utf-8":return R(this,a,h,b);case"ascii":return P(this,a,h,b);case"latin1":case"binary":return B(this,a,h,b);case"base64":return z(this,a,h,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,a,h,b);default:if(U)throw new TypeError("Unknown encoding: "+L);L=(""+L).toLowerCase(),U=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},u.prototype.slice=function(a,h){var b=this.length;a=~~a,h=h===void 0?b:~~h,0>a?(a+=b,0>a&&(a=0)):a>b&&(a=b),0>h?(h+=b,0>h&&(h=0)):h>b&&(h=b),h<a&&(h=a);var L=this.subarray(a,h);return L.__proto__=u.prototype,L},u.prototype.readUIntLE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var L=this[a],O=1,U=0;++U<h&&(O*=256);)L+=this[a+U]*O;return L},u.prototype.readUIntBE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var L=this[a+--h],O=1;0<h&&(O*=256);)L+=this[a+--h]*O;return L},u.prototype.readUInt8=function(a,h){return a>>>=0,h||te(a,1,this.length),this[a]},u.prototype.readUInt16LE=function(a,h){return a>>>=0,h||te(a,2,this.length),this[a]|this[a+1]<<8},u.prototype.readUInt16BE=function(a,h){return a>>>=0,h||te(a,2,this.length),this[a]<<8|this[a+1]},u.prototype.readUInt32LE=function(a,h){return a>>>=0,h||te(a,4,this.length),(this[a]|this[a+1]<<8|this[a+2]<<16)+16777216*this[a+3]},u.prototype.readUInt32BE=function(a,h){return a>>>=0,h||te(a,4,this.length),16777216*this[a]+(this[a+1]<<16|this[a+2]<<8|this[a+3])},u.prototype.readIntLE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var L=this[a],O=1,U=0;++U<h&&(O*=256);)L+=this[a+U]*O;return O*=128,L>=O&&(L-=i(2,8*h)),L},u.prototype.readIntBE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var L=h,O=1,U=this[a+--L];0<L&&(O*=256);)U+=this[a+--L]*O;return O*=128,U>=O&&(U-=i(2,8*h)),U},u.prototype.readInt8=function(a,h){return a>>>=0,h||te(a,1,this.length),128&this[a]?-1*(255-this[a]+1):this[a]},u.prototype.readInt16LE=function(a,h){a>>>=0,h||te(a,2,this.length);var b=this[a]|this[a+1]<<8;return 32768&b?4294901760|b:b},u.prototype.readInt16BE=function(a,h){a>>>=0,h||te(a,2,this.length);var b=this[a+1]|this[a]<<8;return 32768&b?4294901760|b:b},u.prototype.readInt32LE=function(a,h){return a>>>=0,h||te(a,4,this.length),this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24},u.prototype.readInt32BE=function(a,h){return a>>>=0,h||te(a,4,this.length),this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]},u.prototype.readFloatLE=function(a,h){return a>>>=0,h||te(a,4,this.length),ne.read(this,a,!0,23,4)},u.prototype.readFloatBE=function(a,h){return a>>>=0,h||te(a,4,this.length),ne.read(this,a,!1,23,4)},u.prototype.readDoubleLE=function(a,h){return a>>>=0,h||te(a,8,this.length),ne.read(this,a,!0,52,8)},u.prototype.readDoubleBE=function(a,h){return a>>>=0,h||te(a,8,this.length),ne.read(this,a,!1,52,8)},u.prototype.writeUIntLE=function(a,h,b,L){if(a=+a,h>>>=0,b>>>=0,!L){var O=i(2,8*b)-1;Q(this,a,h,b,O,0)}var U=1,re=0;for(this[h]=255&a;++re<b&&(U*=256);)this[h+re]=255&a/U;return h+b},u.prototype.writeUIntBE=function(a,h,b,L){if(a=+a,h>>>=0,b>>>=0,!L){var O=i(2,8*b)-1;Q(this,a,h,b,O,0)}var U=b-1,re=1;for(this[h+U]=255&a;0<=--U&&(re*=256);)this[h+U]=255&a/re;return h+b},u.prototype.writeUInt8=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,1,255,0),this[h]=255&a,h+1},u.prototype.writeUInt16LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,65535,0),this[h]=255&a,this[h+1]=a>>>8,h+2},u.prototype.writeUInt16BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,65535,0),this[h]=a>>>8,this[h+1]=255&a,h+2},u.prototype.writeUInt32LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,4,4294967295,0),this[h+3]=a>>>24,this[h+2]=a>>>16,this[h+1]=a>>>8,this[h]=255&a,h+4},u.prototype.writeUInt32BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,4,4294967295,0),this[h]=a>>>24,this[h+1]=a>>>16,this[h+2]=a>>>8,this[h+3]=255&a,h+4},u.prototype.writeIntLE=function(a,h,b,L){if(a=+a,h>>>=0,!L){var O=i(2,8*b-1);Q(this,a,h,b,O-1,-O)}var U=0,re=1,fe=0;for(this[h]=255&a;++U<b&&(re*=256);)0>a&&fe===0&&this[h+U-1]!==0&&(fe=1),this[h+U]=255&(a/re>>0)-fe;return h+b},u.prototype.writeIntBE=function(a,h,b,L){if(a=+a,h>>>=0,!L){var O=i(2,8*b-1);Q(this,a,h,b,O-1,-O)}var U=b-1,re=1,fe=0;for(this[h+U]=255&a;0<=--U&&(re*=256);)0>a&&fe===0&&this[h+U+1]!==0&&(fe=1),this[h+U]=255&(a/re>>0)-fe;return h+b},u.prototype.writeInt8=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,1,127,-128),0>a&&(a=255+a+1),this[h]=255&a,h+1},u.prototype.writeInt16LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,32767,-32768),this[h]=255&a,this[h+1]=a>>>8,h+2},u.prototype.writeInt16BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,32767,-32768),this[h]=a>>>8,this[h+1]=255&a,h+2},u.prototype.writeInt32LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,4,2147483647,-2147483648),this[h]=255&a,this[h+1]=a>>>8,this[h+2]=a>>>16,this[h+3]=a>>>24,h+4},u.prototype.writeInt32BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,4,2147483647,-2147483648),0>a&&(a=4294967295+a+1),this[h]=a>>>24,this[h+1]=a>>>16,this[h+2]=a>>>8,this[h+3]=255&a,h+4},u.prototype.writeFloatLE=function(a,h,b){return Ce(this,a,h,!0,b)},u.prototype.writeFloatBE=function(a,h,b){return Ce(this,a,h,!1,b)},u.prototype.writeDoubleLE=function(a,h,b){return ce(this,a,h,!0,b)},u.prototype.writeDoubleBE=function(a,h,b){return ce(this,a,h,!1,b)},u.prototype.copy=function(a,h,b,L){if(!u.isBuffer(a))throw new TypeError("argument should be a Buffer");if(b||(b=0),L||L===0||(L=this.length),h>=a.length&&(h=a.length),h||(h=0),0<L&&L<b&&(L=b),L===b||a.length===0||this.length===0)return 0;if(0>h)throw new RangeError("targetStart out of bounds");if(0>b||b>=this.length)throw new RangeError("Index out of range");if(0>L)throw new RangeError("sourceEnd out of bounds");L>this.length&&(L=this.length),a.length-h<L-b&&(L=a.length-h+b);var O=L-b;if(this===a&&typeof Uint8Array.prototype.copyWithin=="function")this.copyWithin(h,b,L);else if(this===a&&b<h&&h<L)for(var U=O-1;0<=U;--U)a[U+h]=this[U+b];else Uint8Array.prototype.set.call(a,this.subarray(b,L),h);return O},u.prototype.fill=function(a,h,b,L){if(typeof a=="string"){if(typeof h=="string"?(L=h,h=0,b=this.length):typeof b=="string"&&(L=b,b=this.length),L!==void 0&&typeof L!="string")throw new TypeError("encoding must be a string");if(typeof L=="string"&&!u.isEncoding(L))throw new TypeError("Unknown encoding: "+L);if(a.length===1){var O=a.charCodeAt(0);(L==="utf8"&&128>O||L==="latin1")&&(a=O)}}else typeof a=="number"&&(a&=255);if(0>h||this.length<h||this.length<b)throw new RangeError("Out of range index");if(b<=h)return this;h>>>=0,b=b===void 0?this.length:b>>>0,a||(a=0);var U;if(typeof a=="number")for(U=h;U<b;++U)this[U]=a;else{var re=u.isBuffer(a)?a:u.from(a,L),fe=re.length;if(fe===0)throw new TypeError('The value "'+a+'" is invalid for argument "value"');for(U=0;U<b-h;++U)this[U+h]=re[U%fe]}return this};var N=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,o("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(o,c,d){(function(l){(function(){function p(){let u;try{u=d.storage.getItem("debug")}catch{}return!u&&typeof l<"u"&&"env"in l&&(u=l.env.DEBUG),u}d.formatArgs=function(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+c.exports.humanize(this.diff),!this.useColors)return;const f="color: "+this.color;u.splice(1,0,f,"color: inherit");let x=0,y=0;u[0].replace(/%[a-zA-Z%]/g,E=>{E==="%%"||(x++,E==="%c"&&(y=x))}),u.splice(y,0,f)},d.save=function(u){try{u?d.storage.setItem("debug",u):d.storage.removeItem("debug")}catch{}},d.load=p,d.useColors=function(){return!!(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))||!(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},d.storage=(function(){try{return localStorage}catch{}})(),d.destroy=(()=>{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),d.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],d.log=console.debug||console.log||(()=>{}),c.exports=o("./common")(d);const{formatters:g}=c.exports;g.j=function(u){try{return JSON.stringify(u)}catch(f){return"[UnexpectedJSONParseError]: "+f.message}}}).call(this)}).call(this,o("_process"))},{"./common":5,_process:12}],5:[function(o,c){c.exports=function(d){function l(u){function f(...E){if(!f.enabled)return;const I=f,v=+new Date,A=v-(x||v);I.diff=A,I.prev=x,I.curr=v,x=v,E[0]=l.coerce(E[0]),typeof E[0]!="string"&&E.unshift("%O");let m=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(_,T)=>{if(_==="%%")return"%";m++;const S=l.formatters[T];if(typeof S=="function"){const C=E[m];_=S.call(I,C),E.splice(m,1),m--}return _}),l.formatArgs.call(I,E),(I.log||l.log).apply(I,E)}let x,y=null;return f.namespace=u,f.useColors=l.useColors(),f.color=l.selectColor(u),f.extend=p,f.destroy=l.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>y===null?l.enabled(u):y,set:E=>{y=E}}),typeof l.init=="function"&&l.init(f),f}function p(u,f){const x=l(this.namespace+(typeof f>"u"?":":f)+u);return x.log=this.log,x}function g(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}return l.debug=l,l.default=l,l.coerce=function(u){return u instanceof Error?u.stack||u.message:u},l.disable=function(){const u=[...l.names.map(g),...l.skips.map(g).map(f=>"-"+f)].join(",");return l.enable(""),u},l.enable=function(u){l.save(u),l.names=[],l.skips=[];let f;const x=(typeof u=="string"?u:"").split(/[\s,]+/),y=x.length;for(f=0;f<y;f++)x[f]&&(u=x[f].replace(/\*/g,".*?"),u[0]==="-"?l.skips.push(new RegExp("^"+u.substr(1)+"$")):l.names.push(new RegExp("^"+u+"$")))},l.enabled=function(u){if(u[u.length-1]==="*")return!0;let f,x;for(f=0,x=l.skips.length;f<x;f++)if(l.skips[f].test(u))return!1;for(f=0,x=l.names.length;f<x;f++)if(l.names[f].test(u))return!0;return!1},l.humanize=o("ms"),l.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(d).forEach(u=>{l[u]=d[u]}),l.names=[],l.skips=[],l.formatters={},l.selectColor=function(u){let f=0;for(let x=0;x<u.length;x++)f=(f<<5)-f+u.charCodeAt(x),f|=0;return l.colors[r(f)%l.colors.length]},l.enable(l.load()),l}},{ms:11}],6:[function(o,c){function d(l,p){for(const g in p)Object.defineProperty(l,g,{value:p[g],enumerable:!0,configurable:!0});return l}c.exports=function(l,p,g){if(!l||typeof l=="string")throw new TypeError("Please pass an Error to err-code");g||(g={}),typeof p=="object"&&(g=p,p=""),p&&(g.code=p);try{return d(l,g)}catch{g.message=l.message,g.stack=l.stack;const f=function(){};return f.prototype=Object.create(Object.getPrototypeOf(l)),d(new f,g)}}},{}],7:[function(o,c){function d(j){console&&console.warn&&console.warn(j)}function l(){l.init.call(this)}function p(j){if(typeof j!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof j)}function g(j){return j._maxListeners===void 0?l.defaultMaxListeners:j._maxListeners}function u(j,R,P,B){var z,q,H;if(p(P),q=j._events,q===void 0?(q=j._events=Object.create(null),j._eventsCount=0):(q.newListener!==void 0&&(j.emit("newListener",R,P.listener?P.listener:P),q=j._events),H=q[R]),H===void 0)H=q[R]=P,++j._eventsCount;else if(typeof H=="function"?H=q[R]=B?[P,H]:[H,P]:B?H.unshift(P):H.push(P),z=g(j),0<z&&H.length>z&&!H.warned){H.warned=!0;var J=new Error("Possible EventEmitter memory leak detected. "+H.length+" "+(R+" listeners added. Use emitter.setMaxListeners() to increase limit"));J.name="MaxListenersExceededWarning",J.emitter=j,J.type=R,J.count=H.length,d(J)}return j}function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function x(j,R,P){var B={fired:!1,wrapFn:void 0,target:j,type:R,listener:P},z=f.bind(B);return z.listener=P,B.wrapFn=z,z}function y(j,R,P){var B=j._events;if(B===void 0)return[];var z=B[R];return z===void 0?[]:typeof z=="function"?P?[z.listener||z]:[z]:P?A(z):I(z,z.length)}function E(j){var R=this._events;if(R!==void 0){var P=R[j];if(typeof P=="function")return 1;if(P!==void 0)return P.length}return 0}function I(j,R){for(var P=Array(R),B=0;B<R;++B)P[B]=j[B];return P}function v(j,R){for(;R+1<j.length;R++)j[R]=j[R+1];j.pop()}function A(j){for(var R=Array(j.length),P=0;P<R.length;++P)R[P]=j[P].listener||j[P];return R}function m(j,R,P){typeof j.on=="function"&&k(j,"error",R,P)}function k(j,R,P,B){if(typeof j.on=="function")B.once?j.once(R,P):j.on(R,P);else if(typeof j.addEventListener=="function")j.addEventListener(R,function z(q){B.once&&j.removeEventListener(R,z),P(q)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof j)}var _,T=typeof Reflect=="object"?Reflect:null,S=T&&typeof T.apply=="function"?T.apply:function(j,R,P){return Function.prototype.apply.call(j,R,P)};_=T&&typeof T.ownKeys=="function"?T.ownKeys:Object.getOwnPropertySymbols?function(j){return Object.getOwnPropertyNames(j).concat(Object.getOwnPropertySymbols(j))}:function(j){return Object.getOwnPropertyNames(j)};var C=Number.isNaN||function(j){return j!==j};c.exports=l,c.exports.once=function(j,R){return new Promise(function(P,B){function z(H){j.removeListener(R,q),B(H)}function q(){typeof j.removeListener=="function"&&j.removeListener("error",z),P([].slice.call(arguments))}k(j,R,q,{once:!0}),R!=="error"&&m(j,z,{once:!0})})},l.EventEmitter=l,l.prototype._events=void 0,l.prototype._eventsCount=0,l.prototype._maxListeners=void 0;var D=10;Object.defineProperty(l,"defaultMaxListeners",{enumerable:!0,get:function(){return D},set:function(j){if(typeof j!="number"||0>j||C(j))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+j+".");D=j}}),l.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},l.prototype.setMaxListeners=function(j){if(typeof j!="number"||0>j||C(j))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+j+".");return this._maxListeners=j,this},l.prototype.getMaxListeners=function(){return g(this)},l.prototype.emit=function(j){for(var R=[],P=1;P<arguments.length;P++)R.push(arguments[P]);var B=j==="error",z=this._events;if(z!==void 0)B=B&&z.error===void 0;else if(!B)return!1;if(B){var q;if(0<R.length&&(q=R[0]),q instanceof Error)throw q;var H=new Error("Unhandled error."+(q?" ("+q.message+")":""));throw H.context=q,H}var J=z[j];if(J===void 0)return!1;if(typeof J=="function")S(J,this,R);else for(var $=J.length,F=I(J,$),P=0;P<$;++P)S(F[P],this,R);return!0},l.prototype.addListener=function(j,R){return u(this,j,R,!1)},l.prototype.on=l.prototype.addListener,l.prototype.prependListener=function(j,R){return u(this,j,R,!0)},l.prototype.once=function(j,R){return p(R),this.on(j,x(this,j,R)),this},l.prototype.prependOnceListener=function(j,R){return p(R),this.prependListener(j,x(this,j,R)),this},l.prototype.removeListener=function(j,R){var P,B,z,q,H;if(p(R),B=this._events,B===void 0)return this;if(P=B[j],P===void 0)return this;if(P===R||P.listener===R)--this._eventsCount==0?this._events=Object.create(null):(delete B[j],B.removeListener&&this.emit("removeListener",j,P.listener||R));else if(typeof P!="function"){for(z=-1,q=P.length-1;0<=q;q--)if(P[q]===R||P[q].listener===R){H=P[q].listener,z=q;break}if(0>z)return this;z===0?P.shift():v(P,z),P.length===1&&(B[j]=P[0]),B.removeListener!==void 0&&this.emit("removeListener",j,H||R)}return this},l.prototype.off=l.prototype.removeListener,l.prototype.removeAllListeners=function(j){var R,P,B;if(P=this._events,P===void 0)return this;if(P.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):P[j]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete P[j]),this;if(arguments.length===0){var z,q=Object.keys(P);for(B=0;B<q.length;++B)z=q[B],z!=="removeListener"&&this.removeAllListeners(z);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(R=P[j],typeof R=="function")this.removeListener(j,R);else if(R!==void 0)for(B=R.length-1;0<=B;B--)this.removeListener(j,R[B]);return this},l.prototype.listeners=function(j){return y(this,j,!0)},l.prototype.rawListeners=function(j){return y(this,j,!1)},l.listenerCount=function(j,R){return typeof j.listenerCount=="function"?j.listenerCount(R):E.call(j,R)},l.prototype.listenerCount=E,l.prototype.eventNames=function(){return 0<this._eventsCount?_(this._events):[]}},{}],8:[function(o,c){c.exports=function(){if(typeof globalThis>"u")return null;var d={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return d.RTCPeerConnection?d:null}},{}],9:[function(o,c,d){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */d.read=function(l,p,g,u,f){var x,y,E=8*f-u-1,I=(1<<E)-1,v=I>>1,A=-7,m=g?f-1:0,k=g?-1:1,_=l[p+m];for(m+=k,x=_&(1<<-A)-1,_>>=-A,A+=E;0<A;x=256*x+l[p+m],m+=k,A-=8);for(y=x&(1<<-A)-1,x>>=-A,A+=u;0<A;y=256*y+l[p+m],m+=k,A-=8);if(x===0)x=1-v;else{if(x===I)return y?NaN:(_?-1:1)*(1/0);y+=i(2,u),x-=v}return(_?-1:1)*y*i(2,x-u)},d.write=function(l,p,g,u,f,x){var y,E,I,v=Math.LN2,A=Math.log,m=8*x-f-1,k=(1<<m)-1,_=k>>1,T=f===23?i(2,-24)-i(2,-77):0,S=u?0:x-1,C=u?1:-1,D=0>p||p===0&&0>1/p?1:0;for(p=r(p),isNaN(p)||p===1/0?(E=isNaN(p)?1:0,y=k):(y=s(A(p)/v),1>p*(I=i(2,-y))&&(y--,I*=2),p+=1<=y+_?T/I:T*i(2,1-_),2<=p*I&&(y++,I/=2),y+_>=k?(E=0,y=k):1<=y+_?(E=(p*I-1)*i(2,f),y+=_):(E=p*i(2,_-1)*i(2,f),y=0));8<=f;l[g+S]=255&E,S+=C,E/=256,f-=8);for(y=y<<f|E,m+=f;0<m;l[g+S]=255&y,S+=C,y/=256,m-=8);l[g+S-C]|=128*D}},{}],10:[function(o,c){c.exports=typeof Object.create=="function"?function(d,l){l&&(d.super_=l,d.prototype=Object.create(l.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}))}:function(d,l){if(l){d.super_=l;var p=function(){};p.prototype=l.prototype,d.prototype=new p,d.prototype.constructor=d}}},{}],11:[function(o,c){var d=Math.round;function l(f){if(f+="",!(100<f.length)){var x=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(x){var y=parseFloat(x[1]),E=(x[2]||"ms").toLowerCase();return E==="years"||E==="year"||E==="yrs"||E==="yr"||E==="y"?315576e5*y:E==="weeks"||E==="week"||E==="w"?6048e5*y:E==="days"||E==="day"||E==="d"?864e5*y:E==="hours"||E==="hour"||E==="hrs"||E==="hr"||E==="h"?36e5*y:E==="minutes"||E==="minute"||E==="mins"||E==="min"||E==="m"?6e4*y:E==="seconds"||E==="second"||E==="secs"||E==="sec"||E==="s"?1e3*y:E==="milliseconds"||E==="millisecond"||E==="msecs"||E==="msec"||E==="ms"?y:void 0}}}function p(f){var x=r(f);return 864e5<=x?d(f/864e5)+"d":36e5<=x?d(f/36e5)+"h":6e4<=x?d(f/6e4)+"m":1e3<=x?d(f/1e3)+"s":f+"ms"}function g(f){var x=r(f);return 864e5<=x?u(f,x,864e5,"day"):36e5<=x?u(f,x,36e5,"hour"):6e4<=x?u(f,x,6e4,"minute"):1e3<=x?u(f,x,1e3,"second"):f+" ms"}function u(f,x,y,E){return d(f/y)+" "+E+(x>=1.5*y?"s":"")}c.exports=function(f,x){x=x||{};var y=typeof f;if(y=="string"&&0<f.length)return l(f);if(y==="number"&&isFinite(f))return x.long?g(f):p(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))}},{}],12:[function(o,c){function d(){throw new Error("setTimeout has not been defined")}function l(){throw new Error("clearTimeout has not been defined")}function p(T){if(E===setTimeout)return setTimeout(T,0);if((E===d||!E)&&setTimeout)return E=setTimeout,setTimeout(T,0);try{return E(T,0)}catch{try{return E.call(null,T,0)}catch{return E.call(this,T,0)}}}function g(T){if(I===clearTimeout)return clearTimeout(T);if((I===l||!I)&&clearTimeout)return I=clearTimeout,clearTimeout(T);try{return I(T)}catch{try{return I.call(null,T)}catch{return I.call(this,T)}}}function u(){k&&A&&(k=!1,A.length?m=A.concat(m):_=-1,m.length&&f())}function f(){if(!k){var T=p(u);k=!0;for(var S=m.length;S;){for(A=m,m=[];++_<S;)A&&A[_].run();_=-1,S=m.length}A=null,k=!1,g(T)}}function x(T,S){this.fun=T,this.array=S}function y(){}var E,I,v=c.exports={};(function(){try{E=typeof setTimeout=="function"?setTimeout:d}catch{E=d}try{I=typeof clearTimeout=="function"?clearTimeout:l}catch{I=l}})();var A,m=[],k=!1,_=-1;v.nextTick=function(T){var S=Array(arguments.length-1);if(1<arguments.length)for(var C=1;C<arguments.length;C++)S[C-1]=arguments[C];m.push(new x(T,S)),m.length!==1||k||p(f)},x.prototype.run=function(){this.fun.apply(null,this.array)},v.title="browser",v.browser=!0,v.env={},v.argv=[],v.version="",v.versions={},v.on=y,v.addListener=y,v.once=y,v.off=y,v.removeListener=y,v.removeAllListeners=y,v.emit=y,v.prependListener=y,v.prependOnceListener=y,v.listeners=function(){return[]},v.binding=function(){throw new Error("process.binding is not supported")},v.cwd=function(){return"/"},v.chdir=function(){throw new Error("process.chdir is not supported")},v.umask=function(){return 0}},{}],13:[function(o,c){(function(d){(function(){/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let l;c.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window>"u"?d:window):p=>(l||(l=Promise.resolve())).then(p).catch(g=>setTimeout(()=>{throw g},0))}).call(this)}).call(this,typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{}],14:[function(o,c){(function(d,l){(function(){var p=o("safe-buffer").Buffer,g=l.crypto||l.msCrypto;c.exports=g&&g.getRandomValues?function(u,f){if(u>4294967295)throw new RangeError("requested too many random bytes");var x=p.allocUnsafe(u);if(0<u)if(65536<u)for(var y=0;y<u;y+=65536)g.getRandomValues(x.slice(y,y+65536));else g.getRandomValues(x);return typeof f=="function"?d.nextTick(function(){f(null,x)}):x}:function(){throw new Error(`Secure random number generation is not supported by this browser.
37
- Use Chrome, Firefox or Internet Explorer 11`)}}).call(this)}).call(this,o("_process"),typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{_process:12,"safe-buffer":30}],15:[function(o,c){function d(y,E){y.prototype=Object.create(E.prototype),y.prototype.constructor=y,y.__proto__=E}function l(y,E,I){function v(m,k,_){return typeof E=="string"?E:E(m,k,_)}I||(I=Error);var A=(function(m){function k(_,T,S){return m.call(this,v(_,T,S))||this}return d(k,m),k})(I);A.prototype.name=I.name,A.prototype.code=y,x[y]=A}function p(y,E){if(Array.isArray(y)){var I=y.length;return y=y.map(function(v){return v+""}),2<I?"one of ".concat(E," ").concat(y.slice(0,I-1).join(", "),", or ")+y[I-1]:I===2?"one of ".concat(E," ").concat(y[0]," or ").concat(y[1]):"of ".concat(E," ").concat(y[0])}return"of ".concat(E," ").concat(y+"")}function g(y,E,I){return y.substr(0,E.length)===E}function u(y,E,I){return(I===void 0||I>y.length)&&(I=y.length),y.substring(I-E.length,I)===E}function f(y,E,I){return typeof I!="number"&&(I=0),!(I+E.length>y.length)&&y.indexOf(E,I)!==-1}var x={};l("ERR_INVALID_OPT_VALUE",function(y,E){return'The value "'+E+'" is invalid for option "'+y+'"'},TypeError),l("ERR_INVALID_ARG_TYPE",function(y,E,I){var v;typeof E=="string"&&g(E,"not ")?(v="must not be",E=E.replace(/^not /,"")):v="must be";var A;if(u(y," argument"))A="The ".concat(y," ").concat(v," ").concat(p(E,"type"));else{var m=f(y,".")?"property":"argument";A='The "'.concat(y,'" ').concat(m," ").concat(v," ").concat(p(E,"type"))}return A+=". Received type ".concat(typeof I),A},TypeError),l("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),l("ERR_METHOD_NOT_IMPLEMENTED",function(y){return"The "+y+" method is not implemented"}),l("ERR_STREAM_PREMATURE_CLOSE","Premature close"),l("ERR_STREAM_DESTROYED",function(y){return"Cannot call "+y+" after a stream was destroyed"}),l("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),l("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),l("ERR_STREAM_WRITE_AFTER_END","write after end"),l("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),l("ERR_UNKNOWN_ENCODING",function(y){return"Unknown encoding: "+y},TypeError),l("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),c.exports.codes=x},{}],16:[function(o,c){(function(d){(function(){function l(v){return this instanceof l?(f.call(this,v),x.call(this,v),this.allowHalfOpen=!0,void(v&&(v.readable===!1&&(this.readable=!1),v.writable===!1&&(this.writable=!1),v.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",p))))):new l(v)}function p(){this._writableState.ended||d.nextTick(g,this)}function g(v){v.end()}var u=Object.keys||function(v){var A=[];for(var m in v)A.push(m);return A};c.exports=l;var f=o("./_stream_readable"),x=o("./_stream_writable");o("inherits")(l,f);for(var y,E=u(x.prototype),I=0;I<E.length;I++)y=E[I],l.prototype[y]||(l.prototype[y]=x.prototype[y]);Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._writableState!==void 0&&this._readableState.destroyed&&this._writableState.destroyed},set:function(v){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=v,this._writableState.destroyed=v)}})}).call(this)}).call(this,o("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(o,c){function d(p){return this instanceof d?void l.call(this,p):new d(p)}c.exports=d;var l=o("./_stream_transform");o("inherits")(d,l),d.prototype._transform=function(p,g,u){u(null,p)}},{"./_stream_transform":19,inherits:10}],18:[function(o,c){(function(d,l){(function(){function p(N){return Y.from(N)}function g(N){return Y.isBuffer(N)||N instanceof te}function u(N,a,h){return typeof N.prependListener=="function"?N.prependListener(a,h):void(N._events&&N._events[a]?Array.isArray(N._events[a])?N._events[a].unshift(h):N._events[a]=[h,N._events[a]]:N.on(a,h))}function f(N,a,h){$=$||o("./_stream_duplex"),N=N||{},typeof h!="boolean"&&(h=a instanceof $),this.objectMode=!!N.objectMode,h&&(this.objectMode=this.objectMode||!!N.readableObjectMode),this.highWaterMark=X(this,N,"readableHighWaterMark",h),this.buffer=new ye,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=N.emitClose!==!1,this.autoDestroy=!!N.autoDestroy,this.destroyed=!1,this.defaultEncoding=N.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,N.encoding&&(!be&&(be=o("string_decoder/").StringDecoder),this.decoder=new be(N.encoding),this.encoding=N.encoding)}function x(N){if($=$||o("./_stream_duplex"),!(this instanceof x))return new x(N);var a=this instanceof $;this._readableState=new f(N,this,a),this.readable=!0,N&&(typeof N.read=="function"&&(this._read=N.read),typeof N.destroy=="function"&&(this._destroy=N.destroy)),se.call(this)}function y(N,a,h,b,L){F("readableAddChunk",a);var O=N._readableState;if(a===null)O.reading=!1,m(N,O);else{var U;if(L||(U=I(O,a)),U)G(N,U);else if(!(O.objectMode||a&&0<a.length))b||(O.reading=!1,T(N,O));else if(typeof a=="string"||O.objectMode||Object.getPrototypeOf(a)===Y.prototype||(a=p(a)),b)O.endEmitted?G(N,new W):E(N,O,a,!0);else if(O.ended)G(N,new ae);else{if(O.destroyed)return!1;O.reading=!1,O.decoder&&!h?(a=O.decoder.write(a),O.objectMode||a.length!==0?E(N,O,a,!1):T(N,O)):E(N,O,a,!1)}}return!O.ended&&(O.length<O.highWaterMark||O.length===0)}function E(N,a,h,b){a.flowing&&a.length===0&&!a.sync?(a.awaitDrain=0,N.emit("data",h)):(a.length+=a.objectMode?1:h.length,b?a.buffer.unshift(h):a.buffer.push(h),a.needReadable&&k(N)),T(N,a)}function I(N,a){var h;return g(a)||typeof a=="string"||a===void 0||N.objectMode||(h=new ee("chunk",["string","Buffer","Uint8Array"],a)),h}function v(N){return 1073741824<=N?N=1073741824:(N--,N|=N>>>1,N|=N>>>2,N|=N>>>4,N|=N>>>8,N|=N>>>16,N++),N}function A(N,a){return 0>=N||a.length===0&&a.ended?0:a.objectMode?1:N===N?(N>a.highWaterMark&&(a.highWaterMark=v(N)),N<=a.length?N:a.ended?a.length:(a.needReadable=!0,0)):a.flowing&&a.length?a.buffer.head.data.length:a.length}function m(N,a){if(F("onEofChunk"),!a.ended){if(a.decoder){var h=a.decoder.end();h&&h.length&&(a.buffer.push(h),a.length+=a.objectMode?1:h.length)}a.ended=!0,a.sync?k(N):(a.needReadable=!1,!a.emittedReadable&&(a.emittedReadable=!0,_(N)))}}function k(N){var a=N._readableState;F("emitReadable",a.needReadable,a.emittedReadable),a.needReadable=!1,a.emittedReadable||(F("emitReadable",a.flowing),a.emittedReadable=!0,d.nextTick(_,N))}function _(N){var a=N._readableState;F("emitReadable_",a.destroyed,a.length,a.ended),!a.destroyed&&(a.length||a.ended)&&(N.emit("readable"),a.emittedReadable=!1),a.needReadable=!a.flowing&&!a.ended&&a.length<=a.highWaterMark,B(N)}function T(N,a){a.readingMore||(a.readingMore=!0,d.nextTick(S,N,a))}function S(N,a){for(;!a.reading&&!a.ended&&(a.length<a.highWaterMark||a.flowing&&a.length===0);){var h=a.length;if(F("maybeReadMore read 0"),N.read(0),h===a.length)break}a.readingMore=!1}function C(N){return function(){var a=N._readableState;F("pipeOnDrain",a.awaitDrain),a.awaitDrain&&a.awaitDrain--,a.awaitDrain===0&&V(N,"data")&&(a.flowing=!0,B(N))}}function D(N){var a=N._readableState;a.readableListening=0<N.listenerCount("readable"),a.resumeScheduled&&!a.paused?a.flowing=!0:0<N.listenerCount("data")&&N.resume()}function j(N){F("readable nexttick read 0"),N.read(0)}function R(N,a){a.resumeScheduled||(a.resumeScheduled=!0,d.nextTick(P,N,a))}function P(N,a){F("resume",a.reading),a.reading||N.read(0),a.resumeScheduled=!1,N.emit("resume"),B(N),a.flowing&&!a.reading&&N.read(0)}function B(N){var a=N._readableState;for(F("flow",a.flowing);a.flowing&&N.read()!==null;);}function z(N,a){if(a.length===0)return null;var h;return a.objectMode?h=a.buffer.shift():!N||N>=a.length?(h=a.decoder?a.buffer.join(""):a.buffer.length===1?a.buffer.first():a.buffer.concat(a.length),a.buffer.clear()):h=a.buffer.consume(N,a.decoder),h}function q(N){var a=N._readableState;F("endReadable",a.endEmitted),a.endEmitted||(a.ended=!0,d.nextTick(H,a,N))}function H(N,a){if(F("endReadableNT",N.endEmitted,N.length),!N.endEmitted&&N.length===0&&(N.endEmitted=!0,a.readable=!1,a.emit("end"),N.autoDestroy)){var h=a._writableState;(!h||h.autoDestroy&&h.finished)&&a.destroy()}}function J(N,a){for(var h=0,b=N.length;h<b;h++)if(N[h]===a)return h;return-1}c.exports=x;var $;x.ReadableState=f;var F;o("events").EventEmitter;var V=function(N,a){return N.listeners(a).length},se=o("./internal/streams/stream"),Y=o("buffer").Buffer,te=l.Uint8Array||function(){},Q=o("util");F=Q&&Q.debuglog?Q.debuglog("stream"):function(){};var be,Ce,ce,ye=o("./internal/streams/buffer_list"),xe=o("./internal/streams/destroy"),ve=o("./internal/streams/state"),X=ve.getHighWaterMark,K=o("../errors").codes,ee=K.ERR_INVALID_ARG_TYPE,ae=K.ERR_STREAM_PUSH_AFTER_EOF,M=K.ERR_METHOD_NOT_IMPLEMENTED,W=K.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;o("inherits")(x,se);var G=xe.errorOrDestroy,ne=["error","close","destroy","pause","resume"];Object.defineProperty(x.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(N){this._readableState&&(this._readableState.destroyed=N)}}),x.prototype.destroy=xe.destroy,x.prototype._undestroy=xe.undestroy,x.prototype._destroy=function(N,a){a(N)},x.prototype.push=function(N,a){var h,b=this._readableState;return b.objectMode?h=!0:typeof N=="string"&&(a=a||b.defaultEncoding,a!==b.encoding&&(N=Y.from(N,a),a=""),h=!0),y(this,N,a,!1,h)},x.prototype.unshift=function(N){return y(this,N,null,!0,!1)},x.prototype.isPaused=function(){return this._readableState.flowing===!1},x.prototype.setEncoding=function(N){be||(be=o("string_decoder/").StringDecoder);var a=new be(N);this._readableState.decoder=a,this._readableState.encoding=this._readableState.decoder.encoding;for(var h=this._readableState.buffer.head,b="";h!==null;)b+=a.write(h.data),h=h.next;return this._readableState.buffer.clear(),b!==""&&this._readableState.buffer.push(b),this._readableState.length=b.length,this},x.prototype.read=function(N){F("read",N),N=parseInt(N,10);var a=this._readableState,h=N;if(N!==0&&(a.emittedReadable=!1),N===0&&a.needReadable&&((a.highWaterMark===0?0<a.length:a.length>=a.highWaterMark)||a.ended))return F("read: emitReadable",a.length,a.ended),a.length===0&&a.ended?q(this):k(this),null;if(N=A(N,a),N===0&&a.ended)return a.length===0&&q(this),null;var b=a.needReadable;F("need readable",b),(a.length===0||a.length-N<a.highWaterMark)&&(b=!0,F("length less than watermark",b)),a.ended||a.reading?(b=!1,F("reading or ended",b)):b&&(F("do read"),a.reading=!0,a.sync=!0,a.length===0&&(a.needReadable=!0),this._read(a.highWaterMark),a.sync=!1,!a.reading&&(N=A(h,a)));var L;return L=0<N?z(N,a):null,L===null?(a.needReadable=a.length<=a.highWaterMark,N=0):(a.length-=N,a.awaitDrain=0),a.length===0&&(!a.ended&&(a.needReadable=!0),h!==N&&a.ended&&q(this)),L!==null&&this.emit("data",L),L},x.prototype._read=function(){G(this,new M("_read()"))},x.prototype.pipe=function(N,a){function h(Ot,Pt){F("onunpipe"),Ot===pe&&Pt&&Pt.hasUnpiped===!1&&(Pt.hasUnpiped=!0,L())}function b(){F("onend"),N.end()}function L(){F("cleanup"),N.removeListener("close",re),N.removeListener("finish",fe),N.removeListener("drain",Mt),N.removeListener("error",U),N.removeListener("unpipe",h),pe.removeListener("end",b),pe.removeListener("end",_e),pe.removeListener("data",O),os=!0,ue.awaitDrain&&(!N._writableState||N._writableState.needDrain)&&Mt()}function O(Ot){F("ondata");var Pt=N.write(Ot);F("dest.write",Pt),Pt===!1&&((ue.pipesCount===1&&ue.pipes===N||1<ue.pipesCount&&J(ue.pipes,N)!==-1)&&!os&&(F("false write response, pause",ue.awaitDrain),ue.awaitDrain++),pe.pause())}function U(Ot){F("onerror",Ot),_e(),N.removeListener("error",U),V(N,"error")===0&&G(N,Ot)}function re(){N.removeListener("finish",fe),_e()}function fe(){F("onfinish"),N.removeListener("close",re),_e()}function _e(){F("unpipe"),pe.unpipe(N)}var pe=this,ue=this._readableState;switch(ue.pipesCount){case 0:ue.pipes=N;break;case 1:ue.pipes=[ue.pipes,N];break;default:ue.pipes.push(N)}ue.pipesCount+=1,F("pipe count=%d opts=%j",ue.pipesCount,a);var Pe=(!a||a.end!==!1)&&N!==d.stdout&&N!==d.stderr,vt=Pe?b:_e;ue.endEmitted?d.nextTick(vt):pe.once("end",vt),N.on("unpipe",h);var Mt=C(pe);N.on("drain",Mt);var os=!1;return pe.on("data",O),u(N,"error",U),N.once("close",re),N.once("finish",fe),N.emit("pipe",pe),ue.flowing||(F("pipe resume"),pe.resume()),N},x.prototype.unpipe=function(N){var a=this._readableState,h={hasUnpiped:!1};if(a.pipesCount===0)return this;if(a.pipesCount===1)return N&&N!==a.pipes?this:(N||(N=a.pipes),a.pipes=null,a.pipesCount=0,a.flowing=!1,N&&N.emit("unpipe",this,h),this);if(!N){var b=a.pipes,L=a.pipesCount;a.pipes=null,a.pipesCount=0,a.flowing=!1;for(var O=0;O<L;O++)b[O].emit("unpipe",this,{hasUnpiped:!1});return this}var U=J(a.pipes,N);return U===-1?this:(a.pipes.splice(U,1),a.pipesCount-=1,a.pipesCount===1&&(a.pipes=a.pipes[0]),N.emit("unpipe",this,h),this)},x.prototype.on=function(N,a){var h=se.prototype.on.call(this,N,a),b=this._readableState;return N==="data"?(b.readableListening=0<this.listenerCount("readable"),b.flowing!==!1&&this.resume()):N=="readable"&&!b.endEmitted&&!b.readableListening&&(b.readableListening=b.needReadable=!0,b.flowing=!1,b.emittedReadable=!1,F("on readable",b.length,b.reading),b.length?k(this):!b.reading&&d.nextTick(j,this)),h},x.prototype.addListener=x.prototype.on,x.prototype.removeListener=function(N,a){var h=se.prototype.removeListener.call(this,N,a);return N==="readable"&&d.nextTick(D,this),h},x.prototype.removeAllListeners=function(N){var a=se.prototype.removeAllListeners.apply(this,arguments);return(N==="readable"||N===void 0)&&d.nextTick(D,this),a},x.prototype.resume=function(){var N=this._readableState;return N.flowing||(F("resume"),N.flowing=!N.readableListening,R(this,N)),N.paused=!1,this},x.prototype.pause=function(){return F("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(F("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},x.prototype.wrap=function(N){var a=this,h=this._readableState,b=!1;for(var L in N.on("end",function(){if(F("wrapped end"),h.decoder&&!h.ended){var U=h.decoder.end();U&&U.length&&a.push(U)}a.push(null)}),N.on("data",function(U){if(F("wrapped data"),h.decoder&&(U=h.decoder.write(U)),!(h.objectMode&&U==null)&&(h.objectMode||U&&U.length)){var re=a.push(U);re||(b=!0,N.pause())}}),N)this[L]===void 0&&typeof N[L]=="function"&&(this[L]=(function(U){return function(){return N[U].apply(N,arguments)}})(L));for(var O=0;O<ne.length;O++)N.on(ne[O],this.emit.bind(this,ne[O]));return this._read=function(U){F("wrapped _read",U),b&&(b=!1,N.resume())},this},typeof Symbol=="function"&&(x.prototype[Symbol.asyncIterator]=function(){return Ce===void 0&&(Ce=o("./internal/streams/async_iterator")),Ce(this)}),Object.defineProperty(x.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(x.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(x.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(N){this._readableState&&(this._readableState.flowing=N)}}),x._fromList=z,Object.defineProperty(x.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),typeof Symbol=="function"&&(x.from=function(N,a){return ce===void 0&&(ce=o("./internal/streams/from")),ce(x,N,a)})}).call(this)}).call(this,o("_process"),typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/async_iterator":21,"./internal/streams/buffer_list":22,"./internal/streams/destroy":23,"./internal/streams/from":25,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,events:7,inherits:10,"string_decoder/":31,util:2}],19:[function(o,c){function d(v,A){var m=this._transformState;m.transforming=!1;var k=m.writecb;if(k===null)return this.emit("error",new x);m.writechunk=null,m.writecb=null,A!=null&&this.push(A),k(v);var _=this._readableState;_.reading=!1,(_.needReadable||_.length<_.highWaterMark)&&this._read(_.highWaterMark)}function l(v){return this instanceof l?(I.call(this,v),this._transformState={afterTransform:d.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,v&&(typeof v.transform=="function"&&(this._transform=v.transform),typeof v.flush=="function"&&(this._flush=v.flush)),void this.on("prefinish",p)):new l(v)}function p(){var v=this;typeof this._flush!="function"||this._readableState.destroyed?g(this,null,null):this._flush(function(A,m){g(v,A,m)})}function g(v,A,m){if(A)return v.emit("error",A);if(m!=null&&v.push(m),v._writableState.length)throw new E;if(v._transformState.transforming)throw new y;return v.push(null)}c.exports=l;var u=o("../errors").codes,f=u.ERR_METHOD_NOT_IMPLEMENTED,x=u.ERR_MULTIPLE_CALLBACK,y=u.ERR_TRANSFORM_ALREADY_TRANSFORMING,E=u.ERR_TRANSFORM_WITH_LENGTH_0,I=o("./_stream_duplex");o("inherits")(l,I),l.prototype.push=function(v,A){return this._transformState.needTransform=!1,I.prototype.push.call(this,v,A)},l.prototype._transform=function(v,A,m){m(new f("_transform()"))},l.prototype._write=function(v,A,m){var k=this._transformState;if(k.writecb=m,k.writechunk=v,k.writeencoding=A,!k.transforming){var _=this._readableState;(k.needTransform||_.needReadable||_.length<_.highWaterMark)&&this._read(_.highWaterMark)}},l.prototype._read=function(){var v=this._transformState;v.writechunk===null||v.transforming?v.needTransform=!0:(v.transforming=!0,this._transform(v.writechunk,v.writeencoding,v.afterTransform))},l.prototype._destroy=function(v,A){I.prototype._destroy.call(this,v,function(m){A(m)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(o,c){(function(d,l){(function(){function p(M){var W=this;this.next=null,this.entry=null,this.finish=function(){q(W,M)}}function g(M){return F.from(M)}function u(M){return F.isBuffer(M)||M instanceof V}function f(){}function x(M,W,G){H=H||o("./_stream_duplex"),M=M||{},typeof G!="boolean"&&(G=W instanceof H),this.objectMode=!!M.objectMode,G&&(this.objectMode=this.objectMode||!!M.writableObjectMode),this.highWaterMark=te(this,M,"writableHighWaterMark",G),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var ne=M.decodeStrings===!1;this.decodeStrings=!ne,this.defaultEncoding=M.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(N){T(W,N)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=M.emitClose!==!1,this.autoDestroy=!!M.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new p(this)}function y(M){H=H||o("./_stream_duplex");var W=this instanceof H;return W||ae.call(y,this)?(this._writableState=new x(M,this,W),this.writable=!0,M&&(typeof M.write=="function"&&(this._write=M.write),typeof M.writev=="function"&&(this._writev=M.writev),typeof M.destroy=="function"&&(this._destroy=M.destroy),typeof M.final=="function"&&(this._final=M.final)),void $.call(this)):new y(M)}function E(M,W){var G=new X;ee(M,G),d.nextTick(W,G)}function I(M,W,G,ne){var N;return G===null?N=new ve:typeof G!="string"&&!W.objectMode&&(N=new be("chunk",["string","Buffer"],G)),!N||(ee(M,N),d.nextTick(ne,N),!1)}function v(M,W,G){return M.objectMode||M.decodeStrings===!1||typeof W!="string"||(W=F.from(W,G)),W}function A(M,W,G,ne,N,a){if(!G){var h=v(W,ne,N);ne!==h&&(G=!0,N="buffer",ne=h)}var b=W.objectMode?1:ne.length;W.length+=b;var L=W.length<W.highWaterMark;if(L||(W.needDrain=!0),W.writing||W.corked){var O=W.lastBufferedRequest;W.lastBufferedRequest={chunk:ne,encoding:N,isBuf:G,callback:a,next:null},O?O.next=W.lastBufferedRequest:W.bufferedRequest=W.lastBufferedRequest,W.bufferedRequestCount+=1}else m(M,W,!1,b,ne,N,a);return L}function m(M,W,G,ne,N,a,h){W.writelen=ne,W.writecb=h,W.writing=!0,W.sync=!0,W.destroyed?W.onwrite(new xe("write")):G?M._writev(N,W.onwrite):M._write(N,a,W.onwrite),W.sync=!1}function k(M,W,G,ne,N){--W.pendingcb,G?(d.nextTick(N,ne),d.nextTick(B,M,W),M._writableState.errorEmitted=!0,ee(M,ne)):(N(ne),M._writableState.errorEmitted=!0,ee(M,ne),B(M,W))}function _(M){M.writing=!1,M.writecb=null,M.length-=M.writelen,M.writelen=0}function T(M,W){var G=M._writableState,ne=G.sync,N=G.writecb;if(typeof N!="function")throw new ce;if(_(G),W)k(M,G,ne,W,N);else{var a=j(G)||M.destroyed;a||G.corked||G.bufferProcessing||!G.bufferedRequest||D(M,G),ne?d.nextTick(S,M,G,a,N):S(M,G,a,N)}}function S(M,W,G,ne){G||C(M,W),W.pendingcb--,ne(),B(M,W)}function C(M,W){W.length===0&&W.needDrain&&(W.needDrain=!1,M.emit("drain"))}function D(M,W){W.bufferProcessing=!0;var G=W.bufferedRequest;if(M._writev&&G&&G.next){var ne=W.bufferedRequestCount,N=Array(ne),a=W.corkedRequestsFree;a.entry=G;for(var h=0,b=!0;G;)N[h]=G,G.isBuf||(b=!1),G=G.next,h+=1;N.allBuffers=b,m(M,W,!0,W.length,N,"",a.finish),W.pendingcb++,W.lastBufferedRequest=null,a.next?(W.corkedRequestsFree=a.next,a.next=null):W.corkedRequestsFree=new p(W),W.bufferedRequestCount=0}else{for(;G;){var L=G.chunk,O=G.encoding,U=G.callback,re=W.objectMode?1:L.length;if(m(M,W,!1,re,L,O,U),G=G.next,W.bufferedRequestCount--,W.writing)break}G===null&&(W.lastBufferedRequest=null)}W.bufferedRequest=G,W.bufferProcessing=!1}function j(M){return M.ending&&M.length===0&&M.bufferedRequest===null&&!M.finished&&!M.writing}function R(M,W){M._final(function(G){W.pendingcb--,G&&ee(M,G),W.prefinished=!0,M.emit("prefinish"),B(M,W)})}function P(M,W){W.prefinished||W.finalCalled||(typeof M._final!="function"||W.destroyed?(W.prefinished=!0,M.emit("prefinish")):(W.pendingcb++,W.finalCalled=!0,d.nextTick(R,M,W)))}function B(M,W){var G=j(W);if(G&&(P(M,W),W.pendingcb===0&&(W.finished=!0,M.emit("finish"),W.autoDestroy))){var ne=M._readableState;(!ne||ne.autoDestroy&&ne.endEmitted)&&M.destroy()}return G}function z(M,W,G){W.ending=!0,B(M,W),G&&(W.finished?d.nextTick(G):M.once("finish",G)),W.ended=!0,M.writable=!1}function q(M,W,G){var ne=M.entry;for(M.entry=null;ne;){var N=ne.callback;W.pendingcb--,N(G),ne=ne.next}W.corkedRequestsFree.next=M}c.exports=y;var H;y.WritableState=x;var J={deprecate:o("util-deprecate")},$=o("./internal/streams/stream"),F=o("buffer").Buffer,V=l.Uint8Array||function(){},se=o("./internal/streams/destroy"),Y=o("./internal/streams/state"),te=Y.getHighWaterMark,Q=o("../errors").codes,be=Q.ERR_INVALID_ARG_TYPE,Ce=Q.ERR_METHOD_NOT_IMPLEMENTED,ce=Q.ERR_MULTIPLE_CALLBACK,ye=Q.ERR_STREAM_CANNOT_PIPE,xe=Q.ERR_STREAM_DESTROYED,ve=Q.ERR_STREAM_NULL_VALUES,X=Q.ERR_STREAM_WRITE_AFTER_END,K=Q.ERR_UNKNOWN_ENCODING,ee=se.errorOrDestroy;o("inherits")(y,$),x.prototype.getBuffer=function(){for(var M=this.bufferedRequest,W=[];M;)W.push(M),M=M.next;return W},(function(){try{Object.defineProperty(x.prototype,"buffer",{get:J.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var ae;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(ae=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(M){return!!ae.call(this,M)||this===y&&M&&M._writableState instanceof x}})):ae=function(M){return M instanceof this},y.prototype.pipe=function(){ee(this,new ye)},y.prototype.write=function(M,W,G){var ne=this._writableState,N=!1,a=!ne.objectMode&&u(M);return a&&!F.isBuffer(M)&&(M=g(M)),typeof W=="function"&&(G=W,W=null),a?W="buffer":!W&&(W=ne.defaultEncoding),typeof G!="function"&&(G=f),ne.ending?E(this,G):(a||I(this,ne,M,G))&&(ne.pendingcb++,N=A(this,ne,a,M,W,G)),N},y.prototype.cork=function(){this._writableState.corked++},y.prototype.uncork=function(){var M=this._writableState;M.corked&&(M.corked--,!M.writing&&!M.corked&&!M.bufferProcessing&&M.bufferedRequest&&D(this,M))},y.prototype.setDefaultEncoding=function(M){if(typeof M=="string"&&(M=M.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((M+"").toLowerCase())))throw new K(M);return this._writableState.defaultEncoding=M,this},Object.defineProperty(y.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(M,W,G){G(new Ce("_write()"))},y.prototype._writev=null,y.prototype.end=function(M,W,G){var ne=this._writableState;return typeof M=="function"?(G=M,M=null,W=null):typeof W=="function"&&(G=W,W=null),M!=null&&this.write(M,W),ne.corked&&(ne.corked=1,this.uncork()),ne.ending||z(this,ne,G),this},Object.defineProperty(y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(y.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(M){this._writableState&&(this._writableState.destroyed=M)}}),y.prototype.destroy=se.destroy,y.prototype._undestroy=se.undestroy,y.prototype._destroy=function(M,W){W(M)}}).call(this)}).call(this,o("_process"),typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/destroy":23,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,inherits:10,"util-deprecate":32}],21:[function(o,c){(function(d){(function(){function l(C,D,j){return D in C?Object.defineProperty(C,D,{value:j,enumerable:!0,configurable:!0,writable:!0}):C[D]=j,C}function p(C,D){return{value:C,done:D}}function g(C){var D=C[E];if(D!==null){var j=C[_].read();j!==null&&(C[m]=null,C[E]=null,C[I]=null,D(p(j,!1)))}}function u(C){d.nextTick(g,C)}function f(C,D){return function(j,R){C.then(function(){return D[A]?void j(p(void 0,!0)):void D[k](j,R)},R)}}var x,y=o("./end-of-stream"),E=Symbol("lastResolve"),I=Symbol("lastReject"),v=Symbol("error"),A=Symbol("ended"),m=Symbol("lastPromise"),k=Symbol("handlePromise"),_=Symbol("stream"),T=Object.getPrototypeOf(function(){}),S=Object.setPrototypeOf((x={get stream(){return this[_]},next:function(){var C=this,D=this[v];if(D!==null)return Promise.reject(D);if(this[A])return Promise.resolve(p(void 0,!0));if(this[_].destroyed)return new Promise(function(B,z){d.nextTick(function(){C[v]?z(C[v]):B(p(void 0,!0))})});var j,R=this[m];if(R)j=new Promise(f(R,this));else{var P=this[_].read();if(P!==null)return Promise.resolve(p(P,!1));j=new Promise(this[k])}return this[m]=j,j}},l(x,Symbol.asyncIterator,function(){return this}),l(x,"return",function(){var C=this;return new Promise(function(D,j){C[_].destroy(null,function(R){return R?void j(R):void D(p(void 0,!0))})})}),x),T);c.exports=function(C){var D,j=Object.create(S,(D={},l(D,_,{value:C,writable:!0}),l(D,E,{value:null,writable:!0}),l(D,I,{value:null,writable:!0}),l(D,v,{value:null,writable:!0}),l(D,A,{value:C._readableState.endEmitted,writable:!0}),l(D,k,{value:function(R,P){var B=j[_].read();B?(j[m]=null,j[E]=null,j[I]=null,R(p(B,!1))):(j[E]=R,j[I]=P)},writable:!0}),D));return j[m]=null,y(C,function(R){if(R&&R.code!=="ERR_STREAM_PREMATURE_CLOSE"){var P=j[I];return P!==null&&(j[m]=null,j[E]=null,j[I]=null,P(R)),void(j[v]=R)}var B=j[E];B!==null&&(j[m]=null,j[E]=null,j[I]=null,B(p(void 0,!0))),j[A]=!0}),C.on("readable",u.bind(null,j)),j}}).call(this)}).call(this,o("_process"))},{"./end-of-stream":24,_process:12}],22:[function(o,c){function d(m,k){var _=Object.keys(m);if(Object.getOwnPropertySymbols){var T=Object.getOwnPropertySymbols(m);k&&(T=T.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),_.push.apply(_,T)}return _}function l(m){for(var k,_=1;_<arguments.length;_++)k=arguments[_]==null?{}:arguments[_],_%2?d(Object(k),!0).forEach(function(T){p(m,T,k[T])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(k)):d(Object(k)).forEach(function(T){Object.defineProperty(m,T,Object.getOwnPropertyDescriptor(k,T))});return m}function p(m,k,_){return k in m?Object.defineProperty(m,k,{value:_,enumerable:!0,configurable:!0,writable:!0}):m[k]=_,m}function g(m,k){if(!(m instanceof k))throw new TypeError("Cannot call a class as a function")}function u(m,k){for(var _,T=0;T<k.length;T++)_=k[T],_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(m,_.key,_)}function f(m,k,_){return k&&u(m.prototype,k),m}function x(m,k,_){E.prototype.copy.call(m,k,_)}var y=o("buffer"),E=y.Buffer,I=o("util"),v=I.inspect,A=v&&v.custom||"inspect";c.exports=(function(){function m(){g(this,m),this.head=null,this.tail=null,this.length=0}return f(m,[{key:"push",value:function(k){var _={data:k,next:null};0<this.length?this.tail.next=_:this.head=_,this.tail=_,++this.length}},{key:"unshift",value:function(k){var _={data:k,next:this.head};this.length===0&&(this.tail=_),this.head=_,++this.length}},{key:"shift",value:function(){if(this.length!==0){var k=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,k}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(k){if(this.length===0)return"";for(var _=this.head,T=""+_.data;_=_.next;)T+=k+_.data;return T}},{key:"concat",value:function(k){if(this.length===0)return E.alloc(0);for(var _=E.allocUnsafe(k>>>0),T=this.head,S=0;T;)x(T.data,_,S),S+=T.data.length,T=T.next;return _}},{key:"consume",value:function(k,_){var T;return k<this.head.data.length?(T=this.head.data.slice(0,k),this.head.data=this.head.data.slice(k)):k===this.head.data.length?T=this.shift():T=_?this._getString(k):this._getBuffer(k),T}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(k){var _=this.head,T=1,S=_.data;for(k-=S.length;_=_.next;){var C=_.data,D=k>C.length?C.length:k;if(S+=D===C.length?C:C.slice(0,k),k-=D,k===0){D===C.length?(++T,this.head=_.next?_.next:this.tail=null):(this.head=_,_.data=C.slice(D));break}++T}return this.length-=T,S}},{key:"_getBuffer",value:function(k){var _=E.allocUnsafe(k),T=this.head,S=1;for(T.data.copy(_),k-=T.data.length;T=T.next;){var C=T.data,D=k>C.length?C.length:k;if(C.copy(_,_.length-k,0,D),k-=D,k===0){D===C.length?(++S,this.head=T.next?T.next:this.tail=null):(this.head=T,T.data=C.slice(D));break}++S}return this.length-=S,_}},{key:A,value:function(k,_){return v(this,l({},_,{depth:0,customInspect:!1}))}}]),m})()},{buffer:3,util:2}],23:[function(o,c){(function(d){(function(){function l(u,f){g(u,f),p(u)}function p(u){u._writableState&&!u._writableState.emitClose||u._readableState&&!u._readableState.emitClose||u.emit("close")}function g(u,f){u.emit("error",f)}c.exports={destroy:function(u,f){var x=this,y=this._readableState&&this._readableState.destroyed,E=this._writableState&&this._writableState.destroyed;return y||E?(f?f(u):u&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,d.nextTick(g,this,u)):d.nextTick(g,this,u)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(u||null,function(I){!f&&I?x._writableState?x._writableState.errorEmitted?d.nextTick(p,x):(x._writableState.errorEmitted=!0,d.nextTick(l,x,I)):d.nextTick(l,x,I):f?(d.nextTick(p,x),f(I)):d.nextTick(p,x)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(u,f){var x=u._readableState,y=u._writableState;x&&x.autoDestroy||y&&y.autoDestroy?u.destroy(f):u.emit("error",f)}}}).call(this)}).call(this,o("_process"))},{_process:12}],24:[function(o,c){function d(f){var x=!1;return function(){if(!x){x=!0;for(var y=arguments.length,E=Array(y),I=0;I<y;I++)E[I]=arguments[I];f.apply(this,E)}}}function l(){}function p(f){return f.setHeader&&typeof f.abort=="function"}function g(f,x,y){if(typeof x=="function")return g(f,null,x);x||(x={}),y=d(y||l);var E=x.readable||x.readable!==!1&&f.readable,I=x.writable||x.writable!==!1&&f.writable,v=function(){f.writable||m()},A=f._writableState&&f._writableState.finished,m=function(){I=!1,A=!0,E||y.call(f)},k=f._readableState&&f._readableState.endEmitted,_=function(){E=!1,k=!0,I||y.call(f)},T=function(D){y.call(f,D)},S=function(){var D;return E&&!k?(f._readableState&&f._readableState.ended||(D=new u),y.call(f,D)):I&&!A?(f._writableState&&f._writableState.ended||(D=new u),y.call(f,D)):void 0},C=function(){f.req.on("finish",m)};return p(f)?(f.on("complete",m),f.on("abort",S),f.req?C():f.on("request",C)):I&&!f._writableState&&(f.on("end",v),f.on("close",v)),f.on("end",_),f.on("finish",m),x.error!==!1&&f.on("error",T),f.on("close",S),function(){f.removeListener("complete",m),f.removeListener("abort",S),f.removeListener("request",C),f.req&&f.req.removeListener("finish",m),f.removeListener("end",v),f.removeListener("close",v),f.removeListener("finish",m),f.removeListener("end",_),f.removeListener("error",T),f.removeListener("close",S)}}var u=o("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;c.exports=g},{"../../../errors":15}],25:[function(o,c){c.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(o,c){function d(A){var m=!1;return function(){m||(m=!0,A.apply(void 0,arguments))}}function l(A){if(A)throw A}function p(A){return A.setHeader&&typeof A.abort=="function"}function g(A,m,k,_){_=d(_);var T=!1;A.on("close",function(){T=!0}),y===void 0&&(y=o("./end-of-stream")),y(A,{readable:m,writable:k},function(C){return C?_(C):(T=!0,void _())});var S=!1;return function(C){if(!T)return S?void 0:(S=!0,p(A)?A.abort():typeof A.destroy=="function"?A.destroy():void _(C||new v("pipe")))}}function u(A){A()}function f(A,m){return A.pipe(m)}function x(A){return A.length&&typeof A[A.length-1]=="function"?A.pop():l}var y,E=o("../../../errors").codes,I=E.ERR_MISSING_ARGS,v=E.ERR_STREAM_DESTROYED;c.exports=function(){for(var A=arguments.length,m=Array(A),k=0;k<A;k++)m[k]=arguments[k];var _=x(m);if(Array.isArray(m[0])&&(m=m[0]),2>m.length)throw new I("streams");var T,S=m.map(function(C,D){var j=D<m.length-1;return g(C,j,0<D,function(R){T||(T=R),R&&S.forEach(u),j||(S.forEach(u),_(T))})});return m.reduce(f)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(o,c){function d(p,g,u){return p.highWaterMark==null?g?p[u]:null:p.highWaterMark}var l=o("../../../errors").codes.ERR_INVALID_OPT_VALUE;c.exports={getHighWaterMark:function(p,g,u,f){var x=d(g,f,u);if(x!=null){if(!(isFinite(x)&&s(x)===x)||0>x){var y=f?u:"highWaterMark";throw new l(y,x)}return s(x)}return p.objectMode?16:16384}}},{"../../../errors":15}],28:[function(o,c){c.exports=o("events").EventEmitter},{events:7}],29:[function(o,c,d){d=c.exports=o("./lib/_stream_readable.js"),d.Stream=d,d.Readable=d,d.Writable=o("./lib/_stream_writable.js"),d.Duplex=o("./lib/_stream_duplex.js"),d.Transform=o("./lib/_stream_transform.js"),d.PassThrough=o("./lib/_stream_passthrough.js"),d.finished=o("./lib/internal/streams/end-of-stream.js"),d.pipeline=o("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(o,c,d){function l(f,x){for(var y in f)x[y]=f[y]}function p(f,x,y){return u(f,x,y)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var g=o("buffer"),u=g.Buffer;u.from&&u.alloc&&u.allocUnsafe&&u.allocUnsafeSlow?c.exports=g:(l(g,d),d.Buffer=p),p.prototype=Object.create(u.prototype),l(u,p),p.from=function(f,x,y){if(typeof f=="number")throw new TypeError("Argument must not be a number");return u(f,x,y)},p.alloc=function(f,x,y){if(typeof f!="number")throw new TypeError("Argument must be a number");var E=u(f);return x===void 0?E.fill(0):typeof y=="string"?E.fill(x,y):E.fill(x),E},p.allocUnsafe=function(f){if(typeof f!="number")throw new TypeError("Argument must be a number");return u(f)},p.allocUnsafeSlow=function(f){if(typeof f!="number")throw new TypeError("Argument must be a number");return g.SlowBuffer(f)}},{buffer:3}],31:[function(o,c,d){function l(S){if(!S)return"utf8";for(var C;;)switch(S){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return S;default:if(C)return;S=(""+S).toLowerCase(),C=!0}}function p(S){var C=l(S);if(typeof C!="string"&&(_.isEncoding===T||!T(S)))throw new Error("Unknown encoding: "+S);return C||S}function g(S){this.encoding=p(S);var C;switch(this.encoding){case"utf16le":this.text=E,this.end=I,C=4;break;case"utf8":this.fillLast=y,C=4;break;case"base64":this.text=v,this.end=A,C=3;break;default:return this.write=m,void(this.end=k)}this.lastNeed=0,this.lastTotal=0,this.lastChar=_.allocUnsafe(C)}function u(S){return 127>=S?0:S>>5==6?2:S>>4==14?3:S>>3==30?4:S>>6==2?-1:-2}function f(S,C,D){var j=C.length-1;if(j<D)return 0;var R=u(C[j]);return 0<=R?(0<R&&(S.lastNeed=R-1),R):--j<D||R===-2?0:(R=u(C[j]),0<=R?(0<R&&(S.lastNeed=R-2),R):--j<D||R===-2?0:(R=u(C[j]),0<=R?(0<R&&(R===2?R=0:S.lastNeed=R-3),R):0))}function x(S,C){if((192&C[0])!=128)return S.lastNeed=0,"�";if(1<S.lastNeed&&1<C.length){if((192&C[1])!=128)return S.lastNeed=1,"�";if(2<S.lastNeed&&2<C.length&&(192&C[2])!=128)return S.lastNeed=2,"�"}}function y(S){var C=this.lastTotal-this.lastNeed,D=x(this,S);return D===void 0?this.lastNeed<=S.length?(S.copy(this.lastChar,C,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(S.copy(this.lastChar,C,0,S.length),void(this.lastNeed-=S.length)):D}function E(S,C){if((S.length-C)%2==0){var D=S.toString("utf16le",C);if(D){var j=D.charCodeAt(D.length-1);if(55296<=j&&56319>=j)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=S[S.length-2],this.lastChar[1]=S[S.length-1],D.slice(0,-1)}return D}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=S[S.length-1],S.toString("utf16le",C,S.length-1)}function I(S){var C=S&&S.length?this.write(S):"";if(this.lastNeed){var D=this.lastTotal-this.lastNeed;return C+this.lastChar.toString("utf16le",0,D)}return C}function v(S,C){var D=(S.length-C)%3;return D==0?S.toString("base64",C):(this.lastNeed=3-D,this.lastTotal=3,D==1?this.lastChar[0]=S[S.length-1]:(this.lastChar[0]=S[S.length-2],this.lastChar[1]=S[S.length-1]),S.toString("base64",C,S.length-D))}function A(S){var C=S&&S.length?this.write(S):"";return this.lastNeed?C+this.lastChar.toString("base64",0,3-this.lastNeed):C}function m(S){return S.toString(this.encoding)}function k(S){return S&&S.length?this.write(S):""}var _=o("safe-buffer").Buffer,T=_.isEncoding||function(S){switch(S=""+S,S&&S.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};d.StringDecoder=g,g.prototype.write=function(S){if(S.length===0)return"";var C,D;if(this.lastNeed){if(C=this.fillLast(S),C===void 0)return"";D=this.lastNeed,this.lastNeed=0}else D=0;return D<S.length?C?C+this.text(S,D):this.text(S,D):C||""},g.prototype.end=function(S){var C=S&&S.length?this.write(S):"";return this.lastNeed?C+"�":C},g.prototype.text=function(S,C){var D=f(this,S,C);if(!this.lastNeed)return S.toString("utf8",C);this.lastTotal=D;var j=S.length-(D-this.lastNeed);return S.copy(this.lastChar,0,j),S.toString("utf8",C,j)},g.prototype.fillLast=function(S){return this.lastNeed<=S.length?(S.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(S.copy(this.lastChar,this.lastTotal-this.lastNeed,0,S.length),void(this.lastNeed-=S.length))}},{"safe-buffer":30}],32:[function(o,c){(function(d){(function(){function l(p){try{if(!d.localStorage)return!1}catch{return!1}var g=d.localStorage[p];return g!=null&&(g+"").toLowerCase()==="true"}c.exports=function(p,g){function u(){if(!f){if(l("throwDeprecation"))throw new Error(g);l("traceDeprecation")?console.trace(g):console.warn(g),f=!0}return p.apply(this,arguments)}if(l("noDeprecation"))return p;var f=!1;return u}}).call(this)}).call(this,typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{}],"/":[function(o,c){function d(A){return A.replace(/a=ice-options:trickle\s\n/g,"")}function l(A){console.warn(A)}/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const p=o("debug")("simple-peer"),g=o("get-browser-rtc"),u=o("randombytes"),f=o("readable-stream"),x=o("queue-microtask"),y=o("err-code"),{Buffer:E}=o("buffer"),I=65536;class v extends f.Duplex{constructor(m){if(m=Object.assign({allowHalfOpen:!1},m),super(m),this._id=u(4).toString("hex").slice(0,7),this._debug("new peer %o",m),this.channelName=m.initiator?m.channelName||u(20).toString("hex"):null,this.initiator=m.initiator||!1,this.channelConfig=m.channelConfig||v.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},v.config,m.config),this.offerOptions=m.offerOptions||{},this.answerOptions=m.answerOptions||{},this.sdpTransform=m.sdpTransform||(k=>k),this.streams=m.streams||(m.stream?[m.stream]:[]),this.trickle=m.trickle===void 0||m.trickle,this.allowHalfTrickle=m.allowHalfTrickle!==void 0&&m.allowHalfTrickle,this.iceCompleteTimeout=m.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=m.wrtc&&typeof m.wrtc=="object"?m.wrtc:g(),!this._wrtc)throw y(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(k){return void this.destroy(y(k,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=k=>{this._onIceCandidate(k)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(k=>{this.destroy(y(k,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=k=>{this._setupData(k)},this.streams&&this.streams.forEach(k=>{this.addStream(k)}),this._pc.ontrack=k=>{this._onTrack(k)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof m=="string")try{m=JSON.parse(m)}catch{m={}}this._debug("signal()"),m.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),m.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(m.transceiverRequest.kind,m.transceiverRequest.init)),m.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(m.candidate):this._pendingCandidates.push(m.candidate)),m.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(m)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(k=>{this._addIceCandidate(k)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(k=>{this.destroy(y(k,"ERR_SET_REMOTE_DESCRIPTION"))}),m.sdp||m.candidate||m.renegotiate||m.transceiverRequest||this.destroy(y(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(m){const k=new this._wrtc.RTCIceCandidate(m);this._pc.addIceCandidate(k).catch(_=>{!k.address||k.address.endsWith(".local")?l("Ignoring unsupported ICE candidate."):this.destroy(y(_,"ERR_ADD_ICE_CANDIDATE"))})}send(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(m)}}addTransceiver(m,k){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(m,k),this._needsNegotiation()}catch(_){this.destroy(y(_,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:m,init:k}})}}addStream(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),m.getTracks().forEach(k=>{this.addTrack(k,m)})}}addTrack(m,k){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const _=this._senderMap.get(m)||new Map;let T=_.get(k);if(!T)T=this._pc.addTrack(m,k),_.set(k,T),this._senderMap.set(m,_),this._needsNegotiation();else throw T.removed?y(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):y(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(m,k,_){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const T=this._senderMap.get(m),S=T?T.get(_):null;if(!S)throw y(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");k&&this._senderMap.set(k,T),S.replaceTrack==null?this.destroy(y(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):S.replaceTrack(k)}removeTrack(m,k){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const _=this._senderMap.get(m),T=_?_.get(k):null;if(!T)throw y(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{T.removed=!0,this._pc.removeTrack(T)}catch(S){S.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(T):this.destroy(y(S,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),m.getTracks().forEach(k=>{this.removeTrack(k,m)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,x(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(m){this._destroy(m,()=>{})}_destroy(m,k){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",m&&(m.message||m)),x(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",m&&(m.message||m)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,m&&this.emit("error",m),this.emit("close"),k()}))}_setupData(m){if(!m.channel)return this.destroy(y(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=m.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=I),this.channelName=this._channel.label,this._channel.onmessage=_=>{this._onChannelMessage(_)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=_=>{const T=_.error instanceof Error?_.error:new Error(`Datachannel error: ${_.message} ${_.filename}:${_.lineno}:${_.colno}`);this.destroy(y(T,"ERR_DATA_CHANNEL"))};let k=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(k&&this._onChannelClose(),k=!0):k=!1},5e3)}_read(){}_write(m,k,_){if(this.destroyed)return _(y(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(m)}catch(T){return this.destroy(y(T,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>I?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=_):_(null)}else this._debug("write before connect"),this._chunk=m,this._cb=_}_onFinish(){if(!this.destroyed){const m=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?m():this.once("connect",m)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(m=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(m.sdp=d(m.sdp)),m.sdp=this.sdpTransform(m.sdp);const k=()=>{if(!this.destroyed){const _=this._pc.localDescription||m;this._debug("signal"),this.emit("signal",{type:_.type,sdp:_.sdp})}};this._pc.setLocalDescription(m).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?k():this.once("_iceComplete",k))}).catch(_=>{this.destroy(y(_,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(m=>{this.destroy(y(m,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(m=>{m.mid||!m.sender.track||m.requested||(m.requested=!0,this.addTransceiver(m.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(m=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(m.sdp=d(m.sdp)),m.sdp=this.sdpTransform(m.sdp);const k=()=>{if(!this.destroyed){const _=this._pc.localDescription||m;this._debug("signal"),this.emit("signal",{type:_.type,sdp:_.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(m).then(()=>{this.destroyed||(this.trickle||this._iceComplete?k():this.once("_iceComplete",k))}).catch(_=>{this.destroy(y(_,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(m=>{this.destroy(y(m,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(y(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const m=this._pc.iceConnectionState,k=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",m,k),this.emit("iceStateChange",m,k),(m==="connected"||m==="completed")&&(this._pcReady=!0,this._maybeReady()),m==="failed"&&this.destroy(y(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),m==="closed"&&this.destroy(y(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(m){const k=_=>(Object.prototype.toString.call(_.values)==="[object Array]"&&_.values.forEach(T=>{Object.assign(_,T)}),_);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(_=>{const T=[];_.forEach(S=>{T.push(k(S))}),m(null,T)},_=>m(_)):0<this._pc.getStats.length?this._pc.getStats(_=>{if(this.destroyed)return;const T=[];_.result().forEach(S=>{const C={};S.names().forEach(D=>{C[D]=S.stat(D)}),C.id=S.id,C.type=S.type,C.timestamp=S.timestamp,T.push(k(C))}),m(null,T)},_=>m(_)):m(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const m=()=>{this.destroyed||this.getStats((k,_)=>{if(this.destroyed)return;k&&(_=[]);const T={},S={},C={};let D=!1;_.forEach(R=>{(R.type==="remotecandidate"||R.type==="remote-candidate")&&(T[R.id]=R),(R.type==="localcandidate"||R.type==="local-candidate")&&(S[R.id]=R),(R.type==="candidatepair"||R.type==="candidate-pair")&&(C[R.id]=R)});const j=R=>{D=!0;let P=S[R.localCandidateId];P&&(P.ip||P.address)?(this.localAddress=P.ip||P.address,this.localPort=+P.port):P&&P.ipAddress?(this.localAddress=P.ipAddress,this.localPort=+P.portNumber):typeof R.googLocalAddress=="string"&&(P=R.googLocalAddress.split(":"),this.localAddress=P[0],this.localPort=+P[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let B=T[R.remoteCandidateId];B&&(B.ip||B.address)?(this.remoteAddress=B.ip||B.address,this.remotePort=+B.port):B&&B.ipAddress?(this.remoteAddress=B.ipAddress,this.remotePort=+B.portNumber):typeof R.googRemoteAddress=="string"&&(B=R.googRemoteAddress.split(":"),this.remoteAddress=B[0],this.remotePort=+B[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(_.forEach(R=>{R.type==="transport"&&R.selectedCandidatePairId&&j(C[R.selectedCandidatePairId]),(R.type==="googCandidatePair"&&R.googActiveConnection==="true"||(R.type==="candidatepair"||R.type==="candidate-pair")&&R.selected)&&j(R)}),!D&&(!Object.keys(C).length||Object.keys(S).length))return void setTimeout(m,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(P){return this.destroy(y(P,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const R=this._cb;this._cb=null,R(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};m()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>I)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(m=>{this._pc.removeTrack(m),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(m){this.destroyed||(m.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:m.candidate.candidate,sdpMLineIndex:m.candidate.sdpMLineIndex,sdpMid:m.candidate.sdpMid}}):!m.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),m.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(m){if(this.destroyed)return;let k=m.data;k instanceof ArrayBuffer&&(k=E.from(k)),this.push(k)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const m=this._cb;this._cb=null,m(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(m){this.destroyed||m.streams.forEach(k=>{this._debug("on track"),this.emit("track",m.track,k),this._remoteTracks.push({track:m.track,stream:k}),this._remoteStreams.some(_=>_.id===k.id)||(this._remoteStreams.push(k),x(()=>{this._debug("on stream"),this.emit("stream",k)}))})}_debug(){const m=[].slice.call(arguments);m[0]="["+this._id+"] "+m[0],p.apply(null,m)}}v.WEBRTC_SUPPORT=!!g(),v.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},v.channelConfig={},c.exports=v},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(Yn)),Yn.exports}var Wh=Ph();const Bh=kl(Wh),ii=0,oi=1,Ya=2,Ka=(t,e)=>{ie(t,ii);const s=uu(e);je(t,s)},Ja=(t,e,s)=>{ie(t,oi),je(t,Jr(e,s))},Uh=(t,e,s)=>Ja(e,s,Ie(t)),Xa=(t,e,s,r)=>{try{pa(e,Ie(t),s)}catch(i){r!=null&&r(i),console.error("Caught error while handling a Yjs update",i)}},Fh=(t,e)=>{ie(t,Ya),je(t,e)},$h=Xa,zh=(t,e,s,r,i)=>{const o=de(t);switch(o){case ii:Uh(t,e,s);break;case oi:Xa(t,s,r,i);break;case Ya:$h(t,s,r,i);break;default:throw new Error("Unknown message type")}return o},Kn=3e4;class Hh extends Lr{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const s=dt();this.getLocalState()!==null&&Kn/2<=s-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((i,o)=>{o!==this.clientID&&Kn<=s-i.lastUpdated&&this.states.has(o)&&r.push(o)}),r.length>0&&mr(this,r,"timeout")},Xe(Kn/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const s=this.clientID,r=this.meta.get(s),i=r===void 0?0:r.clock+1,o=this.states.get(s);e===null?this.states.delete(s):this.states.set(s,e),this.meta.set(s,{clock:i,lastUpdated:dt()});const c=[],d=[],l=[],p=[];e===null?p.push(s):o==null?e!=null&&c.push(s):(d.push(s),Ut(o,e)||l.push(s)),(c.length>0||l.length>0||p.length>0)&&this.emit("change",[{added:c,updated:l,removed:p},"local"]),this.emit("update",[{added:c,updated:d,removed:p},"local"])}setLocalStateField(e,s){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:s})}getStates(){return this.states}}const mr=(t,e,s)=>{const r=[];for(let i=0;i<e.length;i++){const o=e[i];if(t.states.has(o)){if(t.states.delete(o),o===t.clientID){const c=t.meta.get(o);t.meta.set(o,{clock:c.clock+1,lastUpdated:dt()})}r.push(o)}}r.length>0&&(t.emit("change",[{added:[],updated:[],removed:r},s]),t.emit("update",[{added:[],updated:[],removed:r},s]))},ln=(t,e,s=t.states)=>{const r=e.length,i=De();ie(i,r);for(let o=0;o<r;o++){const c=e[o],d=s.get(c)||null,l=t.meta.get(c).clock;ie(i,c),ie(i,l),st(i,JSON.stringify(d))}return Se(i)},Vh=(t,e,s)=>{const r=it(e),i=dt(),o=[],c=[],d=[],l=[],p=de(r);for(let g=0;g<p;g++){const u=de(r);let f=de(r);const x=JSON.parse(lt(r)),y=t.meta.get(u),E=t.states.get(u),I=y===void 0?0:y.clock;(I<f||I===f&&x===null&&t.states.has(u))&&(x===null?u===t.clientID&&t.getLocalState()!=null?f++:t.states.delete(u):t.states.set(u,x),t.meta.set(u,{clock:f,lastUpdated:i}),y===void 0&&x!==null?o.push(u):y!==void 0&&x===null?l.push(u):x!==null&&(Ut(x,E)||d.push(u),c.push(u)))}(o.length>0||d.length>0||l.length>0)&&t.emit("change",[{added:o,updated:d,removed:l},s]),(o.length>0||c.length>0||l.length>0)&&t.emit("update",[{added:o,updated:c,removed:l},s])},Gh=(t,e)=>{const s=or(t).buffer,r=or(e).buffer;return crypto.subtle.importKey("raw",s,"PBKDF2",!1,["deriveKey"]).then(i=>crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:1e5,hash:"SHA-256"},i,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))},Qa=(t,e)=>{if(!e)return Wr(t);const s=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,t).then(r=>{const i=De();return st(i,"AES-GCM"),je(i,s),je(i,new Uint8Array(r)),Se(i)})},qh=(t,e)=>{const s=De();return Gt(s,t),Qa(Se(s),e)},Za=(t,e)=>{if(!e)return Wr(t);const s=it(t);lt(s)!=="AES-GCM"&&Oc(Ge("Unknown encryption algorithm"));const i=Ie(s),o=Ie(s);return crypto.subtle.decrypt({name:"AES-GCM",iv:i},e,o).then(c=>new Uint8Array(c))},Yh=(t,e)=>Za(t,e).then(s=>qt(it(new Uint8Array(s)))),ze=Yd("y-webrtc"),Ht=0,el=3,Ss=1,ai=4,cn=new Map,jt=new Map,tl=t=>{let e=!0;t.webrtcConns.forEach(s=>{s.synced||(e=!1)}),(!e&&t.synced||e&&!t.synced)&&(t.synced=e,t.provider.emit("synced",[{synced:e}]),ze("synced ",Je,t.name,Nt," with all peers"))},sl=(t,e,s)=>{const r=it(e),i=De(),o=de(r);if(t===void 0)return null;const c=t.awareness,d=t.doc;let l=!1;switch(o){case Ht:{ie(i,Ht);const p=zh(r,i,d,t);p===oi&&!t.synced&&s(),p===ii&&(l=!0);break}case el:ie(i,Ss),je(i,ln(c,Array.from(c.getStates().keys()))),l=!0;break;case Ss:Vh(c,Ie(r),t);break;case ai:{const p=Et(r)===1,g=lt(r);if(g!==t.peerId&&(t.bcConns.has(g)&&!p||!t.bcConns.has(g)&&p)){const u=[],f=[];p?(t.bcConns.add(g),f.push(g)):(t.bcConns.delete(g),u.push(g)),t.provider.emit("peers",[{added:f,removed:u,webrtcPeers:Array.from(t.webrtcConns.keys()),bcPeers:Array.from(t.bcConns)}]),nl(t)}break}default:return console.error("Unable to compute message"),i}return l?i:null},Kh=(t,e)=>{const s=t.room;return ze("received message from ",Je,t.remotePeerId,Gr," (",s.name,")",Nt,Cn),sl(s,e,()=>{t.synced=!0,ze("synced ",Je,s.name,Nt," with ",Je,t.remotePeerId),tl(s)})},Jn=(t,e)=>{ze("send message to ",Je,t.remotePeerId,Nt,Gr," (",t.room.name,")",Cn);try{t.peer.send(Se(e))}catch{}},Jh=(t,e)=>{ze("broadcast message in ",Je,t.name,Nt),t.webrtcConns.forEach(s=>{try{s.peer.send(e)}catch{}})};class Bi{constructor(e,s,r,i){ze("establishing connection to ",Je,r),this.room=i,this.remotePeerId=r,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new Bh({initiator:s,...i.provider.peerOpts}),this.peer.on("signal",o=>{this.glareToken===void 0&&(this.glareToken=Date.now()+Math.random()),li(e,i,{to:r,from:i.peerId,type:"signal",token:this.glareToken,signal:o})}),this.peer.on("connect",()=>{ze("connected to ",Je,r),this.connected=!0;const c=i.provider.doc,d=i.awareness,l=De();ie(l,Ht),Ka(l,c),Jn(this,l);const p=d.getStates();if(p.size>0){const g=De();ie(g,Ss),je(g,ln(d,Array.from(p.keys()))),Jn(this,g)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,i.webrtcConns.has(this.remotePeerId)&&(i.webrtcConns.delete(this.remotePeerId),i.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}])),tl(i),this.peer.destroy(),ze("closed connection to ",Je,r),gr(i)}),this.peer.on("error",o=>{ze("Error in connection to ",Je,r,": ",o),gr(i)}),this.peer.on("data",o=>{const c=Kh(this,o);c!==null&&Jn(this,c)})}destroy(){this.peer.destroy()}}const pt=(t,e)=>Qa(e,t.key).then(s=>t.mux(()=>Mh(t.name,s))),Ui=(t,e)=>{t.bcconnected&&pt(t,e),Jh(t,e)},gr=t=>{cn.forEach(e=>{e.connected&&(e.send({type:"subscribe",topics:[t.name]}),t.webrtcConns.size<t.provider.maxConns&&li(e,t,{type:"announce",from:t.peerId}))})},nl=t=>{if(t.provider.filterBcConns){const e=De();ie(e,ai),ys(e,1),st(e,t.peerId),pt(t,Se(e))}};class Xh{constructor(e,s,r,i){this.peerId=jo(),this.doc=e,this.awareness=s.awareness,this.provider=s,this.synced=!1,this.name=r,this.key=i,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=Oh(),this.bcconnected=!1,this._bcSubscriber=o=>Za(new Uint8Array(o),i).then(c=>this.mux(()=>{const d=sl(this,c,()=>{});d&&pt(this,Se(d))})),this._docUpdateHandler=(o,c)=>{const d=De();ie(d,Ht),Fh(d,o),Ui(this,Se(d))},this._awarenessUpdateHandler=({added:o,updated:c,removed:d},l)=>{const p=o.concat(c).concat(d),g=De();ie(g,Ss),je(g,ln(this.awareness,p)),Ui(this,Se(g))},this._beforeUnloadHandler=()=>{mr(this.awareness,[e.clientID],"window unload"),jt.forEach(o=>{o.disconnect()})},typeof window<"u"?window.addEventListener("beforeunload",this._beforeUnloadHandler):typeof process<"u"&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),gr(this);const e=this.name;Ih(e,this._bcSubscriber),this.bcconnected=!0,nl(this);const s=De();ie(s,Ht),Ka(s,this.doc),pt(this,Se(s));const r=De();ie(r,Ht),Ja(r,this.doc),pt(this,Se(r));const i=De();ie(i,el),pt(this,Se(i));const o=De();ie(o,Ss),je(o,ln(this.awareness,[this.doc.clientID])),pt(this,Se(o))}disconnect(){cn.forEach(s=>{s.connected&&s.send({type:"unsubscribe",topics:[this.name]})}),mr(this.awareness,[this.doc.clientID],"disconnect");const e=De();ie(e,ai),ys(e,0),st(e,this.peerId),pt(this,Se(e)),Dh(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 Qh=(t,e,s,r)=>{if(jt.has(s))throw Ge(`A Yjs Doc connected to room "${s}" already exists!`);const i=new Xh(t,e,s,r);return jt.set(s,i),i},li=(t,e,s)=>{e.key?qh(s,e.key).then(r=>{t.send({type:"publish",topic:e.name,data:Do(r)})}):t.send({type:"publish",topic:e.name,data:s})};class Zh extends Rh{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{ze(`connected (${e})`);const s=Array.from(jt.keys());this.send({type:"subscribe",topics:s}),jt.forEach(r=>li(this,r,{type:"announce",from:r.peerId}))}),this.on("message",s=>{switch(s.type){case"publish":{const r=s.topic,i=jt.get(r);if(i==null||typeof r!="string")return;const o=c=>{const d=i.webrtcConns,l=i.peerId;if(c==null||c.from===l||c.to!==void 0&&c.to!==l||i.bcConns.has(c.from))return;const p=d.has(c.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[c.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(c.type){case"announce":d.size<i.provider.maxConns&&(Ve(d,c.from,()=>new Bi(this,!0,c.from,i)),p());break;case"signal":if(c.signal.type==="offer"){const g=d.get(c.from);if(g){const u=c.token,f=g.glareToken;if(f&&f>u){ze("offer rejected: ",c.from);return}g.glareToken=void 0}}if(c.signal.type==="answer"){ze("offer answered by: ",c.from);const g=d.get(c.from);g.glareToken=void 0}c.to===l&&(Ve(d,c.from,()=>new Bi(this,!1,c.from,i)).peer.signal(c.signal),p());break}};i.key?typeof s.data=="string"&&Yh(Mo(s.data),i.key).then(o):o(s.data)}}}),this.on("disconnect",()=>ze(`disconnect (${e})`))}}const Xn=t=>{t.emit("status",[{connected:t.connected}])};class ef extends xo{constructor(e,s,{signaling:r=["wss://y-webrtc-eu.fly.dev"],password:i=null,awareness:o=new Hh(s),maxConns:c=20+Xe(Dc()*15),filterBcConns:d=!0,peerOpts:l={}}={}){super(),this.roomName=e,this.doc=s,this.filterBcConns=d,this.awareness=o,this.shouldConnect=!1,this.signalingUrls=r,this.signalingConns=[],this.maxConns=c,this.peerOpts=l,this.key=i?Gh(i,e):Wr(null),this.room=null,this.key.then(p=>{this.room=Qh(s,this,e,p),this.shouldConnect?this.room.connect():this.room.disconnect(),Xn(this)}),this.connect(),this.destroy=this.destroy.bind(this),s.on("destroy",this.destroy)}get connected(){return this.room!==null&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(e=>{const s=Ve(cn,e,()=>new Zh(e));this.signalingConns.push(s),s.providers.add(this)}),this.room&&(this.room.connect(),Xn(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),e.providers.size===0&&(e.destroy(),cn.delete(e.url))}),this.room&&(this.room.disconnect(),Xn(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),jt.delete(this.roomName)}),super.destroy()}}const us=new Map,dn=new Map,yr=new Map;function tf(){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem("titan2:webrtc"))==="1"}catch{return!1}}function sf(t){if(!us.has(t)){const e=new rs({guid:`titan-space-${t}`});us.set(t,e);const s=new Nh(`titan-space-${t}`,e);if(dn.set(t,s),tf())try{const r=new ef(`titan-space-${t}`,e,{signaling:["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com"]});yr.set(t,r)}catch{}}return us.get(t)}function nf(t){const{widgets:e}=wt(t),s=new Set,r=[];e.forEach((i,o)=>{const c=i.get("id");typeof c!="string"||s.has(c)?r.push(o):s.add(c)});for(let i=r.length-1;i>=0;i--)e.delete(r[i],1);return r.length}function wt(t){const e=sf(t),s=e.getArray("widgets"),r=e.getMap("meta"),i=dn.get(t);return{widgets:s,meta:r,doc:e,whenSynced:i!=null&&i.synced?Promise.resolve():new Promise(o=>{const c=()=>{i==null||i.off("synced",c),o()};i==null||i.on("synced",c),setTimeout(()=>o(),2e3)})}}function rf(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 rl(t){const e=new Tt;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 of(t){try{const e=typeof localStorage<"u"?localStorage.getItem("titan2-spaces"):null;if(!e)return null;const r=JSON.parse(e).find(o=>o.id===t);if(!r)return null;const i=new Set;for(const o of r.widgets||[])o&&typeof o.id=="string"&&i.add(o.id);return i}catch{return null}}const un=new Map;function af(t,e){let s=un.get(t);s||(s=new Set,un.set(t,s)),s.add(e)}function lf(t,e){var s;return((s=un.get(t))==null?void 0:s.has(e))??!1}function il(t){un.delete(t)}function cf(t,e){const{widgets:s}=wt(t),r=new Map,i=()=>{const c=new Set,d=of(t),l=[];s.forEach(p=>{const g=rf(p);if(!g.id||c.has(g.id))return;const u=g.format==="system",f=typeof g.source=="string"&&g.source.trim()!=="";!u&&!f||d&&!d.has(g.id)&&!lf(t,g.id)||(c.add(g.id),l.push(g))}),e(l)},o=()=>{const c=new Set;s.forEach(d=>c.add(d));for(const[d,l]of r)c.has(d)||(d.unobserve(l),r.delete(d));for(const d of c)if(!r.has(d)){const l=()=>i();d.observe(l),r.set(d,l)}i()};return s.observe(o),o(),()=>{s.unobserve(o);for(const[c,d]of r)c.unobserve(d);r.clear()}}function df(t,e){const{widgets:s}=wt(t),r={...e,id:`widget_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,createdAt:Date.now(),updatedAt:Date.now()};return af(t,r.id),s.push([rl(r)]),r}function uf(t,e){const{widgets:s}=wt(t);let r=-1;s.forEach((i,o)=>{i.get("id")===e&&(r=o)}),r>=0&&s.delete(r,1)}function Fi(t,e,s){const{widgets:r}=wt(t);r.forEach(i=>{if(i.get("id")===e){for(const[o,c]of Object.entries(s))i.set(o,c);i.set("updatedAt",Date.now())}})}function hf(t){const{widgets:e}=wt(t);e.delete(0,e.length),il(t)}function ff(t){var e,s,r;(e=dn.get(t))==null||e.destroy(),(s=yr.get(t))==null||s.destroy(),(r=us.get(t))==null||r.destroy(),dn.delete(t),yr.delete(t),us.delete(t),il(t)}const hs="titan2-spaces",pf=!0;function he(t,e,s,r,i,o,c){return{id:t,name:e,format:"system",source:s,x:r,y:i,w:o,h:c,createdAt:Date.now(),updatedAt:Date.now()}}const Os=[{id:"home",name:"Home",icon:"Home",color:"#6366f1",widgets:[he("home-welcome","Welcome","system:soma",0,0,6,5),he("home-voice","Voice","system:voice",6,0,6,5),he("home-overview","Overview","system:overview",0,5,6,5),he("home-sessions","Sessions","system:sessions",6,5,6,5),he("home-watch","Watch","system:watch",0,10,12,7)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"soma",name:"SOMA",icon:"Brain",color:"#8b5cf6",widgets:[he("soma-main","SOMA","system:soma",0,0,8,8),he("soma-memory","Memory Graph","system:memory-graph",8,0,4,8)],agentInstructions:"This is the SOMA consciousness space. Help the user explore consciousness, memory, and self-improvement.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"command",name:"Command Post",icon:"Terminal",color:"#ef4444",widgets:[he("cp-hub","Command Post","system:command-post",0,0,12,10),he("cp-proposals","Self-Proposals","system:self-proposals",0,10,12,6)],agentInstructions:"This is the Command Post. Help the user manage agents, runs, and operations.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"intelligence",name:"Intelligence",icon:"Network",color:"#10b981",widgets:[he("intel-autopilot","Autopilot","system:intelligence-autopilot",0,0,6,5),he("intel-workflows","Workflows","system:intelligence-workflows",6,0,6,5),he("intel-learning","Learning","system:intelligence-learning",0,5,6,5),he("intel-memory","Memory Graph","system:memory-graph",6,5,6,5),he("intel-selfimprove","Self-Improve","system:intelligence-self-improve",0,10,6,5),he("intel-personas","Personas","system:intelligence-personas",6,10,6,5),he("intel-wiki","Memory Wiki","system:memory-wiki",0,15,6,6),he("intel-autoresearch","Autoresearch","system:autoresearch",6,15,6,6)],agentInstructions:"This is the Intelligence space. Help the user explore memory graphs, wiki, and knowledge.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"infra",name:"Infrastructure",icon:"Server",color:"#f59e0b",widgets:[he("infra-homelab","Homelab","system:infra-homelab",0,0,6,6),he("infra-gpu","GPU / NVIDIA","system:infra-gpu",6,0,6,6),he("infra-files","Files","system:infra-files",0,6,4,5),he("infra-logs","Logs","system:infra-logs",4,6,4,5),he("infra-telemetry","Telemetry","system:infra-telemetry",8,6,4,5),he("infra-vram","VRAM","system:vram",0,11,6,5),he("infra-fleet","Fleet","system:fleet",6,11,6,5)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"tools",name:"Tools",icon:"Wrench",color:"#06b6d4",widgets:[he("tools-skills","Skills","system:tools-skills",0,0,6,6),he("tools-mcp","MCP Servers","system:tools-mcp",6,0,6,6),he("tools-integrations","Integrations","system:tools-integrations",0,6,4,5),he("tools-channels","Channels","system:tools-channels",4,6,4,5),he("tools-mesh","Mesh Network","system:tools-mesh",8,6,4,5),he("tools-recipes","Recipes","system:recipes",0,11,6,5),he("tools-browser","Browser","system:browser",6,11,6,5),he("tools-cron","Cron","system:cron",0,16,6,5)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"settings",name:"Settings",icon:"Settings",color:"#6b7280",widgets:[he("settings-specialists","Specialist Models","system:settings-specialists",0,0,6,8),he("settings-privacy","Privacy & Telemetry","system:settings-privacy",6,0,6,8),he("settings-general","General","system:settings-general",0,8,6,8),he("settings-security","Security","system:settings-security",6,8,6,8),he("settings-audit","Audit Log","system:settings-audit",0,16,12,6)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}],br=11,ol={home:new Set(["home-chat"]),tools:new Set(["tools-paperclip"])},xr=new Set(["system:paperclip","system:daemon"]);function mf(t,e){const{widgets:s,meta:r,whenSynced:i}=wt(t.id);i.then(()=>{try{const o=nf(t.id);o>0&&console.info(`[SpaceEngine] healed ${o} duplicate widget(s) in "${t.id}"`);const c=ol[t.id]??new Set;if(c.size>0||xr.size>0)for(let d=s.length-1;d>=0;d--){const l=s.get(d),p=l==null?void 0:l.get("id"),g=l==null?void 0:l.get("source"),u=typeof p=="string"&&c.has(p),f=typeof g=="string"&&xr.has(g);(u||f)&&s.delete(d,1)}if(e){for(let p=s.length-1;p>=0;p--){const g=s.get(p),u=g==null?void 0:g.get("source");(typeof u!="string"||u.trim()==="")&&s.delete(p,1)}const d=new Map;for(const p of t.widgets)d.set(p.id,p);const l=new Set;s.forEach(p=>{const g=p.get("id");if(typeof g=="string"&&d.has(g)){l.add(g);const u=d.get(g);p.set("x",u.x),p.set("y",u.y),p.set("w",u.w),p.set("h",u.h)}});for(const p of t.widgets)l.has(p.id)||s.push([rl(p)]);r.set("seedVersion",br)}}catch(o){console.warn(`[SpaceEngine] healYSpaceOnSync failed for "${t.id}":`,o)}})}function gf(){try{const t=localStorage.getItem(hs),s=parseInt(localStorage.getItem(`${hs}-version`)||"0",10)<br;if(pf)for(const o of Os)mf(o,s);if(!t||s){localStorage.setItem(`${hs}-version`,String(br));const o=Os.map(c=>({...c,widgets:[...c.widgets]}));return kt(o),o}const r=JSON.parse(t);for(const o of r)Array.isArray(o.widgets)||(o.widgets=[]),o.widgets=o.widgets.filter(c=>c&&typeof c.id=="string").filter(c=>{var d;return!(((d=ol[o.id])==null?void 0:d.has(c.id))??!1)}).filter(c=>!(typeof c.source=="string"&&xr.has(c.source))).map(c=>({...c,x:Number.isFinite(c.x)?Math.max(0,Math.floor(c.x)):0,y:Number.isFinite(c.y)?Math.max(0,Math.floor(c.y)):0,w:Number.isFinite(c.w)?Math.max(1,Math.floor(c.w)):4,h:Number.isFinite(c.h)?Math.max(1,Math.floor(c.h)):4}));for(const o of r){const c=new Set;o.widgets=o.widgets.filter(d=>c.has(d.id)?!1:(c.add(d.id),!0))}const i=new Map(r.map(o=>[o.id,o]));return Os.forEach(o=>{i.get(o.id)||i.set(o.id,{...o,widgets:[...o.widgets]})}),Array.from(i.values())}catch{return Os.map(t=>({...t,widgets:[...t.widgets]}))}}let Qn=null;function kt(t){Qn&&clearTimeout(Qn),Qn=setTimeout(()=>{localStorage.setItem(hs,JSON.stringify(t))},250)}let qe=null;const ke={list(){return qe||(qe=gf()),qe},get(t){return this.list().find(e=>e.id===t)},create(t){const e={id:`space_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,name:t,widgets:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return qe=[...this.list(),e],kt(qe),e},save(t){t.updatedAt=new Date().toISOString(),qe=this.list().map(e=>e.id===t.id?t:e),kt(qe)},remove(t){qe=this.list().filter(e=>e.id!==t),kt(qe)},addWidget(t,e){if(!e.source||e.source.trim()==="")throw new Error("Widget source cannot be empty");{const s=df(t,e);try{const r=localStorage.getItem(hs),i=r?JSON.parse(r):[],o=i.find(c=>c.id===t);if(o)new Set((o.widgets||[]).map(d=>d.id)).has(s.id)||(o.widgets=[...o.widgets||[],s]),o.updatedAt=new Date().toISOString(),qe=i,kt(i);else{const c={id:t,name:t,widgets:[s],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};qe=[...i,c],kt(qe)}}catch{}return s}},updateWidget(t,e,s){Fi(t,e,s);const r=this.get(t);r&&(r.widgets=r.widgets.map(i=>i.id===e?{...i,...s,updatedAt:Date.now()}:i),this.save(r))},removeWidget(t,e){uf(t,e);const s=this.get(t);s&&(s.widgets=s.widgets.filter(r=>r.id!==e),this.save(s))},updateLayout(t,e){for(const r of e)Fi(t,r.i,{x:r.x,y:r.y,w:r.w,h:r.h});const s=this.get(t);s&&(s.widgets=s.widgets.map(r=>{const i=e.find(o=>o&&o.i===r.id);return i?{...r,x:Number.isFinite(i.x)?Math.max(0,Math.floor(i.x)):0,y:Number.isFinite(i.y)?Math.max(0,Math.floor(i.y)):0,w:Number.isFinite(i.w)?Math.max(1,Math.floor(i.w)):4,h:Number.isFinite(i.h)?Math.max(1,Math.floor(i.h)):4,updatedAt:Date.now()}:r}),this.save(s))},observe(t,e){return cf(t,e)},async clearSpace(t){{const{whenSynced:r}=wt(t);await r,hf(t),ff(t);try{const i=indexedDB.deleteDatabase(`titan-space-${t}`);await new Promise((o,c)=>{i.onsuccess=()=>o(),i.onerror=()=>c(i.error),i.onblocked=()=>o()})}catch{}}const e=this.list(),s=e.find(r=>r.id===t);s&&(s.widgets=[],kt(e))}};let as=null;function yf(){if(as)return as;const t=async e=>{const s=await fetch(e,{credentials:"same-origin"});if(!s.ok)throw new Error(`Failed to load ${e}: ${s.status} ${s.statusText}`);return s.text()};return as=Promise.all([t("/react.development.js"),t("/react-dom.development.js"),t("/babel.min.js")]).then(([e,s,r])=>({react:e,reactDom:s,babel:r})).catch(e=>{throw as=null,e}),as}function bf(t){const e=xf;return`<!DOCTYPE html><html><head><meta charset="UTF-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'unsafe-inline'; img-src blob: data:; font-src data:;"><style>* { box-sizing: border-box; } html, body { margin: 0; padding: 0; height: 100%; } body { background: transparent; color: #e5e7eb; font-family: system-ui, -apple-system, sans-serif; font-size: 13px; overflow: hidden; } #root { width: 100%; height: 100%; }</style></head><body><div id="root"><div id="sandbox-loading" style="padding:16px;font-family:monospace;font-size:12px;color:#52525b;"><div>Booting widget…</div></div></div><script>`+t.react+"<\/script><script>"+t.reactDom+"<\/script><script>"+t.babel+"<\/script>"+e}const xf=`
32
+ */const sc=[["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"}]],bo=ts("layout-grid",sc),Fe=()=>new Map,rr=t=>{const e=Fe();return t.forEach((s,r)=>{e.set(r,s)}),e},Ve=(t,e,s)=>{let r=t.get(e);return r===void 0&&t.set(e,r=s()),r},nc=(t,e)=>{const s=[];for(const[r,i]of t)s.push(e(i,r));return s},rc=(t,e)=>{for(const[s,r]of t)if(e(r,s))return!0;return!1},bt=()=>new Set,Mn=t=>t[t.length-1],ic=(t,e)=>{for(let s=0;s<e.length;s++)t.push(e[s])},ct=Array.from,Ar=(t,e)=>{for(let s=0;s<t.length;s++)if(!e(t[s],s,t))return!1;return!0},xo=(t,e)=>{for(let s=0;s<t.length;s++)if(e(t[s],s,t))return!0;return!1},oc=(t,e)=>{const s=new Array(t);for(let r=0;r<t;r++)s[r]=e(r,s);return s},yn=Array.isArray;class wo{constructor(){this._observers=Fe()}on(e,s){return Ve(this._observers,e,bt).add(s),s}once(e,s){const r=(...i)=>{this.off(e,r),s(...i)};this.on(e,r)}off(e,s){const r=this._observers.get(e);r!==void 0&&(r.delete(s),r.size===0&&this._observers.delete(e))}emit(e,s){return ct((this._observers.get(e)||Fe()).values()).forEach(r=>r(...s))}destroy(){this._observers=Fe()}}class Lr{constructor(){this._observers=Fe()}on(e,s){Ve(this._observers,e,bt).add(s)}once(e,s){const r=(...i)=>{this.off(e,r),s(...i)};this.on(e,r)}off(e,s){const r=this._observers.get(e);r!==void 0&&(r.delete(s),r.size===0&&this._observers.delete(e))}emit(e,s){return ct((this._observers.get(e)||Fe()).values()).forEach(r=>r(...s))}destroy(){this._observers=Fe()}}const Xe=Math.floor,$s=Math.abs,ac=Math.log10,Ir=(t,e)=>t<e?t:e,Lt=(t,e)=>t>e?t:e,vo=t=>t!==0?t<0:1/t<0,fi=1,pi=2,On=4,Pn=8,ms=32,at=64,He=128,bn=31,ir=63,St=127,lc=2147483647,qs=Number.MAX_SAFE_INTEGER,mi=Number.MIN_SAFE_INTEGER,cc=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&Xe(t)===t),_o=String.fromCharCode,dc=t=>t.toLowerCase(),uc=/^\s*/g,hc=t=>t.replace(uc,""),fc=/([A-Z])/g,gi=(t,e)=>hc(t.replace(fc,s=>`${e}${dc(s)}`)),pc=t=>{const e=unescape(encodeURIComponent(t)),s=e.length,r=new Uint8Array(s);for(let i=0;i<s;i++)r[i]=e.codePointAt(i);return r},gs=typeof TextEncoder<"u"?new TextEncoder:null,mc=t=>gs.encode(t),or=gs?mc:pc;let ds=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ds&&ds.decode(new Uint8Array).length===1&&(ds=null);const gc=(t,e)=>oc(e,()=>t).join("");class Es{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const De=()=>new Es,yc=t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e},Se=t=>{const e=new Uint8Array(yc(t));let s=0;for(let r=0;r<t.bufs.length;r++){const i=t.bufs[r];e.set(i,s),s+=i.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},bc=(t,e)=>{const s=t.cbuf.length;s-t.cpos<e&&(t.bufs.push(new Uint8Array(t.cbuf.buffer,0,t.cpos)),t.cbuf=new Uint8Array(Lt(s,e)*2),t.cpos=0)},Le=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(s*2),t.cpos=0),t.cbuf[t.cpos++]=e},ys=Le,ie=(t,e)=>{for(;e>St;)Le(t,He|St&e),e=Xe(e/128);Le(t,St&e)},Dr=(t,e)=>{const s=vo(e);for(s&&(e=-e),Le(t,(e>ir?He:0)|(s?at:0)|ir&e),e=Xe(e/64);e>0;)Le(t,(e>St?He:0)|St&e),e=Xe(e/128)},ar=new Uint8Array(3e4),xc=ar.length/3,wc=(t,e)=>{if(e.length<xc){const s=gs.encodeInto(e,ar).written||0;ie(t,s);for(let r=0;r<s;r++)Le(t,ar[r])}else je(t,or(e))},vc=(t,e)=>{const s=unescape(encodeURIComponent(e)),r=s.length;ie(t,r);for(let i=0;i<r;i++)Le(t,s.codePointAt(i))},st=gs&&gs.encodeInto?wc:vc,xn=(t,e)=>{const s=t.cbuf.length,r=t.cpos,i=Ir(s-r,e.length),o=e.length-i;t.cbuf.set(e.subarray(0,i),r),t.cpos+=i,o>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(Lt(s*2,o)),t.cbuf.set(e.subarray(i)),t.cpos=o)},je=(t,e)=>{ie(t,e.byteLength),xn(t,e)},Mr=(t,e)=>{bc(t,e);const s=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,s},_c=(t,e)=>Mr(t,4).setFloat32(0,e,!1),kc=(t,e)=>Mr(t,8).setFloat64(0,e,!1),Sc=(t,e)=>Mr(t,8).setBigInt64(0,e,!1),yi=new DataView(new ArrayBuffer(4)),jc=t=>(yi.setFloat32(0,t),yi.getFloat32(0)===t),Gt=(t,e)=>{switch(typeof e){case"string":Le(t,119),st(t,e);break;case"number":cc(e)&&$s(e)<=lc?(Le(t,125),Dr(t,e)):jc(e)?(Le(t,124),_c(t,e)):(Le(t,123),kc(t,e));break;case"bigint":Le(t,122),Sc(t,e);break;case"object":if(e===null)Le(t,126);else if(yn(e)){Le(t,117),ie(t,e.length);for(let s=0;s<e.length;s++)Gt(t,e[s])}else if(e instanceof Uint8Array)Le(t,116),je(t,e);else{Le(t,118);const s=Object.keys(e);ie(t,s.length);for(let r=0;r<s.length;r++){const i=s[r];st(t,i),Gt(t,e[i])}}break;case"boolean":Le(t,e?120:121);break;default:Le(t,127)}};class bi extends Es{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&ie(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const xi=t=>{t.count>0&&(Dr(t.encoder,t.count===1?t.s:-t.s),t.count>1&&ie(t.encoder,t.count-2))};class zs{constructor(){this.encoder=new Es,this.s=0,this.count=0}write(e){this.s===e?this.count++:(xi(this),this.count=1,this.s=e)}toUint8Array(){return xi(this),Se(this.encoder)}}const wi=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);Dr(t.encoder,e),t.count>1&&ie(t.encoder,t.count-2)}};class Wn{constructor(){this.encoder=new Es,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(wi(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return wi(this),Se(this.encoder)}}class Ec{constructor(){this.sarr=[],this.s="",this.lensE=new zs}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 Es;return this.sarr.push(this.s),this.s="",st(e,this.sarr.join("")),xn(e,this.lensE.toUint8Array()),Se(e)}}const Ge=t=>new Error(t),Ze=()=>{throw Ge("Method unimplemented")},Qe=()=>{throw Ge("Unexpected case")},ko=Ge("Unexpected end of array"),So=Ge("Integer out of Range");class wn{constructor(e){this.arr=e,this.pos=0}}const it=t=>new wn(t),Nc=t=>t.pos!==t.arr.length,Cc=(t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s},Ie=t=>Cc(t,de(t)),Et=t=>t.arr[t.pos++],de=t=>{let e=0,s=1;const r=t.arr.length;for(;t.pos<r;){const i=t.arr[t.pos++];if(e=e+(i&St)*s,s*=128,i<He)return e;if(e>qs)throw So}throw ko},Or=t=>{let e=t.arr[t.pos++],s=e&ir,r=64;const i=(e&at)>0?-1:1;if((e&He)===0)return i*s;const o=t.arr.length;for(;t.pos<o;){if(e=t.arr[t.pos++],s=s+(e&St)*r,r*=128,e<He)return i*s;if(s>qs)throw So}throw ko},Tc=t=>{let e=de(t);if(e===0)return"";{let s=String.fromCodePoint(Et(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(Et(t));else for(;e>0;){const r=e<1e4?e:1e4,i=t.arr.subarray(t.pos,t.pos+r);t.pos+=r,s+=String.fromCodePoint.apply(null,i),e-=r}return decodeURIComponent(escape(s))}},Rc=t=>ds.decode(Ie(t)),lt=ds?Rc:Tc,Pr=(t,e)=>{const s=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,s},Ac=t=>Pr(t,4).getFloat32(0,!1),Lc=t=>Pr(t,8).getFloat64(0,!1),Ic=t=>Pr(t,8).getBigInt64(0,!1),Dc=[t=>{},t=>null,Or,Ac,Lc,Ic,t=>!1,t=>!0,lt,t=>{const e=de(t),s={};for(let r=0;r<e;r++){const i=lt(t);s[i]=qt(t)}return s},t=>{const e=de(t),s=[];for(let r=0;r<e;r++)s.push(qt(t));return s},Ie],qt=t=>Dc[127-Et(t)](t);class vi extends wn{constructor(e,s){super(e),this.reader=s,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Nc(this)?this.count=de(this)+1:this.count=-1),this.count--,this.s}}class Hs extends wn{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Or(this);const e=vo(this.s);this.count=1,e&&(this.s=-this.s,this.count=de(this)+2)}return this.count--,this.s}}class Bn extends wn{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Or(this),s=e&1;this.diff=Xe(e/2),this.count=1,s&&(this.count=de(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Mc{constructor(e){this.decoder=new Hs(e),this.str=lt(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 Oc=crypto.getRandomValues.bind(crypto),Pc=Math.random,jo=()=>Oc(new Uint32Array(1))[0],Wc="10000000-1000-4000-8000"+-1e11,Eo=()=>Wc.replace(/[018]/g,t=>(t^jo()&15>>t/4).toString(16)),dt=Date.now,Yt=t=>new Promise(t);Promise.all.bind(Promise);const Bc=t=>Promise.reject(t),Wr=t=>Promise.resolve(t),_i=t=>t===void 0?null:t;class Uc{constructor(){this.map=new Map}setItem(e,s){this.map.set(e,s)}getItem(e){return this.map.get(e)}}let No=new Uc,Br=!0;try{typeof localStorage<"u"&&localStorage&&(No=localStorage,Br=!1)}catch{}const Co=No,Fc=t=>Br||addEventListener("storage",t),$c=t=>Br||removeEventListener("storage",t),bs=Symbol("Equality"),To=(t,e)=>{var s;return t===e||!!((s=t==null?void 0:t[bs])!=null&&s.call(t,e))||!1},zc=t=>typeof t=="object",Hc=Object.assign,Vc=Object.keys,Gc=(t,e)=>{for(const s in t)e(t[s],s)},Ys=t=>Vc(t).length,qc=t=>{for(const e in t)return!1;return!0},Ns=(t,e)=>{for(const s in t)if(!e(t[s],s))return!1;return!0},Ur=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Yc=(t,e)=>t===e||Ys(t)===Ys(e)&&Ns(t,(s,r)=>(s!==void 0||Ur(e,r))&&To(e[r],s)),Kc=Object.freeze,Ro=t=>{for(const e in t){const s=t[e];(typeof s=="object"||typeof s=="function")&&Ro(t[e])}return Kc(t)},Fr=(t,e,s=0)=>{try{for(;s<t.length;s++)t[s](...e)}finally{s<t.length&&Fr(t,e,s+1)}},Jc=()=>{},Xc=t=>t,Ut=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[bs]!=null)return t[bs](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;break}case Set:{if(t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;break}case Map:{if(t.size!==e.size)return!1;for(const s of t.keys())if(!e.has(s)||!Ut(t.get(s),e.get(s)))return!1;break}case void 0:case Object:if(Ys(t)!==Ys(e))return!1;for(const s in t)if(!Ur(t,s)||!Ut(t[s],e[s]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Ut(t[s],e[s]))return!1;break;default:return!1}return!0},Qc=(t,e)=>e.includes(t);var Ao={};const Kt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",Lo=typeof window<"u"&&typeof document<"u"&&!Kt;let tt;const Zc=()=>{if(tt===void 0)if(Kt){tt=Fe();const t=process.argv;let e=null;for(let s=0;s<t.length;s++){const r=t[s];r[0]==="-"?(e!==null&&tt.set(e,""),e=r):e!==null&&(tt.set(e,r),e=null)}e!==null&&tt.set(e,"")}else typeof location=="object"?(tt=Fe(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,s]=t.split("=");tt.set(`--${gi(e,"-")}`,s),tt.set(`-${gi(e,"-")}`,s)}})):tt=Fe();return tt},lr=t=>Zc().has(t),xs=t=>_i(Kt?Ao[t.toUpperCase().replaceAll("-","_")]:Co.getItem(t)),Io=t=>lr("--"+t)||xs(t)!==null,ed=Io("production"),td=Kt&&Qc(Ao.FORCE_COLOR,["true","1","2"]),sd=td||!lr("--no-colors")&&!Io("no-color")&&(!Kt||process.stdout.isTTY)&&(!Kt||lr("--color")||xs("COLORTERM")!==null||(xs("TERM")||"").includes("color")),Do=t=>new Uint8Array(t),nd=(t,e,s)=>new Uint8Array(t,e,s),rd=t=>new Uint8Array(t),id=t=>{let e="";for(let s=0;s<t.byteLength;s++)e+=_o(t[s]);return btoa(e)},od=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),ad=t=>{const e=atob(t),s=Do(e.length);for(let r=0;r<e.length;r++)s[r]=e.charCodeAt(r);return s},ld=t=>{const e=Buffer.from(t,"base64");return nd(e.buffer,e.byteOffset,e.byteLength)},Mo=Lo?id:od,Oo=Lo?ad:ld,cd=t=>{const e=Do(t.byteLength);return e.set(t),e};class dd{constructor(e,s){this.left=e,this.right=s}}const ot=(t,e)=>new dd(t,e),ki=t=>t.next()>=.5,Un=(t,e,s)=>Xe(t.next()*(s+1-e)+e),Po=(t,e,s)=>Xe(t.next()*(s+1-e)+e),$r=(t,e,s)=>Po(t,e,s),ud=t=>_o($r(t,97,122)),hd=(t,e=0,s=20)=>{const r=$r(t,e,s);let i="";for(let o=0;o<r;o++)i+=ud(t);return i},Fn=(t,e)=>e[$r(t,0,e.length-1)],fd=Symbol("0schema");class pd{constructor(){this._rerrs=[]}extend(e,s,r,i=null){this._rerrs.push({path:e,expected:s,has:r,message:i})}toString(){const e=[];for(let s=this._rerrs.length-1;s>0;s--){const r=this._rerrs[s];e.push(gc(" ",(this._rerrs.length-s)*2)+`${r.path!=null?`[${r.path}] `:""}${r.has} doesn't match ${r.expected}. ${r.message}`)}return e.join(`
33
+ `)}}const cr=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[bs]?To(t,e):yn(t)?Ar(t,s=>xo(e,r=>cr(s,r))):zc(t)?Ns(t,(s,r)=>cr(s,e[r])):!1;class Ue{extends(e){let[s,r]=[this.shape,e.shape];return this.constructor._dilutes&&([r,s]=[s,r]),cr(s,r)}equals(e){return this.constructor===e.constructor&&Ut(this.shape,e.shape)}[fd](){return!0}[bs](e){return this.equals(e)}validate(e){return this.check(e)}check(e,s){Ze()}get nullable(){return ss(this,jn)}get optional(){return new Uo(this)}cast(e){return Si(e,this),e}expect(e){return Si(e,this),e}}$e(Ue,"_dilutes",!1);class zr extends Ue{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s=void 0){const r=(e==null?void 0:e.constructor)===this.shape&&(this._c==null||this._c(e));return!r&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name,(e==null?void 0:e.constructor)!==this.shape?"Constructor match failed":"Check failed")),r}}const Ne=(t,e=null)=>new zr(t,e);Ne(zr);class Hr extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=this.shape(e);return!r&&(s==null||s.extend(null,"custom prop",e==null?void 0:e.constructor.name,"failed to check custom prop")),r}}const Oe=t=>new Hr(t);Ne(Hr);class vn extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=this.shape.some(i=>i===e);return!r&&(s==null||s.extend(null,this.shape.join(" | "),e.toString())),r}}const _n=(...t)=>new vn(t),Wo=Ne(vn),md=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Bo=t=>{if(Jt.check(t))return[md(t)];if(Wo.check(t))return t.shape.map(e=>e+"");if(Ko.check(t))return["[+-]?\\d+.?\\d*"];if(Jo.check(t))return[".*"];if(Js.check(t))return t.shape.map(Bo).flat(1);Qe()};class gd extends Ue{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Bo).map(s=>`(${s.join("|")})`).join("")+"$")}check(e,s){const r=this._r.exec(e)!=null;return!r&&(s==null||s.extend(null,this._r.toString(),e.toString(),"String doesn't match string template.")),r}}Ne(gd);const yd=Symbol("optional");class Uo extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=e===void 0||this.shape.check(e);return!r&&(s==null||s.extend(null,"undefined (optional)","()")),r}get[yd](){return!0}}const bd=Ne(Uo);class xd extends Ue{check(e,s){return s==null||s.extend(null,"never",typeof e),!1}}Ne(xd);const hn=class hn extends Ue{constructor(e,s=!1){super(),this.shape=e,this._isPartial=s}get partial(){return new hn(this.shape,!0)}check(e,s){return e==null?(s==null||s.extend(null,"object","null"),!1):Ns(this.shape,(r,i)=>{const o=this._isPartial&&!Ur(e,i)||r.check(e[i],s);return!o&&(s==null||s.extend(i.toString(),r.toString(),typeof e[i],"Object property does not match")),o})}};$e(hn,"_dilutes",!0);let Ks=hn;const wd=t=>new Ks(t),vd=Ne(Ks),_d=Oe(t=>t!=null&&(t.constructor===Object||t.constructor==null));class Fo extends Ue{constructor(e,s){super(),this.shape={keys:e,values:s}}check(e,s){return e!=null&&Ns(e,(r,i)=>{const o=this.shape.keys.check(i,s);return!o&&(s==null||s.extend(i+"","Record",typeof e,o?"Key doesn't match schema":"Value doesn't match value")),o&&this.shape.values.check(r,s)})}}const $o=(t,e)=>new Fo(t,e),kd=Ne(Fo);class zo extends Ue{constructor(e){super(),this.shape=e}check(e,s){return e!=null&&Ns(this.shape,(r,i)=>{const o=r.check(e[i],s);return!o&&(s==null||s.extend(i.toString(),"Tuple",typeof r)),o})}}const Sd=(...t)=>new zo(t);Ne(zo);class Ho extends Ue{constructor(e){super(),this.shape=e.length===1?e[0]:new kn(e)}check(e,s){const r=yn(e)&&Ar(e,i=>this.shape.check(i));return!r&&(s==null||s.extend(null,"Array","")),r}}const Vo=(...t)=>new Ho(t),jd=Ne(Ho),Ed=Oe(t=>yn(t));class Go extends Ue{constructor(e,s){super(),this.shape=e,this._c=s}check(e,s){const r=e instanceof this.shape&&(this._c==null||this._c(e));return!r&&(s==null||s.extend(null,this.shape.name,e==null?void 0:e.constructor.name)),r}}const Nd=(t,e=null)=>new Go(t,e);Ne(Go);const Cd=Nd(Ue);class Td extends Ue{constructor(e){super(),this.len=e.length-1,this.args=Sd(...e.slice(-1)),this.res=e[this.len]}check(e,s){const r=e.constructor===Function&&e.length<=this.len;return!r&&(s==null||s.extend(null,"function",typeof e)),r}}const Rd=Ne(Td),Ad=Oe(t=>typeof t=="function");class Ld extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=Ar(this.shape,i=>i.check(e,s));return!r&&(s==null||s.extend(null,"Intersectinon",typeof e)),r}}Ne(Ld,t=>t.shape.length>0);class kn extends Ue{constructor(e){super(),this.shape=e}check(e,s){const r=xo(this.shape,i=>i.check(e,s));return s==null||s.extend(null,"Union",typeof e),r}}$e(kn,"_dilutes",!0);const ss=(...t)=>t.findIndex(e=>Js.check(e))>=0?ss(...t.map(e=>ws(e)).map(e=>Js.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new kn(t),Js=Ne(kn),qo=()=>!0,Xs=Oe(qo),Id=Ne(Hr,t=>t.shape===qo),Vr=Oe(t=>typeof t=="bigint"),Dd=Oe(t=>t===Vr),Yo=Oe(t=>typeof t=="symbol");Oe(t=>t===Yo);const Ft=Oe(t=>typeof t=="number"),Ko=Oe(t=>t===Ft),Jt=Oe(t=>typeof t=="string"),Jo=Oe(t=>t===Jt),Sn=Oe(t=>typeof t=="boolean"),Md=Oe(t=>t===Sn),Xo=_n(void 0);Ne(vn,t=>t.shape.length===1&&t.shape[0]===void 0);_n(void 0);const jn=_n(null),Od=Ne(vn,t=>t.shape.length===1&&t.shape[0]===null);Ne(Uint8Array);Ne(zr,t=>t.shape===Uint8Array);const Pd=ss(Ft,Jt,jn,Xo,Vr,Sn,Yo);(()=>{const t=Vo(Xs),e=$o(Jt,Xs),s=ss(Ft,Jt,jn,Sn,t,e);return t.shape=s,e.shape.values=s,s})();const ws=t=>{if(Cd.check(t))return t;if(_d.check(t)){const e={};for(const s in t)e[s]=ws(t[s]);return wd(e)}else{if(Ed.check(t))return ss(...t.map(ws));if(Pd.check(t))return _n(t);if(Ad.check(t))return Ne(t)}Qe()},Si=ed?()=>{}:(t,e)=>{const s=new pd;if(!e.check(t,s))throw Ge(`Expected value to be of type ${e.constructor.name}.
34
+ ${s.toString()}`)};class Wd{constructor(e){this.patterns=[],this.$state=e}if(e,s){return this.patterns.push({if:ws(e),h:s}),this}else(e){return this.if(Xs,e)}done(){return(e,s)=>{for(let r=0;r<this.patterns.length;r++){const i=this.patterns[r];if(i.if.check(e))return i.h(e,s)}throw Ge("Unhandled pattern")}}}const Bd=t=>new Wd(t),Qo=Bd(Xs).if(Ko,(t,e)=>Un(e,mi,qs)).if(Jo,(t,e)=>hd(e)).if(Md,(t,e)=>ki(e)).if(Dd,(t,e)=>BigInt(Un(e,mi,qs))).if(Js,(t,e)=>Wt(e,Fn(e,t.shape))).if(vd,(t,e)=>{const s={};for(const r in t.shape){let i=t.shape[r];if(bd.check(i)){if(ki(e))continue;i=i.shape}s[r]=Qo(i,e)}return s}).if(jd,(t,e)=>{const s=[],r=Po(e,0,42);for(let i=0;i<r;i++)s.push(Wt(e,t.shape));return s}).if(Wo,(t,e)=>Fn(e,t.shape)).if(Od,(t,e)=>null).if(Rd,(t,e)=>{const s=Wt(e,t.res);return()=>s}).if(Id,(t,e)=>Wt(e,Fn(e,[Ft,Jt,jn,Xo,Vr,Sn,Vo(Ft),$o(ss("a","b","c"),Ft)]))).if(kd,(t,e)=>{const s={},r=Un(e,0,3);for(let i=0;i<r;i++){const o=Wt(e,t.shape.keys),c=Wt(e,t.shape.values);s[o]=c}return s}).done(),Wt=(t,e)=>Qo(ws(e),t),En=typeof document<"u"?document:{};Oe(t=>t.nodeType===Hd);typeof DOMParser<"u"&&new DOMParser;Oe(t=>t.nodeType===Fd);Oe(t=>t.nodeType===$d);const Ud=t=>nc(t,(e,s)=>`${s}:${e};`).join(""),Fd=En.ELEMENT_NODE,$d=En.TEXT_NODE,zd=En.DOCUMENT_NODE,Hd=En.DOCUMENT_FRAGMENT_NODE;Oe(t=>t.nodeType===zd);const Vd=JSON.stringify,ht=Symbol,Je=ht(),Nt=ht(),Zo=ht(),Gr=ht(),ea=ht(),ta=ht(),sa=ht(),Nn=ht(),Cn=ht(),Gd=t=>{var i;t.length===1&&((i=t[0])==null?void 0:i.constructor)===Function&&(t=t[0]());const e=[],s=[];let r=0;for(;r<t.length;r++){const o=t[r];if(o===void 0)break;if(o.constructor===String||o.constructor===Number)e.push(o);else if(o.constructor===Object)break}for(r>0&&s.push(e.join(""));r<t.length;r++){const o=t[r];o instanceof Symbol||s.push(o)}return s},ji=[ea,sa,Nn,Zo];let $n=0,Ei=dt();const qd=(t,e)=>{const s=ji[$n],r=xs("log"),i=r!==null&&(r==="*"||r==="true"||new RegExp(r,"gi").test(e));return $n=($n+1)%ji.length,e+=": ",i?(...o)=>{var l;o.length===1&&((l=o[0])==null?void 0:l.constructor)===Function&&(o=o[0]());const c=dt(),d=c-Ei;Ei=c,t(s,e,Cn,...o.map(p=>{switch(p!=null&&p.constructor===Uint8Array&&(p=Array.from(p)),typeof p){case"string":case"symbol":return p;default:return Vd(p)}}),s," +"+d+"ms")}:Jc},Yd={[Je]:ot("font-weight","bold"),[Nt]:ot("font-weight","normal"),[Zo]:ot("color","blue"),[ea]:ot("color","green"),[Gr]:ot("color","grey"),[ta]:ot("color","red"),[sa]:ot("color","purple"),[Nn]:ot("color","orange"),[Cn]:ot("color","black")},Kd=t=>{var c;t.length===1&&((c=t[0])==null?void 0:c.constructor)===Function&&(t=t[0]());const e=[],s=[],r=Fe();let i=[],o=0;for(;o<t.length;o++){const d=t[o],l=Yd[d];if(l!==void 0)r.set(l.left,l.right);else{if(d===void 0)break;if(d.constructor===String||d.constructor===Number){const p=Ud(r);o>0||p.length>0?(e.push("%c"+d),s.push(p)):e.push(d)}else break}}for(o>0&&(i=s,i.unshift(e.join("")));o<t.length;o++){const d=t[o];d instanceof Symbol||i.push(d)}return i},na=sd?Kd:Gd,ra=(...t)=>{console.log(...na(t)),ia.forEach(e=>e.print(t))},Jd=(...t)=>{console.warn(...na(t)),t.unshift(Nn),ia.forEach(e=>e.print(t))},ia=bt(),Xd=t=>qd(ra,t),oa=t=>({[Symbol.iterator](){return this},next:t}),Qd=(t,e)=>oa(()=>{let s;do s=t.next();while(!s.done&&!e(s.value));return s}),zn=(t,e)=>oa(()=>{const{done:s,value:r}=t.next();return{done:s,value:s?void 0:e(r)}});class Tn{constructor(e,s){this.clock=e,this.len=s}}class Cs{constructor(){this.clients=new Map}}const aa=(t,e,s)=>e.clients.forEach((r,i)=>{const o=t.doc.store.clients.get(i);if(o!=null){const c=o[o.length-1],d=c.id.clock+c.length;for(let l=0,p=r[l];l<r.length&&p.clock<d;p=r[++l])va(t,o,p.clock,p.len,s)}}),Zd=(t,e)=>{let s=0,r=t.length-1;for(;s<=r;){const i=Xe((s+r)/2),o=t[i],c=o.clock;if(c<=e){if(e<c+o.len)return i;s=i+1}else r=i-1}return null},la=(t,e)=>{const s=t.clients.get(e.client);return s!==void 0&&Zd(s,e.clock)!==null},qr=t=>{t.clients.forEach(e=>{e.sort((i,o)=>i.clock-o.clock);let s,r;for(s=1,r=1;s<e.length;s++){const i=e[r-1],o=e[s];i.clock+i.len>=o.clock?e[r-1]=new Tn(i.clock,Lt(i.len,o.clock+o.len-i.clock)):(r<s&&(e[r]=o),r++)}e.length=r})},eu=t=>{const e=new Cs;for(let s=0;s<t.length;s++)t[s].clients.forEach((r,i)=>{if(!e.clients.has(i)){const o=r.slice();for(let c=s+1;c<t.length;c++)ic(o,t[c].clients.get(i)||[]);e.clients.set(i,o)}});return qr(e),e},Qs=(t,e,s,r)=>{Ve(t.clients,e,()=>[]).push(new Tn(s,r))},tu=()=>new Cs,su=t=>{const e=tu();return t.clients.forEach((s,r)=>{const i=[];for(let o=0;o<s.length;o++){const c=s[o];if(c.deleted){const d=c.id.clock;let l=c.length;if(o+1<s.length)for(let p=s[o+1];o+1<s.length&&p.deleted;p=s[++o+1])l+=p.length;i.push(new Tn(d,l))}}i.length>0&&e.clients.set(r,i)}),e},ns=(t,e)=>{ie(t.restEncoder,e.clients.size),ct(e.clients.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{t.resetDsCurVal(),ie(t.restEncoder,s);const i=r.length;ie(t.restEncoder,i);for(let o=0;o<i;o++){const c=r[o];t.writeDsClock(c.clock),t.writeDsLen(c.len)}})},Yr=t=>{const e=new Cs,s=de(t.restDecoder);for(let r=0;r<s;r++){t.resetDsCurVal();const i=de(t.restDecoder),o=de(t.restDecoder);if(o>0){const c=Ve(e.clients,i,()=>[]);for(let d=0;d<o;d++)c.push(new Tn(t.readDsClock(),t.readDsLen()))}}return e},Ni=(t,e,s)=>{const r=new Cs,i=de(t.restDecoder);for(let o=0;o<i;o++){t.resetDsCurVal();const c=de(t.restDecoder),d=de(t.restDecoder),l=s.clients.get(c)||[],p=Me(s,c);for(let g=0;g<d;g++){const u=t.readDsClock(),f=u+t.readDsLen();if(u<p){p<f&&Qs(r,c,p,f-p);let x=nt(l,u),y=l[x];for(!y.deleted&&y.id.clock<u&&(l.splice(x+1,0,on(e,y,u-y.id.clock)),x++);x<l.length&&(y=l[x++],y.id.clock<f);)y.deleted||(f<y.id.clock+y.length&&l.splice(x,0,on(e,y,f-y.id.clock)),y.delete(e))}else Qs(r,c,u,f-u)}}if(r.clients.size>0){const o=new Ct;return ie(o.restEncoder,0),ns(o,r),o.toUint8Array()}return null},ca=jo;class rs extends wo{constructor({guid:e=Eo(),collectionid:s=null,gc:r=!0,gcFilter:i=()=>!0,meta:o=null,autoLoad:c=!1,shouldLoad:d=!0}={}){super(),this.gc=r,this.gcFilter=i,this.clientID=ca(),this.guid=e,this.collectionid=s,this.share=new Map,this.store=new xa,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=d,this.autoLoad=c,this.meta=o,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Yt(p=>{this.on("load",()=>{this.isLoaded=!0,p(this)})});const l=()=>Yt(p=>{const g=u=>{(u===void 0||u===!0)&&(this.off("sync",g),p())};this.on("sync",g)});this.on("sync",p=>{p===!1&&this.isSynced&&(this.whenSynced=l()),this.isSynced=p===void 0||p===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;e!==null&&!this.shouldLoad&&we(e.parent.doc,s=>{s.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(ct(this.subdocs).map(e=>e.guid))}transact(e,s=null){return we(this,e,s)}get(e,s=We){const r=Ve(this.share,e,()=>{const o=new s;return o._integrate(this,null),o}),i=r.constructor;if(s!==We&&i!==s)if(i===We){const o=new s;o._map=r._map,r._map.forEach(c=>{for(;c!==null;c=c.left)c.parent=o}),o._start=r._start;for(let c=o._start;c!==null;c=c.right)c.parent=o;return o._length=r._length,this.share.set(e,o),o._integrate(this,null),o}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return r}getArray(e=""){return this.get(e,zt)}getText(e=""){return this.get(e,Qt)}getMap(e=""){return this.get(e,Tt)}getXmlElement(e=""){return this.get(e,Zt)}getXmlFragment(e=""){return this.get(e,Rt)}toJSON(){const e={};return this.share.forEach((s,r)=>{e[r]=s.toJSON()}),e}destroy(){this.isDestroyed=!0,ct(this.subdocs).forEach(s=>s.destroy());const e=this._item;if(e!==null){this._item=null;const s=e.content;s.doc=new rs({guid:this.guid,...s.opts,shouldLoad:!1}),s.doc._item=e,we(e.parent.doc,r=>{const i=s.doc;e.deleted||r.subdocsAdded.add(i),r.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class da{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return de(this.restDecoder)}readDsLen(){return de(this.restDecoder)}}class ua extends da{readLeftID(){return me(de(this.restDecoder),de(this.restDecoder))}readRightID(){return me(de(this.restDecoder),de(this.restDecoder))}readClient(){return de(this.restDecoder)}readInfo(){return Et(this.restDecoder)}readString(){return lt(this.restDecoder)}readParentInfo(){return de(this.restDecoder)===1}readTypeRef(){return de(this.restDecoder)}readLen(){return de(this.restDecoder)}readAny(){return qt(this.restDecoder)}readBuf(){return cd(Ie(this.restDecoder))}readJSON(){return JSON.parse(lt(this.restDecoder))}readKey(){return lt(this.restDecoder)}}class nu{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=de(this.restDecoder),this.dsCurrVal}readDsLen(){const e=de(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Xt extends nu{constructor(e){super(e),this.keys=[],de(e),this.keyClockDecoder=new Bn(Ie(e)),this.clientDecoder=new Hs(Ie(e)),this.leftClockDecoder=new Bn(Ie(e)),this.rightClockDecoder=new Bn(Ie(e)),this.infoDecoder=new vi(Ie(e),Et),this.stringDecoder=new Mc(Ie(e)),this.parentInfoDecoder=new vi(Ie(e),Et),this.typeRefDecoder=new Hs(Ie(e)),this.lenDecoder=new Hs(Ie(e))}readLeftID(){return new $t(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new $t(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 qt(this.restDecoder)}readBuf(){return Ie(this.restDecoder)}readJSON(){return qt(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 ha{constructor(){this.restEncoder=De()}toUint8Array(){return Se(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ie(this.restEncoder,e)}writeDsLen(e){ie(this.restEncoder,e)}}class Ts extends ha{writeLeftID(e){ie(this.restEncoder,e.client),ie(this.restEncoder,e.clock)}writeRightID(e){ie(this.restEncoder,e.client),ie(this.restEncoder,e.clock)}writeClient(e){ie(this.restEncoder,e)}writeInfo(e){ys(this.restEncoder,e)}writeString(e){st(this.restEncoder,e)}writeParentInfo(e){ie(this.restEncoder,e?1:0)}writeTypeRef(e){ie(this.restEncoder,e)}writeLen(e){ie(this.restEncoder,e)}writeAny(e){Gt(this.restEncoder,e)}writeBuf(e){je(this.restEncoder,e)}writeJSON(e){st(this.restEncoder,JSON.stringify(e))}writeKey(e){st(this.restEncoder,e)}}class fa{constructor(){this.restEncoder=De(),this.dsCurrVal=0}toUint8Array(){return Se(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const s=e-this.dsCurrVal;this.dsCurrVal=e,ie(this.restEncoder,s)}writeDsLen(e){e===0&&Qe(),ie(this.restEncoder,e-1),this.dsCurrVal+=e}}class Ct extends fa{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Wn,this.clientEncoder=new zs,this.leftClockEncoder=new Wn,this.rightClockEncoder=new Wn,this.infoEncoder=new bi(ys),this.stringEncoder=new Ec,this.parentInfoEncoder=new bi(ys),this.typeRefEncoder=new zs,this.lenEncoder=new zs}toUint8Array(){const e=De();return ie(e,0),je(e,this.keyClockEncoder.toUint8Array()),je(e,this.clientEncoder.toUint8Array()),je(e,this.leftClockEncoder.toUint8Array()),je(e,this.rightClockEncoder.toUint8Array()),je(e,Se(this.infoEncoder)),je(e,this.stringEncoder.toUint8Array()),je(e,Se(this.parentInfoEncoder)),je(e,this.typeRefEncoder.toUint8Array()),je(e,this.lenEncoder.toUint8Array()),xn(e,Se(this.restEncoder)),Se(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Gt(this.restEncoder,e)}writeBuf(e){je(this.restEncoder,e)}writeJSON(e){Gt(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 ru=(t,e,s,r)=>{r=Lt(r,e[0].id.clock);const i=nt(e,r);ie(t.restEncoder,e.length-i),t.writeClient(s),ie(t.restEncoder,r);const o=e[i];o.write(t,r-o.id.clock);for(let c=i+1;c<e.length;c++)e[c].write(t,0)},Kr=(t,e,s)=>{const r=new Map;s.forEach((i,o)=>{Me(e,o)>i&&r.set(o,i)}),Rn(e).forEach((i,o)=>{s.has(o)||r.set(o,0)}),ie(t.restEncoder,r.size),ct(r.entries()).sort((i,o)=>o[0]-i[0]).forEach(([i,o])=>{ru(t,e.clients.get(i),i,o)})},iu=(t,e)=>{const s=Fe(),r=de(t.restDecoder);for(let i=0;i<r;i++){const o=de(t.restDecoder),c=new Array(o),d=t.readClient();let l=de(t.restDecoder);s.set(d,{i:0,refs:c});for(let p=0;p<o;p++){const g=t.readInfo();switch(bn&g){case 0:{const u=t.readLen();c[p]=new Ye(me(d,l),u),l+=u;break}case 10:{const u=de(t.restDecoder);c[p]=new Ke(me(d,l),u),l+=u;break}default:{const u=(g&(at|He))===0,f=new Te(me(d,l),null,(g&He)===He?t.readLeftID():null,null,(g&at)===at?t.readRightID():null,u?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,u&&(g&ms)===ms?t.readString():null,Ua(t,g));c[p]=f,l+=f.length}}}}return s},ou=(t,e,s)=>{const r=[];let i=ct(s.keys()).sort((x,y)=>x-y);if(i.length===0)return null;const o=()=>{if(i.length===0)return null;let x=s.get(i[i.length-1]);for(;x.refs.length===x.i;)if(i.pop(),i.length>0)x=s.get(i[i.length-1]);else return null;return x};let c=o();if(c===null)return null;const d=new xa,l=new Map,p=(x,y)=>{const E=l.get(x);(E==null||E>y)&&l.set(x,y)};let g=c.refs[c.i++];const u=new Map,f=()=>{for(const x of r){const y=x.id.client,E=s.get(y);E?(E.i--,d.clients.set(y,E.refs.slice(E.i)),s.delete(y),E.i=0,E.refs=[]):d.clients.set(y,[x]),i=i.filter(L=>L!==y)}r.length=0};for(;;){if(g.constructor!==Ke){const y=Ve(u,g.id.client,()=>Me(e,g.id.client))-g.id.clock;if(y<0)r.push(g),p(g.id.client,g.id.clock-1),f();else{const E=g.getMissing(t,e);if(E!==null){r.push(g);const L=s.get(E)||{refs:[],i:0};if(L.refs.length===L.i)p(E,Me(e,E)),f();else{g=L.refs[L.i++];continue}}else(y===0||y<g.length)&&(g.integrate(t,y),u.set(g.id.client,g.id.clock+g.length))}}if(r.length>0)g=r.pop();else if(c!==null&&c.i<c.refs.length)g=c.refs[c.i++];else{if(c=o(),c===null)break;g=c.refs[c.i++]}}if(d.clients.size>0){const x=new Ct;return Kr(x,d,new Map),ie(x.restEncoder,0),{missing:l,update:x.toUint8Array()}}return null},au=(t,e)=>Kr(t,e.doc.store,e.beforeState),lu=(t,e,s,r=new Xt(t))=>we(e,i=>{i.local=!1;let o=!1;const c=i.doc,d=c.store,l=iu(r,c),p=ou(i,d,l),g=d.pendingStructs;if(g){for(const[f,x]of g.missing)if(x<Me(d,f)){o=!0;break}if(p){for(const[f,x]of p.missing){const y=g.missing.get(f);(y==null||y>x)&&g.missing.set(f,x)}g.update=Zs([g.update,p.update])}}else d.pendingStructs=p;const u=Ni(r,i,d);if(d.pendingDs){const f=new Xt(it(d.pendingDs));de(f.restDecoder);const x=Ni(f,i,d);u&&x?d.pendingDs=Zs([u,x]):d.pendingDs=u||x}else d.pendingDs=u;if(o){const f=d.pendingStructs.update;d.pendingStructs=null,pa(i.doc,f)}},s,!1),pa=(t,e,s,r=Xt)=>{const i=it(e);lu(i,t,s,new r(i))},ma=(t,e,s)=>pa(t,e,s,ua),cu=(t,e,s=new Map)=>{Kr(t,e.store,s),ns(t,su(e.store))},du=(t,e=new Uint8Array([0]),s=new Ct)=>{const r=ga(e);cu(s,t,r);const i=[s.toUint8Array()];if(t.store.pendingDs&&i.push(t.store.pendingDs),t.store.pendingStructs&&i.push(ju(t.store.pendingStructs.update,e)),i.length>1){if(s.constructor===Ts)return ku(i.map((o,c)=>c===0?o:Nu(o)));if(s.constructor===Ct)return Zs(i)}return i[0]},Jr=(t,e)=>du(t,e,new Ts),uu=t=>{const e=new Map,s=de(t.restDecoder);for(let r=0;r<s;r++){const i=de(t.restDecoder),o=de(t.restDecoder);e.set(i,o)}return e},ga=t=>uu(new da(it(t))),ya=(t,e)=>(ie(t.restEncoder,e.size),ct(e.entries()).sort((s,r)=>r[0]-s[0]).forEach(([s,r])=>{ie(t.restEncoder,s),ie(t.restEncoder,r)}),t),hu=(t,e)=>ya(t,Rn(e.store)),fu=(t,e=new fa)=>(t instanceof Map?ya(e,t):hu(e,t),e.toUint8Array()),pu=t=>fu(t,new ha);class mu{constructor(){this.l=[]}}const Ci=()=>new mu,Ti=(t,e)=>t.l.push(e),Ri=(t,e)=>{const s=t.l,r=s.length;t.l=s.filter(i=>e!==i),r===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},ba=(t,e,s)=>Fr(t.l,[e,s]);class $t{constructor(e,s){this.client=e,this.clock=s}}const Ls=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,me=(t,e)=>new $t(t,e),gu=t=>{for(const[e,s]of t.doc.share.entries())if(s===t)return e;throw Qe()},Bt=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!la(e.ds,t.id),dr=(t,e)=>{const s=Ve(t.meta,dr,bt),r=t.doc.store;s.has(e)||(e.sv.forEach((i,o)=>{i<Me(r,o)&&xt(t,me(o,i))}),aa(t,e.ds,i=>{}),s.add(e))};class xa{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Rn=t=>{const e=new Map;return t.clients.forEach((s,r)=>{const i=s[s.length-1];e.set(r,i.id.clock+i.length)}),e},Me=(t,e)=>{const s=t.clients.get(e);if(s===void 0)return 0;const r=s[s.length-1];return r.id.clock+r.length},wa=(t,e)=>{let s=t.clients.get(e.id.client);if(s===void 0)s=[],t.clients.set(e.id.client,s);else{const r=s[s.length-1];if(r.id.clock+r.length!==e.id.clock)throw Qe()}s.push(e)},nt=(t,e)=>{let s=0,r=t.length-1,i=t[r],o=i.id.clock;if(o===e)return r;let c=Xe(e/(o+i.length-1)*r);for(;s<=r;){if(i=t[c],o=i.id.clock,o<=e){if(e<o+i.length)return c;s=c+1}else r=c-1;c=Xe((s+r)/2)}throw Qe()},yu=(t,e)=>{const s=t.clients.get(e.client);return s[nt(s,e.clock)]},Hn=yu,ur=(t,e,s)=>{const r=nt(e,s),i=e[r];return i.id.clock<s&&i instanceof Te?(e.splice(r+1,0,on(t,i,s-i.id.clock)),r+1):r},xt=(t,e)=>{const s=t.doc.store.clients.get(e.client);return s[ur(t,s,e.clock)]},Ai=(t,e,s)=>{const r=e.clients.get(s.client),i=nt(r,s.clock),o=r[i];return s.clock!==o.id.clock+o.length-1&&o.constructor!==Ye&&r.splice(i+1,0,on(t,o,s.clock-o.id.clock+1)),o},bu=(t,e,s)=>{const r=t.clients.get(e.id.client);r[nt(r,e.id.clock)]=s},va=(t,e,s,r,i)=>{if(r===0)return;const o=s+r;let c=ur(t,e,s),d;do d=e[c++],o<d.id.clock+d.length&&ur(t,e,o),i(d);while(c<e.length&&e[c].id.clock<o)};class xu{constructor(e,s,r){this.doc=e,this.deleteSet=new Cs,this.beforeState=Rn(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=s,this.meta=new Map,this.local=r,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Li=(t,e)=>e.deleteSet.clients.size===0&&!rc(e.afterState,(s,r)=>e.beforeState.get(r)!==s)?!1:(qr(e.deleteSet),au(t,e),ns(t,e.deleteSet),!0),Ii=(t,e,s)=>{const r=e._item;(r===null||r.id.clock<(t.beforeState.get(r.id.client)||0)&&!r.deleted)&&Ve(t.changed,e,bt).add(s)},Vs=(t,e)=>{let s=t[e],r=t[e-1],i=e;for(;i>0;s=r,r=t[--i-1]){if(r.deleted===s.deleted&&r.constructor===s.constructor&&r.mergeWith(s)){s instanceof Te&&s.parentSub!==null&&s.parent._map.get(s.parentSub)===s&&s.parent._map.set(s.parentSub,r);continue}break}const o=e-i;return o&&t.splice(e+1-o,o),o},wu=(t,e,s)=>{for(const[r,i]of t.clients.entries()){const o=e.clients.get(r);for(let c=i.length-1;c>=0;c--){const d=i[c],l=d.clock+d.len;for(let p=nt(o,d.clock),g=o[p];p<o.length&&g.id.clock<l;g=o[++p]){const u=o[p];if(d.clock+d.len<=u.id.clock)break;u instanceof Te&&u.deleted&&!u.keep&&s(u)&&u.gc(e,!1)}}}},vu=(t,e)=>{t.clients.forEach((s,r)=>{const i=e.clients.get(r);for(let o=s.length-1;o>=0;o--){const c=s[o],d=Ir(i.length-1,1+nt(i,c.clock+c.len-1));for(let l=d,p=i[l];l>0&&p.id.clock>=c.clock;p=i[l])l-=1+Vs(i,l)}})},_a=(t,e)=>{if(e<t.length){const s=t[e],r=s.doc,i=r.store,o=s.deleteSet,c=s._mergeStructs;try{qr(o),s.afterState=Rn(s.doc.store),r.emit("beforeObserverCalls",[s,r]);const d=[];s.changed.forEach((l,p)=>d.push(()=>{(p._item===null||!p._item.deleted)&&p._callObserver(s,l)})),d.push(()=>{s.changedParentTypes.forEach((l,p)=>{p._dEH.l.length>0&&(p._item===null||!p._item.deleted)&&(l=l.filter(g=>g.target._item===null||!g.target._item.deleted),l.forEach(g=>{g.currentTarget=p,g._path=null}),l.sort((g,u)=>g.path.length-u.path.length),d.push(()=>{ba(p._dEH,l,s)}))}),d.push(()=>r.emit("afterTransaction",[s,r])),d.push(()=>{s._needFormattingCleanup&&Fu(s)})}),Fr(d,[])}finally{r.gc&&wu(o,i,r.gcFilter),vu(o,i),s.afterState.forEach((g,u)=>{const f=s.beforeState.get(u)||0;if(f!==g){const x=i.clients.get(u),y=Lt(nt(x,f),1);for(let E=x.length-1;E>=y;)E-=1+Vs(x,E)}});for(let g=c.length-1;g>=0;g--){const{client:u,clock:f}=c[g].id,x=i.clients.get(u),y=nt(x,f);y+1<x.length&&Vs(x,y+1)>1||y>0&&Vs(x,y)}if(!s.local&&s.afterState.get(r.clientID)!==s.beforeState.get(r.clientID)&&(ra(Nn,Je,"[yjs] ",Nt,ta,"Changed the client-id because another client seems to be using it."),r.clientID=ca()),r.emit("afterTransactionCleanup",[s,r]),r._observers.has("update")){const g=new Ts;Li(g,s)&&r.emit("update",[g.toUint8Array(),s.origin,r,s])}if(r._observers.has("updateV2")){const g=new Ct;Li(g,s)&&r.emit("updateV2",[g.toUint8Array(),s.origin,r,s])}const{subdocsAdded:d,subdocsLoaded:l,subdocsRemoved:p}=s;(d.size>0||p.size>0||l.size>0)&&(d.forEach(g=>{g.clientID=r.clientID,g.collectionid==null&&(g.collectionid=r.collectionid),r.subdocs.add(g)}),p.forEach(g=>r.subdocs.delete(g)),r.emit("subdocs",[{loaded:l,added:d,removed:p},r,s]),p.forEach(g=>g.destroy())),t.length<=e+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,t])):_a(t,e+1)}}},we=(t,e,s=null,r=!0)=>{const i=t._transactionCleanups;let o=!1,c=null;t._transaction===null&&(o=!0,t._transaction=new xu(t,s,r),i.push(t._transaction),i.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{c=e(t._transaction)}finally{if(o){const d=t._transaction===i[0];t._transaction=null,d&&_a(i,0)}}return c};function*_u(t){const e=de(t.restDecoder);for(let s=0;s<e;s++){const r=de(t.restDecoder),i=t.readClient();let o=de(t.restDecoder);for(let c=0;c<r;c++){const d=t.readInfo();if(d===10){const l=de(t.restDecoder);yield new Ke(me(i,o),l),o+=l}else if((bn&d)!==0){const l=(d&(at|He))===0,p=new Te(me(i,o),null,(d&He)===He?t.readLeftID():null,null,(d&at)===at?t.readRightID():null,l?t.readParentInfo()?t.readString():t.readLeftID():null,l&&(d&ms)===ms?t.readString():null,Ua(t,d));yield p,o+=p.length}else{const l=t.readLen();yield new Ye(me(i,o),l),o+=l}}}}class Xr{constructor(e,s){this.gen=_u(e),this.curr=null,this.done=!1,this.filterSkips=s,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Ke);return this.curr}}class Qr{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const ku=t=>Zs(t,ua,Ts),Su=(t,e)=>{if(t.constructor===Ye){const{client:s,clock:r}=t.id;return new Ye(me(s,r+e),t.length-e)}else if(t.constructor===Ke){const{client:s,clock:r}=t.id;return new Ke(me(s,r+e),t.length-e)}else{const s=t,{client:r,clock:i}=s.id;return new Te(me(r,i+e),null,me(r,i+e-1),null,s.rightOrigin,s.parent,s.parentSub,s.content.splice(e))}},Zs=(t,e=Xt,s=Ct)=>{if(t.length===1)return t[0];const r=t.map(g=>new e(it(g)));let i=r.map(g=>new Xr(g,!0)),o=null;const c=new s,d=new Qr(c);for(;i=i.filter(f=>f.curr!==null),i.sort((f,x)=>{if(f.curr.id.client===x.curr.id.client){const y=f.curr.id.clock-x.curr.id.clock;return y===0?f.curr.constructor===x.curr.constructor?0:f.curr.constructor===Ke?1:-1:y}else return x.curr.id.client-f.curr.id.client}),i.length!==0;){const g=i[0],u=g.curr.id.client;if(o!==null){let f=g.curr,x=!1;for(;f!==null&&f.id.clock+f.length<=o.struct.id.clock+o.struct.length&&f.id.client>=o.struct.id.client;)f=g.next(),x=!0;if(f===null||f.id.client!==u||x&&f.id.clock>o.struct.id.clock+o.struct.length)continue;if(u!==o.struct.id.client)mt(d,o.struct,o.offset),o={struct:f,offset:0},g.next();else if(o.struct.id.clock+o.struct.length<f.id.clock)if(o.struct.constructor===Ke)o.struct.length=f.id.clock+f.length-o.struct.id.clock;else{mt(d,o.struct,o.offset);const y=f.id.clock-o.struct.id.clock-o.struct.length;o={struct:new Ke(me(u,o.struct.id.clock+o.struct.length),y),offset:0}}else{const y=o.struct.id.clock+o.struct.length-f.id.clock;y>0&&(o.struct.constructor===Ke?o.struct.length-=y:f=Su(f,y)),o.struct.mergeWith(f)||(mt(d,o.struct,o.offset),o={struct:f,offset:0},g.next())}}else o={struct:g.curr,offset:0},g.next();for(let f=g.curr;f!==null&&f.id.client===u&&f.id.clock===o.struct.id.clock+o.struct.length&&f.constructor!==Ke;f=g.next())mt(d,o.struct,o.offset),o={struct:f,offset:0}}o!==null&&(mt(d,o.struct,o.offset),o=null),Zr(d);const l=r.map(g=>Yr(g)),p=eu(l);return ns(c,p),c.toUint8Array()},ju=(t,e,s=Xt,r=Ct)=>{const i=ga(e),o=new r,c=new Qr(o),d=new s(it(t)),l=new Xr(d,!1);for(;l.curr;){const g=l.curr,u=g.id.client,f=i.get(u)||0;if(l.curr.constructor===Ke){l.next();continue}if(g.id.clock+g.length>f)for(mt(c,g,Lt(f-g.id.clock,0)),l.next();l.curr&&l.curr.id.client===u;)mt(c,l.curr,0),l.next();else for(;l.curr&&l.curr.id.client===u&&l.curr.id.clock+l.curr.length<=f;)l.next()}Zr(c);const p=Yr(d);return ns(o,p),o.toUint8Array()},ka=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:Se(t.encoder.restEncoder)}),t.encoder.restEncoder=De(),t.written=0)},mt=(t,e,s)=>{t.written>0&&t.currClient!==e.id.client&&ka(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),ie(t.encoder.restEncoder,e.id.clock+s)),e.write(t.encoder,s),t.written++},Zr=t=>{ka(t);const e=t.encoder.restEncoder;ie(e,t.clientStructs.length);for(let s=0;s<t.clientStructs.length;s++){const r=t.clientStructs[s];ie(e,r.written),xn(e,r.restEncoder)}},Eu=(t,e,s,r)=>{const i=new s(it(t)),o=new Xr(i,!1),c=new r,d=new Qr(c);for(let p=o.curr;p!==null;p=o.next())mt(d,e(p),0);Zr(d);const l=Yr(i);return ns(c,l),c.toUint8Array()},Nu=t=>Eu(t,Xc,Xt,Ts),Di="You must not compute changes after the event-handler fired.";class An{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=Cu(this.currentTarget,this.target))}deletes(e){return la(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ge(Di);const e=new Map,s=this.target;this.transaction.changed.get(s).forEach(i=>{if(i!==null){const o=s._map.get(i);let c,d;if(this.adds(o)){let l=o.left;for(;l!==null&&this.adds(l);)l=l.left;if(this.deletes(o))if(l!==null&&this.deletes(l))c="delete",d=Mn(l.content.getContent());else return;else l!==null&&this.deletes(l)?(c="update",d=Mn(l.content.getContent())):(c="add",d=void 0)}else if(this.deletes(o))c="delete",d=Mn(o.content.getContent());else return;e.set(i,{action:c,oldValue:d})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ge(Di);const s=this.target,r=bt(),i=bt(),o=[];if(e={added:r,deleted:i,delta:o,keys:this.keys},this.transaction.changed.get(s).has(null)){let d=null;const l=()=>{d&&o.push(d)};for(let p=s._start;p!==null;p=p.right)p.deleted?this.deletes(p)&&!this.adds(p)&&((d===null||d.delete===void 0)&&(l(),d={delete:0}),d.delete+=p.length,i.add(p)):this.adds(p)?((d===null||d.insert===void 0)&&(l(),d={insert:[]}),d.insert=d.insert.concat(p.content.getContent()),r.add(p)):((d===null||d.retain===void 0)&&(l(),d={retain:0}),d.retain+=p.length);d!==null&&d.retain===void 0&&l()}this._changes=e}return e}}const Cu=(t,e)=>{const s=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)s.unshift(e._item.parentSub);else{let r=0,i=e._item.parent._start;for(;i!==e._item&&i!==null;)!i.deleted&&i.countable&&(r+=i.length),i=i.right;s.unshift(r)}e=e._item.parent}return s},Be=()=>{Jd("Invalid access: Add Yjs type to a document before reading data.")},Sa=80;let ei=0;class Tu{constructor(e,s){e.marker=!0,this.p=e,this.index=s,this.timestamp=ei++}}const Ru=t=>{t.timestamp=ei++},ja=(t,e,s)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=s,t.timestamp=ei++},Au=(t,e,s)=>{if(t.length>=Sa){const r=t.reduce((i,o)=>i.timestamp<o.timestamp?i:o);return ja(r,e,s),r}else{const r=new Tu(e,s);return t.push(r),r}},Ln=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const s=t._searchMarker.length===0?null:t._searchMarker.reduce((o,c)=>$s(e-o.index)<$s(e-c.index)?o:c);let r=t._start,i=0;for(s!==null&&(r=s.p,i=s.index,Ru(s));r.right!==null&&i<e;){if(!r.deleted&&r.countable){if(e<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>e;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return s!==null&&$s(s.index-i)<r.parent.length/Sa?(ja(s,r,i),s):Au(t._searchMarker,r,i)},vs=(t,e,s)=>{for(let r=t.length-1;r>=0;r--){const i=t[r];if(s>0){let o=i.p;for(o.marker=!1;o&&(o.deleted||!o.countable);)o=o.left,o&&!o.deleted&&o.countable&&(i.index-=o.length);if(o===null||o.marker===!0){t.splice(r,1);continue}i.p=o,o.marker=!0}(e<i.index||s>0&&e===i.index)&&(i.index=Lt(e,i.index+s))}},In=(t,e,s)=>{const r=t,i=e.changedParentTypes;for(;Ve(i,t,()=>[]).push(s),t._item!==null;)t=t._item.parent;ba(r._eH,s,e)};class We{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Ci(),this._dEH=Ci(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,s){this.doc=e,this._item=s}_copy(){throw Ze()}clone(){throw Ze()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,s){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Ti(this._eH,e)}observeDeep(e){Ti(this._dEH,e)}unobserve(e){Ri(this._eH,e)}unobserveDeep(e){Ri(this._dEH,e)}toJSON(){}}const Ea=(t,e,s)=>{t.doc??Be(),e<0&&(e=t._length+e),s<0&&(s=t._length+s);let r=s-e;const i=[];let o=t._start;for(;o!==null&&r>0;){if(o.countable&&!o.deleted){const c=o.content.getContent();if(c.length<=e)e-=c.length;else{for(let d=e;d<c.length&&r>0;d++)i.push(c[d]),r--;e=0}}o=o.right}return i},Na=t=>{t.doc??Be();const e=[];let s=t._start;for(;s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i<r.length;i++)e.push(r[i])}s=s.right}return e},_s=(t,e)=>{let s=0,r=t._start;for(t.doc??Be();r!==null;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let o=0;o<i.length;o++)e(i[o],s++,t)}r=r.right}},Ca=(t,e)=>{const s=[];return _s(t,(r,i)=>{s.push(e(r,i,t))}),s},Lu=t=>{let e=t._start,s=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(s===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};s=e.content.getContent(),r=0,e=e.right}const i=s[r++];return s.length<=r&&(s=null),{done:!1,value:i}}}},Ta=(t,e)=>{t.doc??Be();const s=Ln(t,e);let r=t._start;for(s!==null&&(r=s.p,e-=s.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(e<r.length)return r.content.getContent()[e];e-=r.length}},en=(t,e,s,r)=>{let i=s;const o=t.doc,c=o.clientID,d=o.store,l=s===null?e._start:s.right;let p=[];const g=()=>{p.length>0&&(i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new At(p)),i.integrate(t,0),p=[])};r.forEach(u=>{if(u===null)p.push(u);else switch(u.constructor){case Number:case Object:case Boolean:case Array:case String:p.push(u);break;default:switch(g(),u.constructor){case Uint8Array:case ArrayBuffer:i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new Rs(new Uint8Array(u))),i.integrate(t,0);break;case rs:i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new As(u)),i.integrate(t,0);break;default:if(u instanceof We)i=new Te(me(c,Me(d,c)),i,i&&i.lastId,l,l&&l.id,e,null,new ft(u)),i.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),g()},Ra=()=>Ge("Length exceeded!"),Aa=(t,e,s,r)=>{if(s>e._length)throw Ra();if(s===0)return e._searchMarker&&vs(e._searchMarker,s,r.length),en(t,e,null,r);const i=s,o=Ln(e,s);let c=e._start;for(o!==null&&(c=o.p,s-=o.index,s===0&&(c=c.prev,s+=c&&c.countable&&!c.deleted?c.length:0));c!==null;c=c.right)if(!c.deleted&&c.countable){if(s<=c.length){s<c.length&&xt(t,me(c.id.client,c.id.clock+s));break}s-=c.length}return e._searchMarker&&vs(e._searchMarker,i,r.length),en(t,e,c,r)},Iu=(t,e,s)=>{let i=(e._searchMarker||[]).reduce((o,c)=>c.index>o.index?c:o,{index:0,p:e._start}).p;if(i)for(;i.right;)i=i.right;return en(t,e,i,s)},La=(t,e,s,r)=>{if(r===0)return;const i=s,o=r,c=Ln(e,s);let d=e._start;for(c!==null&&(d=c.p,s-=c.index);d!==null&&s>0;d=d.right)!d.deleted&&d.countable&&(s<d.length&&xt(t,me(d.id.client,d.id.clock+s)),s-=d.length);for(;r>0&&d!==null;)d.deleted||(r<d.length&&xt(t,me(d.id.client,d.id.clock+r)),d.delete(t),r-=d.length),d=d.right;if(r>0)throw Ra();e._searchMarker&&vs(e._searchMarker,i,-o+r)},tn=(t,e,s)=>{const r=e._map.get(s);r!==void 0&&r.delete(t)},ti=(t,e,s,r)=>{const i=e._map.get(s)||null,o=t.doc,c=o.clientID;let d;if(r==null)d=new At([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:d=new At([r]);break;case Uint8Array:d=new Rs(r);break;case rs:d=new As(r);break;default:if(r instanceof We)d=new ft(r);else throw new Error("Unexpected content type")}new Te(me(c,Me(o.store,c)),i,i&&i.lastId,null,null,e,s,d).integrate(t,0)},si=(t,e)=>{t.doc??Be();const s=t._map.get(e);return s!==void 0&&!s.deleted?s.content.getContent()[s.length-1]:void 0},Ia=t=>{const e={};return t.doc??Be(),t._map.forEach((s,r)=>{s.deleted||(e[r]=s.content.getContent()[s.length-1])}),e},Da=(t,e)=>{t.doc??Be();const s=t._map.get(e);return s!==void 0&&!s.deleted},Du=(t,e)=>{const s={};return t._map.forEach((r,i)=>{let o=r;for(;o!==null&&(!e.sv.has(o.id.client)||o.id.clock>=(e.sv.get(o.id.client)||0));)o=o.left;o!==null&&Bt(o,e)&&(s[i]=o.content.getContent()[o.length-1])}),s},Is=t=>(t.doc??Be(),Qd(t._map.entries(),e=>!e[1].deleted));class Mu extends An{}class zt extends We{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const s=new zt;return s.push(e),s}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new zt}clone(){const e=new zt;return e.insert(0,this.toArray().map(s=>s instanceof We?s.clone():s)),e}get length(){return this.doc??Be(),this._length}_callObserver(e,s){super._callObserver(e,s),In(this,e,new Mu(this,e))}insert(e,s){this.doc!==null?we(this.doc,r=>{Aa(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}push(e){this.doc!==null?we(this.doc,s=>{Iu(s,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,s=1){this.doc!==null?we(this.doc,r=>{La(r,this,e,s)}):this._prelimContent.splice(e,s)}get(e){return Ta(this,e)}toArray(){return Na(this)}slice(e=0,s=this.length){return Ea(this,e,s)}toJSON(){return this.map(e=>e instanceof We?e.toJSON():e)}map(e){return Ca(this,e)}forEach(e){_s(this,e)}[Symbol.iterator](){return Lu(this)}_write(e){e.writeTypeRef(oh)}}const Ou=t=>new zt;class Pu extends An{constructor(e,s,r){super(e,s),this.keysChanged=r}}class Tt extends We{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,s){super._integrate(e,s),this._prelimContent.forEach((r,i)=>{this.set(i,r)}),this._prelimContent=null}_copy(){return new Tt}clone(){const e=new Tt;return this.forEach((s,r)=>{e.set(r,s instanceof We?s.clone():s)}),e}_callObserver(e,s){In(this,e,new Pu(this,e,s))}toJSON(){this.doc??Be();const e={};return this._map.forEach((s,r)=>{if(!s.deleted){const i=s.content.getContent()[s.length-1];e[r]=i instanceof We?i.toJSON():i}}),e}get size(){return[...Is(this)].length}keys(){return zn(Is(this),e=>e[0])}values(){return zn(Is(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return zn(Is(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Be(),this._map.forEach((s,r)=>{s.deleted||e(s.content.getContent()[s.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?we(this.doc,s=>{tn(s,this,e)}):this._prelimContent.delete(e)}set(e,s){return this.doc!==null?we(this.doc,r=>{ti(r,this,e,s)}):this._prelimContent.set(e,s),s}get(e){return si(this,e)}has(e){return Da(this,e)}clear(){this.doc!==null?we(this.doc,e=>{this.forEach(function(s,r,i){tn(e,i,r)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(ah)}}const Wu=t=>new Tt,gt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&Yc(t,e);class hr{constructor(e,s,r,i){this.left=e,this.right=s,this.index=r,this.currentAttributes=i}forward(){switch(this.right===null&&Qe(),this.right.content.constructor){case Re:this.right.deleted||is(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 Mi=(t,e,s)=>{for(;e.right!==null&&s>0;){switch(e.right.content.constructor){case Re:e.right.deleted||is(e.currentAttributes,e.right.content);break;default:e.right.deleted||(s<e.right.length&&xt(t,me(e.right.id.client,e.right.id.clock+s)),e.index+=e.right.length,s-=e.right.length);break}e.left=e.right,e.right=e.right.right}return e},Ds=(t,e,s,r)=>{const i=new Map,o=r?Ln(e,s):null;if(o){const c=new hr(o.p.left,o.p,o.index,i);return Mi(t,c,s-o.index)}else{const c=new hr(null,e._start,0,i);return Mi(t,c,s)}},Ma=(t,e,s,r)=>{for(;s.right!==null&&(s.right.deleted===!0||s.right.content.constructor===Re&&gt(r.get(s.right.content.key),s.right.content.value));)s.right.deleted||r.delete(s.right.content.key),s.forward();const i=t.doc,o=i.clientID;r.forEach((c,d)=>{const l=s.left,p=s.right,g=new Te(me(o,Me(i.store,o)),l,l&&l.lastId,p,p&&p.id,e,null,new Re(d,c));g.integrate(t,0),s.right=g,s.forward()})},is=(t,e)=>{const{key:s,value:r}=e;r===null?t.delete(s):t.set(s,r)},Oa=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Re&&gt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Pa=(t,e,s,r)=>{const i=t.doc,o=i.clientID,c=new Map;for(const d in r){const l=r[d],p=s.currentAttributes.get(d)??null;if(!gt(p,l)){c.set(d,p);const{left:g,right:u}=s;s.right=new Te(me(o,Me(i.store,o)),g,g&&g.lastId,u,u&&u.id,e,null,new Re(d,l)),s.right.integrate(t,0),s.forward()}}return c},Vn=(t,e,s,r,i)=>{s.currentAttributes.forEach((f,x)=>{i[x]===void 0&&(i[x]=null)});const o=t.doc,c=o.clientID;Oa(s,i);const d=Pa(t,e,s,i),l=r.constructor===String?new rt(r):r instanceof We?new ft(r):new It(r);let{left:p,right:g,index:u}=s;e._searchMarker&&vs(e._searchMarker,s.index,l.getLength()),g=new Te(me(c,Me(o.store,c)),p,p&&p.lastId,g,g&&g.id,e,null,l),g.integrate(t,0),s.right=g,s.index=u,s.forward(),Ma(t,e,s,d)},Oi=(t,e,s,r,i)=>{const o=t.doc,c=o.clientID;Oa(s,i);const d=Pa(t,e,s,i);e:for(;s.right!==null&&(r>0||d.size>0&&(s.right.deleted||s.right.content.constructor===Re));){if(!s.right.deleted)switch(s.right.content.constructor){case Re:{const{key:l,value:p}=s.right.content,g=i[l];if(g!==void 0){if(gt(g,p))d.delete(l);else{if(r===0)break e;d.set(l,p)}s.right.delete(t)}else s.currentAttributes.set(l,p);break}default:r<s.right.length&&xt(t,me(s.right.id.client,s.right.id.clock+r)),r-=s.right.length;break}s.forward()}if(r>0){let l="";for(;r>0;r--)l+=`
35
+ `;s.right=new Te(me(c,Me(o.store,c)),s.left,s.left&&s.left.lastId,s.right,s.right&&s.right.id,e,null,new rt(l)),s.right.integrate(t,0),s.forward()}Ma(t,e,s,d)},Wa=(t,e,s,r,i)=>{let o=e;const c=Fe();for(;o&&(!o.countable||o.deleted);){if(!o.deleted&&o.content.constructor===Re){const p=o.content;c.set(p.key,p)}o=o.right}let d=0,l=!1;for(;e!==o;){if(s===e&&(l=!0),!e.deleted){const p=e.content;switch(p.constructor){case Re:{const{key:g,value:u}=p,f=r.get(g)??null;(c.get(g)!==p||f===u)&&(e.delete(t),d++,!l&&(i.get(g)??null)===u&&f!==u&&(f===null?i.delete(g):i.set(g,f))),!l&&!e.deleted&&is(i,p);break}}}e=e.right}return d},Bu=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const s=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Re){const r=e.content.key;s.has(r)?e.delete(t):s.add(r)}e=e.left}},Uu=t=>{let e=0;return we(t.doc,s=>{let r=t._start,i=t._start,o=Fe();const c=rr(o);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Re:is(c,i.content);break;default:e+=Wa(s,r,i,o,c),o=rr(c),r=i;break}i=i.right}}),e},Fu=t=>{const e=new Set,s=t.doc;for(const[r,i]of t.afterState.entries()){const o=t.beforeState.get(r)||0;i!==o&&va(t,s.store.clients.get(r),o,i,c=>{!c.deleted&&c.content.constructor===Re&&c.constructor!==Ye&&e.add(c.parent)})}we(s,r=>{aa(t,t.deleteSet,i=>{if(i instanceof Ye||!i.parent._hasFormatting||e.has(i.parent))return;const o=i.parent;i.content.constructor===Re?e.add(o):Bu(r,i)});for(const i of e)Uu(i)})},Pi=(t,e,s)=>{const r=s,i=rr(e.currentAttributes),o=e.right;for(;s>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case ft:case It:case rt:s<e.right.length&&xt(t,me(e.right.id.client,e.right.id.clock+s)),s-=e.right.length,e.right.delete(t);break}e.forward()}o&&Wa(t,o,e.right,i,e.currentAttributes);const c=(e.left||e.right).parent;return c._searchMarker&&vs(c._searchMarker,e.index,-r+s),e};class $u extends An{constructor(e,s,r){super(e,s),this.childListChanged=!1,this.keysChanged=new Set,r.forEach(i=>{i===null?this.childListChanged=!0:this.keysChanged.add(i)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,s=[];we(e,r=>{const i=new Map,o=new Map;let c=this.target._start,d=null;const l={};let p="",g=0,u=0;const f=()=>{if(d!==null){let x=null;switch(d){case"delete":u>0&&(x={delete:u}),u=0;break;case"insert":(typeof p=="object"||p.length>0)&&(x={insert:p},i.size>0&&(x.attributes={},i.forEach((y,E)=>{y!==null&&(x.attributes[E]=y)}))),p="";break;case"retain":g>0&&(x={retain:g},qc(l)||(x.attributes=Hc({},l))),g=0;break}x&&s.push(x),d=null}};for(;c!==null;){switch(c.content.constructor){case ft:case It:this.adds(c)?this.deletes(c)||(f(),d="insert",p=c.content.getContent()[0],f()):this.deletes(c)?(d!=="delete"&&(f(),d="delete"),u+=1):c.deleted||(d!=="retain"&&(f(),d="retain"),g+=1);break;case rt:this.adds(c)?this.deletes(c)||(d!=="insert"&&(f(),d="insert"),p+=c.content.str):this.deletes(c)?(d!=="delete"&&(f(),d="delete"),u+=c.length):c.deleted||(d!=="retain"&&(f(),d="retain"),g+=c.length);break;case Re:{const{key:x,value:y}=c.content;if(this.adds(c)){if(!this.deletes(c)){const E=i.get(x)??null;gt(E,y)?y!==null&&c.delete(r):(d==="retain"&&f(),gt(y,o.get(x)??null)?delete l[x]:l[x]=y)}}else if(this.deletes(c)){o.set(x,y);const E=i.get(x)??null;gt(E,y)||(d==="retain"&&f(),l[x]=E)}else if(!c.deleted){o.set(x,y);const E=l[x];E!==void 0&&(gt(E,y)?E!==null&&c.delete(r):(d==="retain"&&f(),y===null?delete l[x]:l[x]=y))}c.deleted||(d==="insert"&&f(),is(i,c.content));break}}c=c.right}for(f();s.length>0;){const x=s[s.length-1];if(x.retain!==void 0&&x.attributes===void 0)s.pop();else break}}),this._delta=s}return this._delta}}class Qt extends We{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Be(),this._length}_integrate(e,s){super._integrate(e,s);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new Qt}clone(){const e=new Qt;return e.applyDelta(this.toDelta()),e}_callObserver(e,s){super._callObserver(e,s);const r=new $u(this,e,s);In(this,e,r),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Be();let e="",s=this._start;for(;s!==null;)!s.deleted&&s.countable&&s.content.constructor===rt&&(e+=s.content.str),s=s.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:s=!0}={}){this.doc!==null?we(this.doc,r=>{const i=new hr(null,this._start,0,new Map);for(let o=0;o<e.length;o++){const c=e[o];if(c.insert!==void 0){const d=!s&&typeof c.insert=="string"&&o===e.length-1&&i.right===null&&c.insert.slice(-1)===`
36
+ `?c.insert.slice(0,-1):c.insert;(typeof d!="string"||d.length>0)&&Vn(r,this,i,d,c.attributes||{})}else c.retain!==void 0?Oi(r,this,i,c.retain,c.attributes||{}):c.delete!==void 0&&Pi(r,i,c.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,s,r){this.doc??Be();const i=[],o=new Map,c=this.doc;let d="",l=this._start;function p(){if(d.length>0){const u={};let f=!1;o.forEach((y,E)=>{f=!0,u[E]=y});const x={insert:d};f&&(x.attributes=u),i.push(x),d=""}}const g=()=>{for(;l!==null;){if(Bt(l,e)||s!==void 0&&Bt(l,s))switch(l.content.constructor){case rt:{const u=o.get("ychange");e!==void 0&&!Bt(l,e)?(u===void 0||u.user!==l.id.client||u.type!=="removed")&&(p(),o.set("ychange",r?r("removed",l.id):{type:"removed"})):s!==void 0&&!Bt(l,s)?(u===void 0||u.user!==l.id.client||u.type!=="added")&&(p(),o.set("ychange",r?r("added",l.id):{type:"added"})):u!==void 0&&(p(),o.delete("ychange")),d+=l.content.str;break}case ft:case It:{p();const u={insert:l.content.getContent()[0]};if(o.size>0){const f={};u.attributes=f,o.forEach((x,y)=>{f[y]=x})}i.push(u);break}case Re:Bt(l,e)&&(p(),is(o,l.content));break}l=l.right}p()};return e||s?we(c,u=>{e&&dr(u,e),s&&dr(u,s),g()},"cleanup"):g(),i}insert(e,s,r){if(s.length<=0)return;const i=this.doc;i!==null?we(i,o=>{const c=Ds(o,this,e,!r);r||(r={},c.currentAttributes.forEach((d,l)=>{r[l]=d})),Vn(o,this,c,s,r)}):this._pending.push(()=>this.insert(e,s,r))}insertEmbed(e,s,r){const i=this.doc;i!==null?we(i,o=>{const c=Ds(o,this,e,!r);Vn(o,this,c,s,r||{})}):this._pending.push(()=>this.insertEmbed(e,s,r||{}))}delete(e,s){if(s===0)return;const r=this.doc;r!==null?we(r,i=>{Pi(i,Ds(i,this,e,!0),s)}):this._pending.push(()=>this.delete(e,s))}format(e,s,r){if(s===0)return;const i=this.doc;i!==null?we(i,o=>{const c=Ds(o,this,e,!1);c.right!==null&&Oi(o,this,c,s,r)}):this._pending.push(()=>this.format(e,s,r))}removeAttribute(e){this.doc!==null?we(this.doc,s=>{tn(s,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,s){this.doc!==null?we(this.doc,r=>{ti(r,this,e,s)}):this._pending.push(()=>this.setAttribute(e,s))}getAttribute(e){return si(this,e)}getAttributes(){return Ia(this)}_write(e){e.writeTypeRef(lh)}}const zu=t=>new Qt;class Gn{constructor(e,s=()=>!0){this._filter=s,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Be()}[Symbol.iterator](){return this}next(){let e=this._currentNode,s=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(s)))do if(s=e.content.type,!e.deleted&&(s.constructor===Zt||s.constructor===Rt)&&s._start!==null)e=s._start;else for(;e!==null;){const r=e.next;if(r!==null){e=r;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Rt extends We{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,s){super._integrate(e,s),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Rt}clone(){const e=new Rt;return e.insert(0,this.toArray().map(s=>s instanceof We?s.clone():s)),e}get length(){return this.doc??Be(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Gn(this,e)}querySelector(e){e=e.toUpperCase();const r=new Gn(this,i=>i.nodeName&&i.nodeName.toUpperCase()===e).next();return r.done?null:r.value}querySelectorAll(e){return e=e.toUpperCase(),ct(new Gn(this,s=>s.nodeName&&s.nodeName.toUpperCase()===e))}_callObserver(e,s){In(this,e,new Gu(this,s,e))}toString(){return Ca(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,s={},r){const i=e.createDocumentFragment();return r!==void 0&&r._createAssociation(i,this),_s(this,o=>{i.insertBefore(o.toDOM(e,s,r),null)}),i}insert(e,s){this.doc!==null?we(this.doc,r=>{Aa(r,this,e,s)}):this._prelimContent.splice(e,0,...s)}insertAfter(e,s){if(this.doc!==null)we(this.doc,r=>{const i=e&&e instanceof We?e._item:e;en(r,this,i,s)});else{const r=this._prelimContent,i=e===null?0:r.findIndex(o=>o===e)+1;if(i===0&&e!==null)throw Ge("Reference item not found");r.splice(i,0,...s)}}delete(e,s=1){this.doc!==null?we(this.doc,r=>{La(r,this,e,s)}):this._prelimContent.splice(e,s)}toArray(){return Na(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Ta(this,e)}slice(e=0,s=this.length){return Ea(this,e,s)}forEach(e){_s(this,e)}_write(e){e.writeTypeRef(dh)}}const Hu=t=>new Rt;class Zt extends Rt{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,s){super._integrate(e,s),this._prelimAttrs.forEach((r,i)=>{this.setAttribute(i,r)}),this._prelimAttrs=null}_copy(){return new Zt(this.nodeName)}clone(){const e=new Zt(this.nodeName),s=this.getAttributes();return Gc(s,(r,i)=>{e.setAttribute(i,r)}),e.insert(0,this.toArray().map(r=>r instanceof We?r.clone():r)),e}toString(){const e=this.getAttributes(),s=[],r=[];for(const d in e)r.push(d);r.sort();const i=r.length;for(let d=0;d<i;d++){const l=r[d];s.push(l+'="'+e[l]+'"')}const o=this.nodeName.toLocaleLowerCase(),c=s.length>0?" "+s.join(" "):"";return`<${o}${c}>${super.toString()}</${o}>`}removeAttribute(e){this.doc!==null?we(this.doc,s=>{tn(s,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,s){this.doc!==null?we(this.doc,r=>{ti(r,this,e,s)}):this._prelimAttrs.set(e,s)}getAttribute(e){return si(this,e)}hasAttribute(e){return Da(this,e)}getAttributes(e){return e?Du(this,e):Ia(this)}toDOM(e=document,s={},r){const i=e.createElement(this.nodeName),o=this.getAttributes();for(const c in o){const d=o[c];typeof d=="string"&&i.setAttribute(c,d)}return _s(this,c=>{i.appendChild(c.toDOM(e,s,r))}),r!==void 0&&r._createAssociation(i,this),i}_write(e){e.writeTypeRef(ch),e.writeKey(this.nodeName)}}const Vu=t=>new Zt(t.readKey());class Gu extends An{constructor(e,s,r){super(e,r),this.childListChanged=!1,this.attributesChanged=new Set,s.forEach(i=>{i===null?this.childListChanged=!0:this.attributesChanged.add(i)})}}class sn extends Tt{constructor(e){super(),this.hookName=e}_copy(){return new sn(this.hookName)}clone(){const e=new sn(this.hookName);return this.forEach((s,r)=>{e.set(r,s)}),e}toDOM(e=document,s={},r){const i=s[this.hookName];let o;return i!==void 0?o=i.createDom(this):o=document.createElement(this.hookName),o.setAttribute("data-yjs-hook",this.hookName),r!==void 0&&r._createAssociation(o,this),o}_write(e){e.writeTypeRef(uh),e.writeKey(this.hookName)}}const qu=t=>new sn(t.readKey());class nn extends Qt{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 nn}clone(){const e=new nn;return e.applyDelta(this.toDelta()),e}toDOM(e=document,s,r){const i=e.createTextNode(this.toString());return r!==void 0&&r._createAssociation(i,this),i}toString(){return this.toDelta().map(e=>{const s=[];for(const i in e.attributes){const o=[];for(const c in e.attributes[i])o.push({key:c,value:e.attributes[i][c]});o.sort((c,d)=>c.key<d.key?-1:1),s.push({nodeName:i,attrs:o})}s.sort((i,o)=>i.nodeName<o.nodeName?-1:1);let r="";for(let i=0;i<s.length;i++){const o=s[i];r+=`<${o.nodeName}`;for(let c=0;c<o.attrs.length;c++){const d=o.attrs[c];r+=` ${d.key}="${d.value}"`}r+=">"}r+=e.insert;for(let i=s.length-1;i>=0;i--)r+=`</${s[i].nodeName}>`;return r}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(hh)}}const Yu=t=>new nn;class ni{constructor(e,s){this.id=e,this.length=s}get deleted(){throw Ze()}mergeWith(e){return!1}write(e,s,r){throw Ze()}integrate(e,s){throw Ze()}}const Ku=0;class Ye extends ni{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),wa(e.doc.store,this)}write(e,s){e.writeInfo(Ku),e.writeLen(this.length-s)}getMissing(e,s){return null}}class Rs{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Rs(this.content)}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeBuf(this.content)}getRef(){return 3}}const Ju=t=>new Rs(t.readBuf());class ks{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new ks(this.len)}splice(e){const s=new ks(this.len-e);return this.len=e,s}mergeWith(e){return this.len+=e.len,!0}integrate(e,s){Qs(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 Xu=t=>new ks(t.readLen()),Ba=(t,e)=>new rs({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class As{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 As(Ba(this.doc.guid,this.opts))}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){this.doc._item=s,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,s){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const Qu=t=>new As(Ba(t.readString(),t.readAny()));class It{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new It(this.embed)}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeJSON(this.embed)}getRef(){return 5}}const Zu=t=>new It(t.readJSON());class Re{constructor(e,s){this.key=e,this.value=s}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Re(this.key,this.value)}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){const r=s.parent;r._searchMarker=null,r._hasFormatting=!0}delete(e){}gc(e){}write(e,s){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const eh=t=>new Re(t.readKey(),t.readJSON());class rn{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new rn(this.arr)}splice(e){const s=new rn(this.arr.slice(e));return this.arr=this.arr.slice(0,e),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){const r=this.arr.length;e.writeLen(r-s);for(let i=s;i<r;i++){const o=this.arr[i];e.writeString(o===void 0?"undefined":JSON.stringify(o))}}getRef(){return 2}}const th=t=>{const e=t.readLen(),s=[];for(let r=0;r<e;r++){const i=t.readString();i==="undefined"?s.push(void 0):s.push(JSON.parse(i))}return new rn(s)},sh=xs("node_env")==="development";class At{constructor(e){this.arr=e,sh&&Ro(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new At(this.arr)}splice(e){const s=new At(this.arr.slice(e));return this.arr=this.arr.slice(0,e),s}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){const r=this.arr.length;e.writeLen(r-s);for(let i=s;i<r;i++){const o=this.arr[i];e.writeAny(o)}}getRef(){return 8}}const nh=t=>{const e=t.readLen(),s=[];for(let r=0;r<e;r++)s.push(t.readAny());return new At(s)};class rt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new rt(this.str)}splice(e){const s=new rt(this.str.slice(e));this.str=this.str.slice(0,e);const r=this.str.charCodeAt(e-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,e-1)+"�",s.str="�"+s.str.slice(1)),s}mergeWith(e){return this.str+=e.str,!0}integrate(e,s){}delete(e){}gc(e){}write(e,s){e.writeString(s===0?this.str:this.str.slice(s))}getRef(){return 4}}const rh=t=>new rt(t.readString()),ih=[Ou,Wu,zu,Vu,Hu,qu,Yu],oh=0,ah=1,lh=2,ch=3,dh=4,uh=5,hh=6;class ft{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new ft(this.type._copy())}splice(e){throw Ze()}mergeWith(e){return!1}integrate(e,s){this.type._integrate(e.doc,s)}delete(e){let s=this.type._start;for(;s!==null;)s.deleted?s.id.clock<(e.beforeState.get(s.id.client)||0)&&e._mergeStructs.push(s):s.delete(e),s=s.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(e.beforeState.get(r.id.client)||0)&&e._mergeStructs.push(r):r.delete(e)}),e.changed.delete(this.type)}gc(e){let s=this.type._start;for(;s!==null;)s.gc(e,!0),s=s.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(e,!0),r=r.left}),this.type._map=new Map}write(e,s){this.type._write(e)}getRef(){return 7}}const fh=t=>new ft(ih[t.readTypeRef()](t)),on=(t,e,s)=>{const{client:r,clock:i}=e.id,o=new Te(me(r,i+s),e,me(r,i+s-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(s));return e.deleted&&o.markDeleted(),e.keep&&(o.keep=!0),e.redone!==null&&(o.redone=me(e.redone.client,e.redone.clock+s)),e.right=o,o.right!==null&&(o.right.left=o),t._mergeStructs.push(o),o.parentSub!==null&&o.right===null&&o.parent._map.set(o.parentSub,o),e.length=s,o};class Te extends ni{constructor(e,s,r,i,o,c,d,l){super(e,l.getLength()),this.origin=r,this.left=s,this.right=i,this.rightOrigin=o,this.parent=c,this.parentSub=d,this.redone=null,this.content=l,this.info=this.content.isCountable()?pi:0}set marker(e){(this.info&Pn)>0!==e&&(this.info^=Pn)}get marker(){return(this.info&Pn)>0}get keep(){return(this.info&fi)>0}set keep(e){this.keep!==e&&(this.info^=fi)}get countable(){return(this.info&pi)>0}get deleted(){return(this.info&On)>0}set deleted(e){this.deleted!==e&&(this.info^=On)}markDeleted(){this.info|=On}getMissing(e,s){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Me(s,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Me(s,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===$t&&this.id.client!==this.parent.client&&this.parent.clock>=Me(s,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Ai(e,s,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=xt(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ye||this.right&&this.right.constructor===Ye)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===Te?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Te&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===$t){const r=Hn(s,this.parent);r.constructor===Ye?this.parent=null:this.parent=r.content.type}return null}integrate(e,s){if(s>0&&(this.id.clock+=s,this.left=Ai(e,e.doc.store,me(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(s),this.length-=s),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,i;if(r!==null)i=r.right;else if(this.parentSub!==null)for(i=this.parent._map.get(this.parentSub)||null;i!==null&&i.left!==null;)i=i.left;else i=this.parent._start;const o=new Set,c=new Set;for(;i!==null&&i!==this.right;){if(c.add(i),o.add(i),Ls(this.origin,i.origin)){if(i.id.client<this.id.client)r=i,o.clear();else if(Ls(this.rightOrigin,i.rightOrigin))break}else if(i.origin!==null&&c.has(Hn(e.doc.store,i.origin)))o.has(Hn(e.doc.store,i.origin))||(r=i,o.clear());else break;i=i.right}this.left=r}if(this.left!==null){const r=this.left.right;this.right=r,this.left.right=this}else{let r;if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start,this.parent._start=this;this.right=r}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),wa(e.doc.store,this),this.content.integrate(e,this),Ii(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Ye(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:me(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ls(e.origin,this.lastId)&&this.right===e&&Ls(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const s=this.parent._searchMarker;return s&&s.forEach(r=>{r.p===e&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const s=this.parent;this.countable&&this.parentSub===null&&(s._length-=this.length),this.markDeleted(),Qs(e.deleteSet,this.id.client,this.id.clock,this.length),Ii(e,s,this.parentSub),this.content.delete(e)}}gc(e,s){if(!this.deleted)throw Qe();this.content.gc(e),s?bu(e,this,new Ye(this.id,this.length)):this.content=new ks(this.length)}write(e,s){const r=s>0?me(this.id.client,this.id.clock+s-1):this.origin,i=this.rightOrigin,o=this.parentSub,c=this.content.getRef()&bn|(r===null?0:He)|(i===null?0:at)|(o===null?0:ms);if(e.writeInfo(c),r!==null&&e.writeLeftID(r),i!==null&&e.writeRightID(i),r===null&&i===null){const d=this.parent;if(d._item!==void 0){const l=d._item;if(l===null){const p=gu(d);e.writeParentInfo(!0),e.writeString(p)}else e.writeParentInfo(!1),e.writeLeftID(l.id)}else d.constructor===String?(e.writeParentInfo(!0),e.writeString(d)):d.constructor===$t?(e.writeParentInfo(!1),e.writeLeftID(d)):Qe();o!==null&&e.writeString(o)}this.content.write(e,s)}}const Ua=(t,e)=>ph[e&bn](t),ph=[()=>{Qe()},Xu,th,Ju,rh,Zu,eh,fh,nh,Qu,()=>{Qe()}],mh=10;class Ke extends ni{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,s){Qe()}write(e,s){e.writeInfo(mh),ie(e.restEncoder,this.length-s)}getMissing(e,s){return null}}const Fa=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},$a="__ $YJS$ __";Fa[$a]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Fa[$a]=!0;const Dt=t=>Yt((e,s)=>{t.onerror=r=>s(new Error(r.target.error)),t.onsuccess=r=>e(r.target.result)}),gh=(t,e)=>Yt((s,r)=>{const i=indexedDB.open(t);i.onupgradeneeded=o=>e(o.target.result),i.onerror=o=>r(Ge(o.target.error)),i.onsuccess=o=>{const c=o.target.result;c.onversionchange=()=>{c.close()},s(c)}}),yh=t=>Dt(indexedDB.deleteDatabase(t)),bh=(t,e)=>e.forEach(s=>t.createObjectStore.apply(t,s)),cs=(t,e,s="readwrite")=>{const r=t.transaction(e,s);return e.map(i=>Eh(r,i))},za=(t,e)=>Dt(t.count(e)),xh=(t,e)=>Dt(t.get(e)),Ha=(t,e)=>Dt(t.delete(e)),wh=(t,e,s)=>Dt(t.put(e,s)),fr=(t,e)=>Dt(t.add(e)),vh=(t,e,s)=>Dt(t.getAll(e,s)),_h=(t,e,s)=>{let r=null;return jh(t,e,i=>(r=i,!1),s).then(()=>r)},kh=(t,e=null)=>_h(t,e,"prev"),Sh=(t,e)=>Yt((s,r)=>{t.onerror=r,t.onsuccess=async i=>{const o=i.target.result;if(o===null||await e(o)===!1)return s();o.continue()}}),jh=(t,e,s,r="next")=>Sh(t.openKeyCursor(e,r),i=>s(i.key)),Eh=(t,e)=>t.objectStore(e),Nh=(t,e)=>IDBKeyRange.upperBound(t,e),Ch=(t,e)=>IDBKeyRange.lowerBound(t,e),qn="custom",Va="updates",Ga=500,qa=(t,e=()=>{},s=()=>{})=>{const[r]=cs(t.db,[Va]);return vh(r,Ch(t._dbref,!1)).then(i=>{t._destroyed||(e(r),we(t.doc,()=>{i.forEach(o=>ma(t.doc,o))},t,!1),s(r))}).then(()=>kh(r).then(i=>{t._dbref=i+1})).then(()=>za(r).then(i=>{t._dbsize=i})).then(()=>r)},Th=(t,e=!0)=>qa(t).then(s=>{(e||t._dbsize>=Ga)&&fr(s,Jr(t.doc)).then(()=>Ha(s,Nh(t._dbref,!0))).then(()=>za(s).then(r=>{t._dbsize=r}))});class Rh extends Lr{constructor(e,s){super(),this.doc=s,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=gh(e,r=>bh(r,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Yt(r=>this.on("synced",()=>r(this))),this._db.then(r=>{this.db=r,qa(this,c=>fr(c,Jr(s)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(r,i)=>{if(this.db&&i!==this){const[o]=cs(this.db,[Va]);fr(o,r),++this._dbsize>=Ga&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{Th(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},s.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),s.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{yh(this.name)})}get(e){return this._db.then(s=>{const[r]=cs(s,[qn],"readonly");return xh(r,e)})}set(e,s){return this._db.then(r=>{const[i]=cs(r,[qn]);return wh(i,s,e)})}del(e){return this._db.then(s=>{const[r]=cs(s,[qn]);return Ha(r,e)})}}const Ah=1200,Lh=2500,an=3e4,pr=t=>{if(t.shouldConnect&&t.ws===null){const e=new WebSocket(t.url),s=t.binaryType;let r=null;s&&(e.binaryType=s),t.ws=e,t.connecting=!0,t.connected=!1,e.onmessage=c=>{t.lastMessageReceived=dt();const d=c.data,l=typeof d=="string"?JSON.parse(d):d;l&&l.type==="pong"&&(clearTimeout(r),r=setTimeout(o,an/2)),t.emit("message",[l,t])};const i=c=>{t.ws!==null&&(t.ws=null,t.connecting=!1,t.connected?(t.connected=!1,t.emit("disconnect",[{type:"disconnect",error:c},t])):t.unsuccessfulReconnects++,setTimeout(pr,Ir(ac(t.unsuccessfulReconnects+1)*Ah,Lh),t)),clearTimeout(r)},o=()=>{t.ws===e&&t.send({type:"ping"})};e.onclose=()=>i(null),e.onerror=c=>i(c),e.onopen=()=>{t.lastMessageReceived=dt(),t.connecting=!1,t.connected=!0,t.unsuccessfulReconnects=0,t.emit("connect",[{type:"connect"},t]),r=setTimeout(o,an/2)}}};class Ih extends Lr{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&&an<dt()-this.lastMessageReceived&&this.ws.close()},an/2),pr(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&&pr(this)}}const Ya=new Map;class Dh{constructor(e){this.room=e,this.onmessage=null,this._onChange=s=>s.key===e&&this.onmessage!==null&&this.onmessage({data:Oo(s.newValue||"")}),Fc(this._onChange)}postMessage(e){Co.setItem(this.room,Mo(rd(e)))}close(){$c(this._onChange)}}const Mh=typeof BroadcastChannel>"u"?Dh:BroadcastChannel,ri=t=>Ve(Ya,t,()=>{const e=bt(),s=new Mh(t);return s.onmessage=r=>e.forEach(i=>i(r.data,"broadcastchannel")),{bc:s,subs:e}}),Oh=(t,e)=>(ri(t).subs.add(e),e),Ph=(t,e)=>{const s=ri(t),r=s.subs.delete(e);return r&&s.subs.size===0&&(s.bc.close(),Ya.delete(t)),r},Wh=(t,e,s=null)=>{const r=ri(t);r.bc.postMessage(e),r.subs.forEach(i=>i(e,s))},Bh=()=>{let t=!0;return(e,s)=>{if(t){t=!1;try{e()}finally{t=!0}}else s!==void 0&&s()}};function Ms(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 Yn={exports:{}},Wi;function Uh(){return Wi||(Wi=1,(function(t,e){(function(s){t.exports=s()})(function(){var s=Math.floor,r=Math.abs,i=Math.pow;return(function(){function o(c,d,l){function p(f,x){if(!d[f]){if(!c[f]){var y=typeof Ms=="function"&&Ms;if(!x&&y)return y(f,!0);if(g)return g(f,!0);var E=new Error("Cannot find module '"+f+"'");throw E.code="MODULE_NOT_FOUND",E}var L=d[f]={exports:{}};c[f][0].call(L.exports,function(v){var A=c[f][1][v];return p(A||v)},L,L.exports,o,c,d,l)}return d[f].exports}for(var g=typeof Ms=="function"&&Ms,u=0;u<l.length;u++)p(l[u]);return p}return o})()({1:[function(o,c,d){function l(k){var _=k.length;if(0<_%4)throw new Error("Invalid string. Length must be a multiple of 4");var T=k.indexOf("=");T===-1&&(T=_);var S=T===_?0:4-T%4;return[T,S]}function p(k,_,T){return 3*(_+T)/4-T}function g(k){var _,T,S=l(k),C=S[0],D=S[1],j=new L(p(k,C,D)),R=0,P=0<D?C-4:C;for(T=0;T<P;T+=4)_=E[k.charCodeAt(T)]<<18|E[k.charCodeAt(T+1)]<<12|E[k.charCodeAt(T+2)]<<6|E[k.charCodeAt(T+3)],j[R++]=255&_>>16,j[R++]=255&_>>8,j[R++]=255&_;return D===2&&(_=E[k.charCodeAt(T)]<<2|E[k.charCodeAt(T+1)]>>4,j[R++]=255&_),D===1&&(_=E[k.charCodeAt(T)]<<10|E[k.charCodeAt(T+1)]<<4|E[k.charCodeAt(T+2)]>>2,j[R++]=255&_>>8,j[R++]=255&_),j}function u(k){return y[63&k>>18]+y[63&k>>12]+y[63&k>>6]+y[63&k]}function f(k,_,T){for(var S,C=[],D=_;D<T;D+=3)S=(16711680&k[D]<<16)+(65280&k[D+1]<<8)+(255&k[D+2]),C.push(u(S));return C.join("")}function x(k){for(var _,T=k.length,S=T%3,C=[],D=16383,j=0,R=T-S;j<R;j+=D)C.push(f(k,j,j+D>R?R:j+D));return S===1?(_=k[T-1],C.push(y[_>>2]+y[63&_<<4]+"==")):S===2&&(_=(k[T-2]<<8)+k[T-1],C.push(y[_>>10]+y[63&_>>4]+y[63&_<<2]+"=")),C.join("")}d.byteLength=function(k){var _=l(k),T=_[0],S=_[1];return 3*(T+S)/4-S},d.toByteArray=g,d.fromByteArray=x;for(var y=[],E=[],L=typeof Uint8Array>"u"?Array:Uint8Array,v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",A=0,m=v.length;A<m;++A)y[A]=v[A],E[v.charCodeAt(A)]=A;E[45]=62,E[95]=63},{}],2:[function(){},{}],3:[function(o,c,d){(function(){(function(){var l=String.fromCharCode,p=Math.min;function g(a){if(2147483647<a)throw new RangeError('The value "'+a+'" is invalid for option "size"');var h=new Uint8Array(a);return h.__proto__=u.prototype,h}function u(a,h,b){if(typeof a=="number"){if(typeof h=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return E(a)}return f(a,h,b)}function f(a,h,b){if(typeof a=="string")return L(a,h);if(ArrayBuffer.isView(a))return v(a);if(a==null)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a);if(M(a,ArrayBuffer)||a&&M(a.buffer,ArrayBuffer))return A(a,h,b);if(typeof a=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var I=a.valueOf&&a.valueOf();if(I!=null&&I!==a)return u.from(I,h,b);var O=m(a);if(O)return O;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof a[Symbol.toPrimitive]=="function")return u.from(a[Symbol.toPrimitive]("string"),h,b);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof a)}function x(a){if(typeof a!="number")throw new TypeError('"size" argument must be of type number');if(0>a)throw new RangeError('The value "'+a+'" is invalid for option "size"')}function y(a,h,b){return x(a),0>=a||h===void 0?g(a):typeof b=="string"?g(a).fill(h,b):g(a).fill(h)}function E(a){return x(a),g(0>a?0:0|k(a))}function L(a,h){if((typeof h!="string"||h==="")&&(h="utf8"),!u.isEncoding(h))throw new TypeError("Unknown encoding: "+h);var b=0|_(a,h),I=g(b),O=I.write(a,h);return O!==b&&(I=I.slice(0,O)),I}function v(a){for(var h=0>a.length?0:0|k(a.length),b=g(h),I=0;I<h;I+=1)b[I]=255&a[I];return b}function A(a,h,b){if(0>h||a.byteLength<h)throw new RangeError('"offset" is outside of buffer bounds');if(a.byteLength<h+(b||0))throw new RangeError('"length" is outside of buffer bounds');var I;return I=h===void 0&&b===void 0?new Uint8Array(a):b===void 0?new Uint8Array(a,h):new Uint8Array(a,h,b),I.__proto__=u.prototype,I}function m(a){if(u.isBuffer(a)){var h=0|k(a.length),b=g(h);return b.length===0||a.copy(b,0,0,h),b}return a.length===void 0?a.type==="Buffer"&&Array.isArray(a.data)?v(a.data):void 0:typeof a.length!="number"||W(a.length)?g(0):v(a)}function k(a){if(a>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|a}function _(a,h){if(u.isBuffer(a))return a.length;if(ArrayBuffer.isView(a)||M(a,ArrayBuffer))return a.byteLength;if(typeof a!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof a);var b=a.length,I=2<arguments.length&&arguments[2]===!0;if(!I&&b===0)return 0;for(var O=!1;;)switch(h){case"ascii":case"latin1":case"binary":return b;case"utf8":case"utf-8":return ve(a).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*b;case"hex":return b>>>1;case"base64":return ee(a).length;default:if(O)return I?-1:ve(a).length;h=(""+h).toLowerCase(),O=!0}}function T(a,h,b){var I=!1;if((h===void 0||0>h)&&(h=0),h>this.length||((b===void 0||b>this.length)&&(b=this.length),0>=b)||(b>>>=0,h>>>=0,b<=h))return"";for(a||(a="utf8");;)switch(a){case"hex":return se(this,h,b);case"utf8":case"utf-8":return J(this,h,b);case"ascii":return F(this,h,b);case"latin1":case"binary":return V(this,h,b);case"base64":return H(this,h,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Y(this,h,b);default:if(I)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase(),I=!0}}function S(a,h,b){var I=a[h];a[h]=a[b],a[b]=I}function C(a,h,b,I,O){if(a.length===0)return-1;if(typeof b=="string"?(I=b,b=0):2147483647<b?b=2147483647:-2147483648>b&&(b=-2147483648),b=+b,W(b)&&(b=O?0:a.length-1),0>b&&(b=a.length+b),b>=a.length){if(O)return-1;b=a.length-1}else if(0>b)if(O)b=0;else return-1;if(typeof h=="string"&&(h=u.from(h,I)),u.isBuffer(h))return h.length===0?-1:D(a,h,b,I,O);if(typeof h=="number")return h&=255,typeof Uint8Array.prototype.indexOf=="function"?O?Uint8Array.prototype.indexOf.call(a,h,b):Uint8Array.prototype.lastIndexOf.call(a,h,b):D(a,[h],b,I,O);throw new TypeError("val must be string, number or Buffer")}function D(a,h,b,I,O){function U(Mt,os){return re===1?Mt[os]:Mt.readUInt16BE(os*re)}var re=1,fe=a.length,_e=h.length;if(I!==void 0&&(I=(I+"").toLowerCase(),I==="ucs2"||I==="ucs-2"||I==="utf16le"||I==="utf-16le")){if(2>a.length||2>h.length)return-1;re=2,fe/=2,_e/=2,b/=2}var pe;if(O){var ue=-1;for(pe=b;pe<fe;pe++)if(U(a,pe)!==U(h,ue===-1?0:pe-ue))ue!==-1&&(pe-=pe-ue),ue=-1;else if(ue===-1&&(ue=pe),pe-ue+1===_e)return ue*re}else for(b+_e>fe&&(b=fe-_e),pe=b;0<=pe;pe--){for(var Pe=!0,vt=0;vt<_e;vt++)if(U(a,pe+vt)!==U(h,vt)){Pe=!1;break}if(Pe)return pe}return-1}function j(a,h,b,I){b=+b||0;var O=a.length-b;I?(I=+I,I>O&&(I=O)):I=O;var U=h.length;I>U/2&&(I=U/2);for(var re,fe=0;fe<I;++fe){if(re=parseInt(h.substr(2*fe,2),16),W(re))return fe;a[b+fe]=re}return fe}function R(a,h,b,I){return ae(ve(h,a.length-b),a,b,I)}function P(a,h,b,I){return ae(X(h),a,b,I)}function B(a,h,b,I){return P(a,h,b,I)}function z(a,h,b,I){return ae(ee(h),a,b,I)}function q(a,h,b,I){return ae(K(h,a.length-b),a,b,I)}function H(a,h,b){return h===0&&b===a.length?G.fromByteArray(a):G.fromByteArray(a.slice(h,b))}function J(a,h,b){b=p(a.length,b);for(var I=[],O=h;O<b;){var U=a[O],re=null,fe=239<U?4:223<U?3:191<U?2:1;if(O+fe<=b){var _e,pe,ue,Pe;fe===1?128>U&&(re=U):fe===2?(_e=a[O+1],(192&_e)==128&&(Pe=(31&U)<<6|63&_e,127<Pe&&(re=Pe))):fe===3?(_e=a[O+1],pe=a[O+2],(192&_e)==128&&(192&pe)==128&&(Pe=(15&U)<<12|(63&_e)<<6|63&pe,2047<Pe&&(55296>Pe||57343<Pe)&&(re=Pe))):fe===4&&(_e=a[O+1],pe=a[O+2],ue=a[O+3],(192&_e)==128&&(192&pe)==128&&(192&ue)==128&&(Pe=(15&U)<<18|(63&_e)<<12|(63&pe)<<6|63&ue,65535<Pe&&1114112>Pe&&(re=Pe)))}re===null?(re=65533,fe=1):65535<re&&(re-=65536,I.push(55296|1023&re>>>10),re=56320|1023&re),I.push(re),O+=fe}return $(I)}function $(a){var h=a.length;if(h<=4096)return l.apply(String,a);for(var b="",I=0;I<h;)b+=l.apply(String,a.slice(I,I+=4096));return b}function F(a,h,b){var I="";b=p(a.length,b);for(var O=h;O<b;++O)I+=l(127&a[O]);return I}function V(a,h,b){var I="";b=p(a.length,b);for(var O=h;O<b;++O)I+=l(a[O]);return I}function se(a,h,b){var I=a.length;(!h||0>h)&&(h=0),(!b||0>b||b>I)&&(b=I);for(var O="",U=h;U<b;++U)O+=xe(a[U]);return O}function Y(a,h,b){for(var I=a.slice(h,b),O="",U=0;U<I.length;U+=2)O+=l(I[U]+256*I[U+1]);return O}function te(a,h,b){if(a%1!=0||0>a)throw new RangeError("offset is not uint");if(a+h>b)throw new RangeError("Trying to access beyond buffer length")}function Q(a,h,b,I,O,U){if(!u.isBuffer(a))throw new TypeError('"buffer" argument must be a Buffer instance');if(h>O||h<U)throw new RangeError('"value" argument is out of bounds');if(b+I>a.length)throw new RangeError("Index out of range")}function be(a,h,b,I){if(b+I>a.length)throw new RangeError("Index out of range");if(0>b)throw new RangeError("Index out of range")}function Ce(a,h,b,I,O){return h=+h,b>>>=0,O||be(a,h,b,4),ne.write(a,h,b,I,23,4),b+4}function ce(a,h,b,I,O){return h=+h,b>>>=0,O||be(a,h,b,8),ne.write(a,h,b,I,52,8),b+8}function ye(a){if(a=a.split("=")[0],a=a.trim().replace(N,""),2>a.length)return"";for(;a.length%4!=0;)a+="=";return a}function xe(a){return 16>a?"0"+a.toString(16):a.toString(16)}function ve(a,h){h=h||1/0;for(var b,I=a.length,O=null,U=[],re=0;re<I;++re){if(b=a.charCodeAt(re),55295<b&&57344>b){if(!O){if(56319<b){-1<(h-=3)&&U.push(239,191,189);continue}else if(re+1===I){-1<(h-=3)&&U.push(239,191,189);continue}O=b;continue}if(56320>b){-1<(h-=3)&&U.push(239,191,189),O=b;continue}b=(O-55296<<10|b-56320)+65536}else O&&-1<(h-=3)&&U.push(239,191,189);if(O=null,128>b){if(0>(h-=1))break;U.push(b)}else if(2048>b){if(0>(h-=2))break;U.push(192|b>>6,128|63&b)}else if(65536>b){if(0>(h-=3))break;U.push(224|b>>12,128|63&b>>6,128|63&b)}else if(1114112>b){if(0>(h-=4))break;U.push(240|b>>18,128|63&b>>12,128|63&b>>6,128|63&b)}else throw new Error("Invalid code point")}return U}function X(a){for(var h=[],b=0;b<a.length;++b)h.push(255&a.charCodeAt(b));return h}function K(a,h){for(var b,I,O,U=[],re=0;re<a.length&&!(0>(h-=2));++re)b=a.charCodeAt(re),I=b>>8,O=b%256,U.push(O),U.push(I);return U}function ee(a){return G.toByteArray(ye(a))}function ae(a,h,b,I){for(var O=0;O<I&&!(O+b>=h.length||O>=a.length);++O)h[O+b]=a[O];return O}function M(a,h){return a instanceof h||a!=null&&a.constructor!=null&&a.constructor.name!=null&&a.constructor.name===h.name}function W(a){return a!==a}var G=o("base64-js"),ne=o("ieee754");d.Buffer=u,d.SlowBuffer=function(a){return+a!=a&&(a=0),u.alloc(+a)},d.INSPECT_MAX_BYTES=50,d.kMaxLength=2147483647,u.TYPED_ARRAY_SUPPORT=(function(){try{var a=new Uint8Array(1);return a.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},a.foo()===42}catch{return!1}})(),u.TYPED_ARRAY_SUPPORT||typeof console>"u"||typeof console.error!="function"||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(u.prototype,"parent",{enumerable:!0,get:function(){return u.isBuffer(this)?this.buffer:void 0}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){return u.isBuffer(this)?this.byteOffset:void 0}}),typeof Symbol<"u"&&Symbol.species!=null&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),u.poolSize=8192,u.from=function(a,h,b){return f(a,h,b)},u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,u.alloc=function(a,h,b){return y(a,h,b)},u.allocUnsafe=function(a){return E(a)},u.allocUnsafeSlow=function(a){return E(a)},u.isBuffer=function(a){return a!=null&&a._isBuffer===!0&&a!==u.prototype},u.compare=function(a,h){if(M(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),M(h,Uint8Array)&&(h=u.from(h,h.offset,h.byteLength)),!u.isBuffer(a)||!u.isBuffer(h))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(a===h)return 0;for(var b=a.length,I=h.length,O=0,U=p(b,I);O<U;++O)if(a[O]!==h[O]){b=a[O],I=h[O];break}return b<I?-1:I<b?1:0},u.isEncoding=function(a){switch((a+"").toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(a,h){if(!Array.isArray(a))throw new TypeError('"list" argument must be an Array of Buffers');if(a.length===0)return u.alloc(0);var b;if(h===void 0)for(h=0,b=0;b<a.length;++b)h+=a[b].length;var I=u.allocUnsafe(h),O=0;for(b=0;b<a.length;++b){var U=a[b];if(M(U,Uint8Array)&&(U=u.from(U)),!u.isBuffer(U))throw new TypeError('"list" argument must be an Array of Buffers');U.copy(I,O),O+=U.length}return I},u.byteLength=_,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var a=this.length;if(a%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var h=0;h<a;h+=2)S(this,h,h+1);return this},u.prototype.swap32=function(){var a=this.length;if(a%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var h=0;h<a;h+=4)S(this,h,h+3),S(this,h+1,h+2);return this},u.prototype.swap64=function(){var a=this.length;if(a%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var h=0;h<a;h+=8)S(this,h,h+7),S(this,h+1,h+6),S(this,h+2,h+5),S(this,h+3,h+4);return this},u.prototype.toString=function(){var a=this.length;return a===0?"":arguments.length===0?J(this,0,a):T.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(a){if(!u.isBuffer(a))throw new TypeError("Argument must be a Buffer");return this===a||u.compare(this,a)===0},u.prototype.inspect=function(){var a="",h=d.INSPECT_MAX_BYTES;return a=this.toString("hex",0,h).replace(/(.{2})/g,"$1 ").trim(),this.length>h&&(a+=" ... "),"<Buffer "+a+">"},u.prototype.compare=function(a,h,b,I,O){if(M(a,Uint8Array)&&(a=u.from(a,a.offset,a.byteLength)),!u.isBuffer(a))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof a);if(h===void 0&&(h=0),b===void 0&&(b=a?a.length:0),I===void 0&&(I=0),O===void 0&&(O=this.length),0>h||b>a.length||0>I||O>this.length)throw new RangeError("out of range index");if(I>=O&&h>=b)return 0;if(I>=O)return-1;if(h>=b)return 1;if(h>>>=0,b>>>=0,I>>>=0,O>>>=0,this===a)return 0;for(var U=O-I,re=b-h,fe=p(U,re),_e=this.slice(I,O),pe=a.slice(h,b),ue=0;ue<fe;++ue)if(_e[ue]!==pe[ue]){U=_e[ue],re=pe[ue];break}return U<re?-1:re<U?1:0},u.prototype.includes=function(a,h,b){return this.indexOf(a,h,b)!==-1},u.prototype.indexOf=function(a,h,b){return C(this,a,h,b,!0)},u.prototype.lastIndexOf=function(a,h,b){return C(this,a,h,b,!1)},u.prototype.write=function(a,h,b,I){if(h===void 0)I="utf8",b=this.length,h=0;else if(b===void 0&&typeof h=="string")I=h,b=this.length,h=0;else if(isFinite(h))h>>>=0,isFinite(b)?(b>>>=0,I===void 0&&(I="utf8")):(I=b,b=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var O=this.length-h;if((b===void 0||b>O)&&(b=O),0<a.length&&(0>b||0>h)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");I||(I="utf8");for(var U=!1;;)switch(I){case"hex":return j(this,a,h,b);case"utf8":case"utf-8":return R(this,a,h,b);case"ascii":return P(this,a,h,b);case"latin1":case"binary":return B(this,a,h,b);case"base64":return z(this,a,h,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,a,h,b);default:if(U)throw new TypeError("Unknown encoding: "+I);I=(""+I).toLowerCase(),U=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},u.prototype.slice=function(a,h){var b=this.length;a=~~a,h=h===void 0?b:~~h,0>a?(a+=b,0>a&&(a=0)):a>b&&(a=b),0>h?(h+=b,0>h&&(h=0)):h>b&&(h=b),h<a&&(h=a);var I=this.subarray(a,h);return I.__proto__=u.prototype,I},u.prototype.readUIntLE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var I=this[a],O=1,U=0;++U<h&&(O*=256);)I+=this[a+U]*O;return I},u.prototype.readUIntBE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var I=this[a+--h],O=1;0<h&&(O*=256);)I+=this[a+--h]*O;return I},u.prototype.readUInt8=function(a,h){return a>>>=0,h||te(a,1,this.length),this[a]},u.prototype.readUInt16LE=function(a,h){return a>>>=0,h||te(a,2,this.length),this[a]|this[a+1]<<8},u.prototype.readUInt16BE=function(a,h){return a>>>=0,h||te(a,2,this.length),this[a]<<8|this[a+1]},u.prototype.readUInt32LE=function(a,h){return a>>>=0,h||te(a,4,this.length),(this[a]|this[a+1]<<8|this[a+2]<<16)+16777216*this[a+3]},u.prototype.readUInt32BE=function(a,h){return a>>>=0,h||te(a,4,this.length),16777216*this[a]+(this[a+1]<<16|this[a+2]<<8|this[a+3])},u.prototype.readIntLE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var I=this[a],O=1,U=0;++U<h&&(O*=256);)I+=this[a+U]*O;return O*=128,I>=O&&(I-=i(2,8*h)),I},u.prototype.readIntBE=function(a,h,b){a>>>=0,h>>>=0,b||te(a,h,this.length);for(var I=h,O=1,U=this[a+--I];0<I&&(O*=256);)U+=this[a+--I]*O;return O*=128,U>=O&&(U-=i(2,8*h)),U},u.prototype.readInt8=function(a,h){return a>>>=0,h||te(a,1,this.length),128&this[a]?-1*(255-this[a]+1):this[a]},u.prototype.readInt16LE=function(a,h){a>>>=0,h||te(a,2,this.length);var b=this[a]|this[a+1]<<8;return 32768&b?4294901760|b:b},u.prototype.readInt16BE=function(a,h){a>>>=0,h||te(a,2,this.length);var b=this[a+1]|this[a]<<8;return 32768&b?4294901760|b:b},u.prototype.readInt32LE=function(a,h){return a>>>=0,h||te(a,4,this.length),this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24},u.prototype.readInt32BE=function(a,h){return a>>>=0,h||te(a,4,this.length),this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]},u.prototype.readFloatLE=function(a,h){return a>>>=0,h||te(a,4,this.length),ne.read(this,a,!0,23,4)},u.prototype.readFloatBE=function(a,h){return a>>>=0,h||te(a,4,this.length),ne.read(this,a,!1,23,4)},u.prototype.readDoubleLE=function(a,h){return a>>>=0,h||te(a,8,this.length),ne.read(this,a,!0,52,8)},u.prototype.readDoubleBE=function(a,h){return a>>>=0,h||te(a,8,this.length),ne.read(this,a,!1,52,8)},u.prototype.writeUIntLE=function(a,h,b,I){if(a=+a,h>>>=0,b>>>=0,!I){var O=i(2,8*b)-1;Q(this,a,h,b,O,0)}var U=1,re=0;for(this[h]=255&a;++re<b&&(U*=256);)this[h+re]=255&a/U;return h+b},u.prototype.writeUIntBE=function(a,h,b,I){if(a=+a,h>>>=0,b>>>=0,!I){var O=i(2,8*b)-1;Q(this,a,h,b,O,0)}var U=b-1,re=1;for(this[h+U]=255&a;0<=--U&&(re*=256);)this[h+U]=255&a/re;return h+b},u.prototype.writeUInt8=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,1,255,0),this[h]=255&a,h+1},u.prototype.writeUInt16LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,65535,0),this[h]=255&a,this[h+1]=a>>>8,h+2},u.prototype.writeUInt16BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,65535,0),this[h]=a>>>8,this[h+1]=255&a,h+2},u.prototype.writeUInt32LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,4,4294967295,0),this[h+3]=a>>>24,this[h+2]=a>>>16,this[h+1]=a>>>8,this[h]=255&a,h+4},u.prototype.writeUInt32BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,4,4294967295,0),this[h]=a>>>24,this[h+1]=a>>>16,this[h+2]=a>>>8,this[h+3]=255&a,h+4},u.prototype.writeIntLE=function(a,h,b,I){if(a=+a,h>>>=0,!I){var O=i(2,8*b-1);Q(this,a,h,b,O-1,-O)}var U=0,re=1,fe=0;for(this[h]=255&a;++U<b&&(re*=256);)0>a&&fe===0&&this[h+U-1]!==0&&(fe=1),this[h+U]=255&(a/re>>0)-fe;return h+b},u.prototype.writeIntBE=function(a,h,b,I){if(a=+a,h>>>=0,!I){var O=i(2,8*b-1);Q(this,a,h,b,O-1,-O)}var U=b-1,re=1,fe=0;for(this[h+U]=255&a;0<=--U&&(re*=256);)0>a&&fe===0&&this[h+U+1]!==0&&(fe=1),this[h+U]=255&(a/re>>0)-fe;return h+b},u.prototype.writeInt8=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,1,127,-128),0>a&&(a=255+a+1),this[h]=255&a,h+1},u.prototype.writeInt16LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,32767,-32768),this[h]=255&a,this[h+1]=a>>>8,h+2},u.prototype.writeInt16BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,2,32767,-32768),this[h]=a>>>8,this[h+1]=255&a,h+2},u.prototype.writeInt32LE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,4,2147483647,-2147483648),this[h]=255&a,this[h+1]=a>>>8,this[h+2]=a>>>16,this[h+3]=a>>>24,h+4},u.prototype.writeInt32BE=function(a,h,b){return a=+a,h>>>=0,b||Q(this,a,h,4,2147483647,-2147483648),0>a&&(a=4294967295+a+1),this[h]=a>>>24,this[h+1]=a>>>16,this[h+2]=a>>>8,this[h+3]=255&a,h+4},u.prototype.writeFloatLE=function(a,h,b){return Ce(this,a,h,!0,b)},u.prototype.writeFloatBE=function(a,h,b){return Ce(this,a,h,!1,b)},u.prototype.writeDoubleLE=function(a,h,b){return ce(this,a,h,!0,b)},u.prototype.writeDoubleBE=function(a,h,b){return ce(this,a,h,!1,b)},u.prototype.copy=function(a,h,b,I){if(!u.isBuffer(a))throw new TypeError("argument should be a Buffer");if(b||(b=0),I||I===0||(I=this.length),h>=a.length&&(h=a.length),h||(h=0),0<I&&I<b&&(I=b),I===b||a.length===0||this.length===0)return 0;if(0>h)throw new RangeError("targetStart out of bounds");if(0>b||b>=this.length)throw new RangeError("Index out of range");if(0>I)throw new RangeError("sourceEnd out of bounds");I>this.length&&(I=this.length),a.length-h<I-b&&(I=a.length-h+b);var O=I-b;if(this===a&&typeof Uint8Array.prototype.copyWithin=="function")this.copyWithin(h,b,I);else if(this===a&&b<h&&h<I)for(var U=O-1;0<=U;--U)a[U+h]=this[U+b];else Uint8Array.prototype.set.call(a,this.subarray(b,I),h);return O},u.prototype.fill=function(a,h,b,I){if(typeof a=="string"){if(typeof h=="string"?(I=h,h=0,b=this.length):typeof b=="string"&&(I=b,b=this.length),I!==void 0&&typeof I!="string")throw new TypeError("encoding must be a string");if(typeof I=="string"&&!u.isEncoding(I))throw new TypeError("Unknown encoding: "+I);if(a.length===1){var O=a.charCodeAt(0);(I==="utf8"&&128>O||I==="latin1")&&(a=O)}}else typeof a=="number"&&(a&=255);if(0>h||this.length<h||this.length<b)throw new RangeError("Out of range index");if(b<=h)return this;h>>>=0,b=b===void 0?this.length:b>>>0,a||(a=0);var U;if(typeof a=="number")for(U=h;U<b;++U)this[U]=a;else{var re=u.isBuffer(a)?a:u.from(a,I),fe=re.length;if(fe===0)throw new TypeError('The value "'+a+'" is invalid for argument "value"');for(U=0;U<b-h;++U)this[U+h]=re[U%fe]}return this};var N=/[^+/0-9A-Za-z-_]/g}).call(this)}).call(this,o("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:9}],4:[function(o,c,d){(function(l){(function(){function p(){let u;try{u=d.storage.getItem("debug")}catch{}return!u&&typeof l<"u"&&"env"in l&&(u=l.env.DEBUG),u}d.formatArgs=function(u){if(u[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+u[0]+(this.useColors?"%c ":" ")+"+"+c.exports.humanize(this.diff),!this.useColors)return;const f="color: "+this.color;u.splice(1,0,f,"color: inherit");let x=0,y=0;u[0].replace(/%[a-zA-Z%]/g,E=>{E==="%%"||(x++,E==="%c"&&(y=x))}),u.splice(y,0,f)},d.save=function(u){try{u?d.storage.setItem("debug",u):d.storage.removeItem("debug")}catch{}},d.load=p,d.useColors=function(){return!!(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))||!(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&(typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&31<=parseInt(RegExp.$1,10)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},d.storage=(function(){try{return localStorage}catch{}})(),d.destroy=(()=>{let u=!1;return()=>{u||(u=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),d.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],d.log=console.debug||console.log||(()=>{}),c.exports=o("./common")(d);const{formatters:g}=c.exports;g.j=function(u){try{return JSON.stringify(u)}catch(f){return"[UnexpectedJSONParseError]: "+f.message}}}).call(this)}).call(this,o("_process"))},{"./common":5,_process:12}],5:[function(o,c){c.exports=function(d){function l(u){function f(...E){if(!f.enabled)return;const L=f,v=+new Date,A=v-(x||v);L.diff=A,L.prev=x,L.curr=v,x=v,E[0]=l.coerce(E[0]),typeof E[0]!="string"&&E.unshift("%O");let m=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(_,T)=>{if(_==="%%")return"%";m++;const S=l.formatters[T];if(typeof S=="function"){const C=E[m];_=S.call(L,C),E.splice(m,1),m--}return _}),l.formatArgs.call(L,E),(L.log||l.log).apply(L,E)}let x,y=null;return f.namespace=u,f.useColors=l.useColors(),f.color=l.selectColor(u),f.extend=p,f.destroy=l.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>y===null?l.enabled(u):y,set:E=>{y=E}}),typeof l.init=="function"&&l.init(f),f}function p(u,f){const x=l(this.namespace+(typeof f>"u"?":":f)+u);return x.log=this.log,x}function g(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}return l.debug=l,l.default=l,l.coerce=function(u){return u instanceof Error?u.stack||u.message:u},l.disable=function(){const u=[...l.names.map(g),...l.skips.map(g).map(f=>"-"+f)].join(",");return l.enable(""),u},l.enable=function(u){l.save(u),l.names=[],l.skips=[];let f;const x=(typeof u=="string"?u:"").split(/[\s,]+/),y=x.length;for(f=0;f<y;f++)x[f]&&(u=x[f].replace(/\*/g,".*?"),u[0]==="-"?l.skips.push(new RegExp("^"+u.substr(1)+"$")):l.names.push(new RegExp("^"+u+"$")))},l.enabled=function(u){if(u[u.length-1]==="*")return!0;let f,x;for(f=0,x=l.skips.length;f<x;f++)if(l.skips[f].test(u))return!1;for(f=0,x=l.names.length;f<x;f++)if(l.names[f].test(u))return!0;return!1},l.humanize=o("ms"),l.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(d).forEach(u=>{l[u]=d[u]}),l.names=[],l.skips=[],l.formatters={},l.selectColor=function(u){let f=0;for(let x=0;x<u.length;x++)f=(f<<5)-f+u.charCodeAt(x),f|=0;return l.colors[r(f)%l.colors.length]},l.enable(l.load()),l}},{ms:11}],6:[function(o,c){function d(l,p){for(const g in p)Object.defineProperty(l,g,{value:p[g],enumerable:!0,configurable:!0});return l}c.exports=function(l,p,g){if(!l||typeof l=="string")throw new TypeError("Please pass an Error to err-code");g||(g={}),typeof p=="object"&&(g=p,p=""),p&&(g.code=p);try{return d(l,g)}catch{g.message=l.message,g.stack=l.stack;const f=function(){};return f.prototype=Object.create(Object.getPrototypeOf(l)),d(new f,g)}}},{}],7:[function(o,c){function d(j){console&&console.warn&&console.warn(j)}function l(){l.init.call(this)}function p(j){if(typeof j!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof j)}function g(j){return j._maxListeners===void 0?l.defaultMaxListeners:j._maxListeners}function u(j,R,P,B){var z,q,H;if(p(P),q=j._events,q===void 0?(q=j._events=Object.create(null),j._eventsCount=0):(q.newListener!==void 0&&(j.emit("newListener",R,P.listener?P.listener:P),q=j._events),H=q[R]),H===void 0)H=q[R]=P,++j._eventsCount;else if(typeof H=="function"?H=q[R]=B?[P,H]:[H,P]:B?H.unshift(P):H.push(P),z=g(j),0<z&&H.length>z&&!H.warned){H.warned=!0;var J=new Error("Possible EventEmitter memory leak detected. "+H.length+" "+(R+" listeners added. Use emitter.setMaxListeners() to increase limit"));J.name="MaxListenersExceededWarning",J.emitter=j,J.type=R,J.count=H.length,d(J)}return j}function f(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function x(j,R,P){var B={fired:!1,wrapFn:void 0,target:j,type:R,listener:P},z=f.bind(B);return z.listener=P,B.wrapFn=z,z}function y(j,R,P){var B=j._events;if(B===void 0)return[];var z=B[R];return z===void 0?[]:typeof z=="function"?P?[z.listener||z]:[z]:P?A(z):L(z,z.length)}function E(j){var R=this._events;if(R!==void 0){var P=R[j];if(typeof P=="function")return 1;if(P!==void 0)return P.length}return 0}function L(j,R){for(var P=Array(R),B=0;B<R;++B)P[B]=j[B];return P}function v(j,R){for(;R+1<j.length;R++)j[R]=j[R+1];j.pop()}function A(j){for(var R=Array(j.length),P=0;P<R.length;++P)R[P]=j[P].listener||j[P];return R}function m(j,R,P){typeof j.on=="function"&&k(j,"error",R,P)}function k(j,R,P,B){if(typeof j.on=="function")B.once?j.once(R,P):j.on(R,P);else if(typeof j.addEventListener=="function")j.addEventListener(R,function z(q){B.once&&j.removeEventListener(R,z),P(q)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof j)}var _,T=typeof Reflect=="object"?Reflect:null,S=T&&typeof T.apply=="function"?T.apply:function(j,R,P){return Function.prototype.apply.call(j,R,P)};_=T&&typeof T.ownKeys=="function"?T.ownKeys:Object.getOwnPropertySymbols?function(j){return Object.getOwnPropertyNames(j).concat(Object.getOwnPropertySymbols(j))}:function(j){return Object.getOwnPropertyNames(j)};var C=Number.isNaN||function(j){return j!==j};c.exports=l,c.exports.once=function(j,R){return new Promise(function(P,B){function z(H){j.removeListener(R,q),B(H)}function q(){typeof j.removeListener=="function"&&j.removeListener("error",z),P([].slice.call(arguments))}k(j,R,q,{once:!0}),R!=="error"&&m(j,z,{once:!0})})},l.EventEmitter=l,l.prototype._events=void 0,l.prototype._eventsCount=0,l.prototype._maxListeners=void 0;var D=10;Object.defineProperty(l,"defaultMaxListeners",{enumerable:!0,get:function(){return D},set:function(j){if(typeof j!="number"||0>j||C(j))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+j+".");D=j}}),l.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},l.prototype.setMaxListeners=function(j){if(typeof j!="number"||0>j||C(j))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+j+".");return this._maxListeners=j,this},l.prototype.getMaxListeners=function(){return g(this)},l.prototype.emit=function(j){for(var R=[],P=1;P<arguments.length;P++)R.push(arguments[P]);var B=j==="error",z=this._events;if(z!==void 0)B=B&&z.error===void 0;else if(!B)return!1;if(B){var q;if(0<R.length&&(q=R[0]),q instanceof Error)throw q;var H=new Error("Unhandled error."+(q?" ("+q.message+")":""));throw H.context=q,H}var J=z[j];if(J===void 0)return!1;if(typeof J=="function")S(J,this,R);else for(var $=J.length,F=L(J,$),P=0;P<$;++P)S(F[P],this,R);return!0},l.prototype.addListener=function(j,R){return u(this,j,R,!1)},l.prototype.on=l.prototype.addListener,l.prototype.prependListener=function(j,R){return u(this,j,R,!0)},l.prototype.once=function(j,R){return p(R),this.on(j,x(this,j,R)),this},l.prototype.prependOnceListener=function(j,R){return p(R),this.prependListener(j,x(this,j,R)),this},l.prototype.removeListener=function(j,R){var P,B,z,q,H;if(p(R),B=this._events,B===void 0)return this;if(P=B[j],P===void 0)return this;if(P===R||P.listener===R)--this._eventsCount==0?this._events=Object.create(null):(delete B[j],B.removeListener&&this.emit("removeListener",j,P.listener||R));else if(typeof P!="function"){for(z=-1,q=P.length-1;0<=q;q--)if(P[q]===R||P[q].listener===R){H=P[q].listener,z=q;break}if(0>z)return this;z===0?P.shift():v(P,z),P.length===1&&(B[j]=P[0]),B.removeListener!==void 0&&this.emit("removeListener",j,H||R)}return this},l.prototype.off=l.prototype.removeListener,l.prototype.removeAllListeners=function(j){var R,P,B;if(P=this._events,P===void 0)return this;if(P.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):P[j]!==void 0&&(--this._eventsCount==0?this._events=Object.create(null):delete P[j]),this;if(arguments.length===0){var z,q=Object.keys(P);for(B=0;B<q.length;++B)z=q[B],z!=="removeListener"&&this.removeAllListeners(z);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(R=P[j],typeof R=="function")this.removeListener(j,R);else if(R!==void 0)for(B=R.length-1;0<=B;B--)this.removeListener(j,R[B]);return this},l.prototype.listeners=function(j){return y(this,j,!0)},l.prototype.rawListeners=function(j){return y(this,j,!1)},l.listenerCount=function(j,R){return typeof j.listenerCount=="function"?j.listenerCount(R):E.call(j,R)},l.prototype.listenerCount=E,l.prototype.eventNames=function(){return 0<this._eventsCount?_(this._events):[]}},{}],8:[function(o,c){c.exports=function(){if(typeof globalThis>"u")return null;var d={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return d.RTCPeerConnection?d:null}},{}],9:[function(o,c,d){/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */d.read=function(l,p,g,u,f){var x,y,E=8*f-u-1,L=(1<<E)-1,v=L>>1,A=-7,m=g?f-1:0,k=g?-1:1,_=l[p+m];for(m+=k,x=_&(1<<-A)-1,_>>=-A,A+=E;0<A;x=256*x+l[p+m],m+=k,A-=8);for(y=x&(1<<-A)-1,x>>=-A,A+=u;0<A;y=256*y+l[p+m],m+=k,A-=8);if(x===0)x=1-v;else{if(x===L)return y?NaN:(_?-1:1)*(1/0);y+=i(2,u),x-=v}return(_?-1:1)*y*i(2,x-u)},d.write=function(l,p,g,u,f,x){var y,E,L,v=Math.LN2,A=Math.log,m=8*x-f-1,k=(1<<m)-1,_=k>>1,T=f===23?i(2,-24)-i(2,-77):0,S=u?0:x-1,C=u?1:-1,D=0>p||p===0&&0>1/p?1:0;for(p=r(p),isNaN(p)||p===1/0?(E=isNaN(p)?1:0,y=k):(y=s(A(p)/v),1>p*(L=i(2,-y))&&(y--,L*=2),p+=1<=y+_?T/L:T*i(2,1-_),2<=p*L&&(y++,L/=2),y+_>=k?(E=0,y=k):1<=y+_?(E=(p*L-1)*i(2,f),y+=_):(E=p*i(2,_-1)*i(2,f),y=0));8<=f;l[g+S]=255&E,S+=C,E/=256,f-=8);for(y=y<<f|E,m+=f;0<m;l[g+S]=255&y,S+=C,y/=256,m-=8);l[g+S-C]|=128*D}},{}],10:[function(o,c){c.exports=typeof Object.create=="function"?function(d,l){l&&(d.super_=l,d.prototype=Object.create(l.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}))}:function(d,l){if(l){d.super_=l;var p=function(){};p.prototype=l.prototype,d.prototype=new p,d.prototype.constructor=d}}},{}],11:[function(o,c){var d=Math.round;function l(f){if(f+="",!(100<f.length)){var x=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(f);if(x){var y=parseFloat(x[1]),E=(x[2]||"ms").toLowerCase();return E==="years"||E==="year"||E==="yrs"||E==="yr"||E==="y"?315576e5*y:E==="weeks"||E==="week"||E==="w"?6048e5*y:E==="days"||E==="day"||E==="d"?864e5*y:E==="hours"||E==="hour"||E==="hrs"||E==="hr"||E==="h"?36e5*y:E==="minutes"||E==="minute"||E==="mins"||E==="min"||E==="m"?6e4*y:E==="seconds"||E==="second"||E==="secs"||E==="sec"||E==="s"?1e3*y:E==="milliseconds"||E==="millisecond"||E==="msecs"||E==="msec"||E==="ms"?y:void 0}}}function p(f){var x=r(f);return 864e5<=x?d(f/864e5)+"d":36e5<=x?d(f/36e5)+"h":6e4<=x?d(f/6e4)+"m":1e3<=x?d(f/1e3)+"s":f+"ms"}function g(f){var x=r(f);return 864e5<=x?u(f,x,864e5,"day"):36e5<=x?u(f,x,36e5,"hour"):6e4<=x?u(f,x,6e4,"minute"):1e3<=x?u(f,x,1e3,"second"):f+" ms"}function u(f,x,y,E){return d(f/y)+" "+E+(x>=1.5*y?"s":"")}c.exports=function(f,x){x=x||{};var y=typeof f;if(y=="string"&&0<f.length)return l(f);if(y==="number"&&isFinite(f))return x.long?g(f):p(f);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(f))}},{}],12:[function(o,c){function d(){throw new Error("setTimeout has not been defined")}function l(){throw new Error("clearTimeout has not been defined")}function p(T){if(E===setTimeout)return setTimeout(T,0);if((E===d||!E)&&setTimeout)return E=setTimeout,setTimeout(T,0);try{return E(T,0)}catch{try{return E.call(null,T,0)}catch{return E.call(this,T,0)}}}function g(T){if(L===clearTimeout)return clearTimeout(T);if((L===l||!L)&&clearTimeout)return L=clearTimeout,clearTimeout(T);try{return L(T)}catch{try{return L.call(null,T)}catch{return L.call(this,T)}}}function u(){k&&A&&(k=!1,A.length?m=A.concat(m):_=-1,m.length&&f())}function f(){if(!k){var T=p(u);k=!0;for(var S=m.length;S;){for(A=m,m=[];++_<S;)A&&A[_].run();_=-1,S=m.length}A=null,k=!1,g(T)}}function x(T,S){this.fun=T,this.array=S}function y(){}var E,L,v=c.exports={};(function(){try{E=typeof setTimeout=="function"?setTimeout:d}catch{E=d}try{L=typeof clearTimeout=="function"?clearTimeout:l}catch{L=l}})();var A,m=[],k=!1,_=-1;v.nextTick=function(T){var S=Array(arguments.length-1);if(1<arguments.length)for(var C=1;C<arguments.length;C++)S[C-1]=arguments[C];m.push(new x(T,S)),m.length!==1||k||p(f)},x.prototype.run=function(){this.fun.apply(null,this.array)},v.title="browser",v.browser=!0,v.env={},v.argv=[],v.version="",v.versions={},v.on=y,v.addListener=y,v.once=y,v.off=y,v.removeListener=y,v.removeAllListeners=y,v.emit=y,v.prependListener=y,v.prependOnceListener=y,v.listeners=function(){return[]},v.binding=function(){throw new Error("process.binding is not supported")},v.cwd=function(){return"/"},v.chdir=function(){throw new Error("process.chdir is not supported")},v.umask=function(){return 0}},{}],13:[function(o,c){(function(d){(function(){/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let l;c.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window>"u"?d:window):p=>(l||(l=Promise.resolve())).then(p).catch(g=>setTimeout(()=>{throw g},0))}).call(this)}).call(this,typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{}],14:[function(o,c){(function(d,l){(function(){var p=o("safe-buffer").Buffer,g=l.crypto||l.msCrypto;c.exports=g&&g.getRandomValues?function(u,f){if(u>4294967295)throw new RangeError("requested too many random bytes");var x=p.allocUnsafe(u);if(0<u)if(65536<u)for(var y=0;y<u;y+=65536)g.getRandomValues(x.slice(y,y+65536));else g.getRandomValues(x);return typeof f=="function"?d.nextTick(function(){f(null,x)}):x}:function(){throw new Error(`Secure random number generation is not supported by this browser.
37
+ Use Chrome, Firefox or Internet Explorer 11`)}}).call(this)}).call(this,o("_process"),typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{_process:12,"safe-buffer":30}],15:[function(o,c){function d(y,E){y.prototype=Object.create(E.prototype),y.prototype.constructor=y,y.__proto__=E}function l(y,E,L){function v(m,k,_){return typeof E=="string"?E:E(m,k,_)}L||(L=Error);var A=(function(m){function k(_,T,S){return m.call(this,v(_,T,S))||this}return d(k,m),k})(L);A.prototype.name=L.name,A.prototype.code=y,x[y]=A}function p(y,E){if(Array.isArray(y)){var L=y.length;return y=y.map(function(v){return v+""}),2<L?"one of ".concat(E," ").concat(y.slice(0,L-1).join(", "),", or ")+y[L-1]:L===2?"one of ".concat(E," ").concat(y[0]," or ").concat(y[1]):"of ".concat(E," ").concat(y[0])}return"of ".concat(E," ").concat(y+"")}function g(y,E,L){return y.substr(0,E.length)===E}function u(y,E,L){return(L===void 0||L>y.length)&&(L=y.length),y.substring(L-E.length,L)===E}function f(y,E,L){return typeof L!="number"&&(L=0),!(L+E.length>y.length)&&y.indexOf(E,L)!==-1}var x={};l("ERR_INVALID_OPT_VALUE",function(y,E){return'The value "'+E+'" is invalid for option "'+y+'"'},TypeError),l("ERR_INVALID_ARG_TYPE",function(y,E,L){var v;typeof E=="string"&&g(E,"not ")?(v="must not be",E=E.replace(/^not /,"")):v="must be";var A;if(u(y," argument"))A="The ".concat(y," ").concat(v," ").concat(p(E,"type"));else{var m=f(y,".")?"property":"argument";A='The "'.concat(y,'" ').concat(m," ").concat(v," ").concat(p(E,"type"))}return A+=". Received type ".concat(typeof L),A},TypeError),l("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),l("ERR_METHOD_NOT_IMPLEMENTED",function(y){return"The "+y+" method is not implemented"}),l("ERR_STREAM_PREMATURE_CLOSE","Premature close"),l("ERR_STREAM_DESTROYED",function(y){return"Cannot call "+y+" after a stream was destroyed"}),l("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),l("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),l("ERR_STREAM_WRITE_AFTER_END","write after end"),l("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),l("ERR_UNKNOWN_ENCODING",function(y){return"Unknown encoding: "+y},TypeError),l("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),c.exports.codes=x},{}],16:[function(o,c){(function(d){(function(){function l(v){return this instanceof l?(f.call(this,v),x.call(this,v),this.allowHalfOpen=!0,void(v&&(v.readable===!1&&(this.readable=!1),v.writable===!1&&(this.writable=!1),v.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",p))))):new l(v)}function p(){this._writableState.ended||d.nextTick(g,this)}function g(v){v.end()}var u=Object.keys||function(v){var A=[];for(var m in v)A.push(m);return A};c.exports=l;var f=o("./_stream_readable"),x=o("./_stream_writable");o("inherits")(l,f);for(var y,E=u(x.prototype),L=0;L<E.length;L++)y=E[L],l.prototype[y]||(l.prototype[y]=x.prototype[y]);Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._writableState!==void 0&&this._readableState.destroyed&&this._writableState.destroyed},set:function(v){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=v,this._writableState.destroyed=v)}})}).call(this)}).call(this,o("_process"))},{"./_stream_readable":18,"./_stream_writable":20,_process:12,inherits:10}],17:[function(o,c){function d(p){return this instanceof d?void l.call(this,p):new d(p)}c.exports=d;var l=o("./_stream_transform");o("inherits")(d,l),d.prototype._transform=function(p,g,u){u(null,p)}},{"./_stream_transform":19,inherits:10}],18:[function(o,c){(function(d,l){(function(){function p(N){return Y.from(N)}function g(N){return Y.isBuffer(N)||N instanceof te}function u(N,a,h){return typeof N.prependListener=="function"?N.prependListener(a,h):void(N._events&&N._events[a]?Array.isArray(N._events[a])?N._events[a].unshift(h):N._events[a]=[h,N._events[a]]:N.on(a,h))}function f(N,a,h){$=$||o("./_stream_duplex"),N=N||{},typeof h!="boolean"&&(h=a instanceof $),this.objectMode=!!N.objectMode,h&&(this.objectMode=this.objectMode||!!N.readableObjectMode),this.highWaterMark=X(this,N,"readableHighWaterMark",h),this.buffer=new ye,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=N.emitClose!==!1,this.autoDestroy=!!N.autoDestroy,this.destroyed=!1,this.defaultEncoding=N.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,N.encoding&&(!be&&(be=o("string_decoder/").StringDecoder),this.decoder=new be(N.encoding),this.encoding=N.encoding)}function x(N){if($=$||o("./_stream_duplex"),!(this instanceof x))return new x(N);var a=this instanceof $;this._readableState=new f(N,this,a),this.readable=!0,N&&(typeof N.read=="function"&&(this._read=N.read),typeof N.destroy=="function"&&(this._destroy=N.destroy)),se.call(this)}function y(N,a,h,b,I){F("readableAddChunk",a);var O=N._readableState;if(a===null)O.reading=!1,m(N,O);else{var U;if(I||(U=L(O,a)),U)G(N,U);else if(!(O.objectMode||a&&0<a.length))b||(O.reading=!1,T(N,O));else if(typeof a=="string"||O.objectMode||Object.getPrototypeOf(a)===Y.prototype||(a=p(a)),b)O.endEmitted?G(N,new W):E(N,O,a,!0);else if(O.ended)G(N,new ae);else{if(O.destroyed)return!1;O.reading=!1,O.decoder&&!h?(a=O.decoder.write(a),O.objectMode||a.length!==0?E(N,O,a,!1):T(N,O)):E(N,O,a,!1)}}return!O.ended&&(O.length<O.highWaterMark||O.length===0)}function E(N,a,h,b){a.flowing&&a.length===0&&!a.sync?(a.awaitDrain=0,N.emit("data",h)):(a.length+=a.objectMode?1:h.length,b?a.buffer.unshift(h):a.buffer.push(h),a.needReadable&&k(N)),T(N,a)}function L(N,a){var h;return g(a)||typeof a=="string"||a===void 0||N.objectMode||(h=new ee("chunk",["string","Buffer","Uint8Array"],a)),h}function v(N){return 1073741824<=N?N=1073741824:(N--,N|=N>>>1,N|=N>>>2,N|=N>>>4,N|=N>>>8,N|=N>>>16,N++),N}function A(N,a){return 0>=N||a.length===0&&a.ended?0:a.objectMode?1:N===N?(N>a.highWaterMark&&(a.highWaterMark=v(N)),N<=a.length?N:a.ended?a.length:(a.needReadable=!0,0)):a.flowing&&a.length?a.buffer.head.data.length:a.length}function m(N,a){if(F("onEofChunk"),!a.ended){if(a.decoder){var h=a.decoder.end();h&&h.length&&(a.buffer.push(h),a.length+=a.objectMode?1:h.length)}a.ended=!0,a.sync?k(N):(a.needReadable=!1,!a.emittedReadable&&(a.emittedReadable=!0,_(N)))}}function k(N){var a=N._readableState;F("emitReadable",a.needReadable,a.emittedReadable),a.needReadable=!1,a.emittedReadable||(F("emitReadable",a.flowing),a.emittedReadable=!0,d.nextTick(_,N))}function _(N){var a=N._readableState;F("emitReadable_",a.destroyed,a.length,a.ended),!a.destroyed&&(a.length||a.ended)&&(N.emit("readable"),a.emittedReadable=!1),a.needReadable=!a.flowing&&!a.ended&&a.length<=a.highWaterMark,B(N)}function T(N,a){a.readingMore||(a.readingMore=!0,d.nextTick(S,N,a))}function S(N,a){for(;!a.reading&&!a.ended&&(a.length<a.highWaterMark||a.flowing&&a.length===0);){var h=a.length;if(F("maybeReadMore read 0"),N.read(0),h===a.length)break}a.readingMore=!1}function C(N){return function(){var a=N._readableState;F("pipeOnDrain",a.awaitDrain),a.awaitDrain&&a.awaitDrain--,a.awaitDrain===0&&V(N,"data")&&(a.flowing=!0,B(N))}}function D(N){var a=N._readableState;a.readableListening=0<N.listenerCount("readable"),a.resumeScheduled&&!a.paused?a.flowing=!0:0<N.listenerCount("data")&&N.resume()}function j(N){F("readable nexttick read 0"),N.read(0)}function R(N,a){a.resumeScheduled||(a.resumeScheduled=!0,d.nextTick(P,N,a))}function P(N,a){F("resume",a.reading),a.reading||N.read(0),a.resumeScheduled=!1,N.emit("resume"),B(N),a.flowing&&!a.reading&&N.read(0)}function B(N){var a=N._readableState;for(F("flow",a.flowing);a.flowing&&N.read()!==null;);}function z(N,a){if(a.length===0)return null;var h;return a.objectMode?h=a.buffer.shift():!N||N>=a.length?(h=a.decoder?a.buffer.join(""):a.buffer.length===1?a.buffer.first():a.buffer.concat(a.length),a.buffer.clear()):h=a.buffer.consume(N,a.decoder),h}function q(N){var a=N._readableState;F("endReadable",a.endEmitted),a.endEmitted||(a.ended=!0,d.nextTick(H,a,N))}function H(N,a){if(F("endReadableNT",N.endEmitted,N.length),!N.endEmitted&&N.length===0&&(N.endEmitted=!0,a.readable=!1,a.emit("end"),N.autoDestroy)){var h=a._writableState;(!h||h.autoDestroy&&h.finished)&&a.destroy()}}function J(N,a){for(var h=0,b=N.length;h<b;h++)if(N[h]===a)return h;return-1}c.exports=x;var $;x.ReadableState=f;var F;o("events").EventEmitter;var V=function(N,a){return N.listeners(a).length},se=o("./internal/streams/stream"),Y=o("buffer").Buffer,te=l.Uint8Array||function(){},Q=o("util");F=Q&&Q.debuglog?Q.debuglog("stream"):function(){};var be,Ce,ce,ye=o("./internal/streams/buffer_list"),xe=o("./internal/streams/destroy"),ve=o("./internal/streams/state"),X=ve.getHighWaterMark,K=o("../errors").codes,ee=K.ERR_INVALID_ARG_TYPE,ae=K.ERR_STREAM_PUSH_AFTER_EOF,M=K.ERR_METHOD_NOT_IMPLEMENTED,W=K.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;o("inherits")(x,se);var G=xe.errorOrDestroy,ne=["error","close","destroy","pause","resume"];Object.defineProperty(x.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState!==void 0&&this._readableState.destroyed},set:function(N){this._readableState&&(this._readableState.destroyed=N)}}),x.prototype.destroy=xe.destroy,x.prototype._undestroy=xe.undestroy,x.prototype._destroy=function(N,a){a(N)},x.prototype.push=function(N,a){var h,b=this._readableState;return b.objectMode?h=!0:typeof N=="string"&&(a=a||b.defaultEncoding,a!==b.encoding&&(N=Y.from(N,a),a=""),h=!0),y(this,N,a,!1,h)},x.prototype.unshift=function(N){return y(this,N,null,!0,!1)},x.prototype.isPaused=function(){return this._readableState.flowing===!1},x.prototype.setEncoding=function(N){be||(be=o("string_decoder/").StringDecoder);var a=new be(N);this._readableState.decoder=a,this._readableState.encoding=this._readableState.decoder.encoding;for(var h=this._readableState.buffer.head,b="";h!==null;)b+=a.write(h.data),h=h.next;return this._readableState.buffer.clear(),b!==""&&this._readableState.buffer.push(b),this._readableState.length=b.length,this},x.prototype.read=function(N){F("read",N),N=parseInt(N,10);var a=this._readableState,h=N;if(N!==0&&(a.emittedReadable=!1),N===0&&a.needReadable&&((a.highWaterMark===0?0<a.length:a.length>=a.highWaterMark)||a.ended))return F("read: emitReadable",a.length,a.ended),a.length===0&&a.ended?q(this):k(this),null;if(N=A(N,a),N===0&&a.ended)return a.length===0&&q(this),null;var b=a.needReadable;F("need readable",b),(a.length===0||a.length-N<a.highWaterMark)&&(b=!0,F("length less than watermark",b)),a.ended||a.reading?(b=!1,F("reading or ended",b)):b&&(F("do read"),a.reading=!0,a.sync=!0,a.length===0&&(a.needReadable=!0),this._read(a.highWaterMark),a.sync=!1,!a.reading&&(N=A(h,a)));var I;return I=0<N?z(N,a):null,I===null?(a.needReadable=a.length<=a.highWaterMark,N=0):(a.length-=N,a.awaitDrain=0),a.length===0&&(!a.ended&&(a.needReadable=!0),h!==N&&a.ended&&q(this)),I!==null&&this.emit("data",I),I},x.prototype._read=function(){G(this,new M("_read()"))},x.prototype.pipe=function(N,a){function h(Ot,Pt){F("onunpipe"),Ot===pe&&Pt&&Pt.hasUnpiped===!1&&(Pt.hasUnpiped=!0,I())}function b(){F("onend"),N.end()}function I(){F("cleanup"),N.removeListener("close",re),N.removeListener("finish",fe),N.removeListener("drain",Mt),N.removeListener("error",U),N.removeListener("unpipe",h),pe.removeListener("end",b),pe.removeListener("end",_e),pe.removeListener("data",O),os=!0,ue.awaitDrain&&(!N._writableState||N._writableState.needDrain)&&Mt()}function O(Ot){F("ondata");var Pt=N.write(Ot);F("dest.write",Pt),Pt===!1&&((ue.pipesCount===1&&ue.pipes===N||1<ue.pipesCount&&J(ue.pipes,N)!==-1)&&!os&&(F("false write response, pause",ue.awaitDrain),ue.awaitDrain++),pe.pause())}function U(Ot){F("onerror",Ot),_e(),N.removeListener("error",U),V(N,"error")===0&&G(N,Ot)}function re(){N.removeListener("finish",fe),_e()}function fe(){F("onfinish"),N.removeListener("close",re),_e()}function _e(){F("unpipe"),pe.unpipe(N)}var pe=this,ue=this._readableState;switch(ue.pipesCount){case 0:ue.pipes=N;break;case 1:ue.pipes=[ue.pipes,N];break;default:ue.pipes.push(N)}ue.pipesCount+=1,F("pipe count=%d opts=%j",ue.pipesCount,a);var Pe=(!a||a.end!==!1)&&N!==d.stdout&&N!==d.stderr,vt=Pe?b:_e;ue.endEmitted?d.nextTick(vt):pe.once("end",vt),N.on("unpipe",h);var Mt=C(pe);N.on("drain",Mt);var os=!1;return pe.on("data",O),u(N,"error",U),N.once("close",re),N.once("finish",fe),N.emit("pipe",pe),ue.flowing||(F("pipe resume"),pe.resume()),N},x.prototype.unpipe=function(N){var a=this._readableState,h={hasUnpiped:!1};if(a.pipesCount===0)return this;if(a.pipesCount===1)return N&&N!==a.pipes?this:(N||(N=a.pipes),a.pipes=null,a.pipesCount=0,a.flowing=!1,N&&N.emit("unpipe",this,h),this);if(!N){var b=a.pipes,I=a.pipesCount;a.pipes=null,a.pipesCount=0,a.flowing=!1;for(var O=0;O<I;O++)b[O].emit("unpipe",this,{hasUnpiped:!1});return this}var U=J(a.pipes,N);return U===-1?this:(a.pipes.splice(U,1),a.pipesCount-=1,a.pipesCount===1&&(a.pipes=a.pipes[0]),N.emit("unpipe",this,h),this)},x.prototype.on=function(N,a){var h=se.prototype.on.call(this,N,a),b=this._readableState;return N==="data"?(b.readableListening=0<this.listenerCount("readable"),b.flowing!==!1&&this.resume()):N=="readable"&&!b.endEmitted&&!b.readableListening&&(b.readableListening=b.needReadable=!0,b.flowing=!1,b.emittedReadable=!1,F("on readable",b.length,b.reading),b.length?k(this):!b.reading&&d.nextTick(j,this)),h},x.prototype.addListener=x.prototype.on,x.prototype.removeListener=function(N,a){var h=se.prototype.removeListener.call(this,N,a);return N==="readable"&&d.nextTick(D,this),h},x.prototype.removeAllListeners=function(N){var a=se.prototype.removeAllListeners.apply(this,arguments);return(N==="readable"||N===void 0)&&d.nextTick(D,this),a},x.prototype.resume=function(){var N=this._readableState;return N.flowing||(F("resume"),N.flowing=!N.readableListening,R(this,N)),N.paused=!1,this},x.prototype.pause=function(){return F("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(F("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},x.prototype.wrap=function(N){var a=this,h=this._readableState,b=!1;for(var I in N.on("end",function(){if(F("wrapped end"),h.decoder&&!h.ended){var U=h.decoder.end();U&&U.length&&a.push(U)}a.push(null)}),N.on("data",function(U){if(F("wrapped data"),h.decoder&&(U=h.decoder.write(U)),!(h.objectMode&&U==null)&&(h.objectMode||U&&U.length)){var re=a.push(U);re||(b=!0,N.pause())}}),N)this[I]===void 0&&typeof N[I]=="function"&&(this[I]=(function(U){return function(){return N[U].apply(N,arguments)}})(I));for(var O=0;O<ne.length;O++)N.on(ne[O],this.emit.bind(this,ne[O]));return this._read=function(U){F("wrapped _read",U),b&&(b=!1,N.resume())},this},typeof Symbol=="function"&&(x.prototype[Symbol.asyncIterator]=function(){return Ce===void 0&&(Ce=o("./internal/streams/async_iterator")),Ce(this)}),Object.defineProperty(x.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(x.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(x.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(N){this._readableState&&(this._readableState.flowing=N)}}),x._fromList=z,Object.defineProperty(x.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),typeof Symbol=="function"&&(x.from=function(N,a){return ce===void 0&&(ce=o("./internal/streams/from")),ce(x,N,a)})}).call(this)}).call(this,o("_process"),typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/async_iterator":21,"./internal/streams/buffer_list":22,"./internal/streams/destroy":23,"./internal/streams/from":25,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,events:7,inherits:10,"string_decoder/":31,util:2}],19:[function(o,c){function d(v,A){var m=this._transformState;m.transforming=!1;var k=m.writecb;if(k===null)return this.emit("error",new x);m.writechunk=null,m.writecb=null,A!=null&&this.push(A),k(v);var _=this._readableState;_.reading=!1,(_.needReadable||_.length<_.highWaterMark)&&this._read(_.highWaterMark)}function l(v){return this instanceof l?(L.call(this,v),this._transformState={afterTransform:d.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,v&&(typeof v.transform=="function"&&(this._transform=v.transform),typeof v.flush=="function"&&(this._flush=v.flush)),void this.on("prefinish",p)):new l(v)}function p(){var v=this;typeof this._flush!="function"||this._readableState.destroyed?g(this,null,null):this._flush(function(A,m){g(v,A,m)})}function g(v,A,m){if(A)return v.emit("error",A);if(m!=null&&v.push(m),v._writableState.length)throw new E;if(v._transformState.transforming)throw new y;return v.push(null)}c.exports=l;var u=o("../errors").codes,f=u.ERR_METHOD_NOT_IMPLEMENTED,x=u.ERR_MULTIPLE_CALLBACK,y=u.ERR_TRANSFORM_ALREADY_TRANSFORMING,E=u.ERR_TRANSFORM_WITH_LENGTH_0,L=o("./_stream_duplex");o("inherits")(l,L),l.prototype.push=function(v,A){return this._transformState.needTransform=!1,L.prototype.push.call(this,v,A)},l.prototype._transform=function(v,A,m){m(new f("_transform()"))},l.prototype._write=function(v,A,m){var k=this._transformState;if(k.writecb=m,k.writechunk=v,k.writeencoding=A,!k.transforming){var _=this._readableState;(k.needTransform||_.needReadable||_.length<_.highWaterMark)&&this._read(_.highWaterMark)}},l.prototype._read=function(){var v=this._transformState;v.writechunk===null||v.transforming?v.needTransform=!0:(v.transforming=!0,this._transform(v.writechunk,v.writeencoding,v.afterTransform))},l.prototype._destroy=function(v,A){L.prototype._destroy.call(this,v,function(m){A(m)})}},{"../errors":15,"./_stream_duplex":16,inherits:10}],20:[function(o,c){(function(d,l){(function(){function p(M){var W=this;this.next=null,this.entry=null,this.finish=function(){q(W,M)}}function g(M){return F.from(M)}function u(M){return F.isBuffer(M)||M instanceof V}function f(){}function x(M,W,G){H=H||o("./_stream_duplex"),M=M||{},typeof G!="boolean"&&(G=W instanceof H),this.objectMode=!!M.objectMode,G&&(this.objectMode=this.objectMode||!!M.writableObjectMode),this.highWaterMark=te(this,M,"writableHighWaterMark",G),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var ne=M.decodeStrings===!1;this.decodeStrings=!ne,this.defaultEncoding=M.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(N){T(W,N)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=M.emitClose!==!1,this.autoDestroy=!!M.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new p(this)}function y(M){H=H||o("./_stream_duplex");var W=this instanceof H;return W||ae.call(y,this)?(this._writableState=new x(M,this,W),this.writable=!0,M&&(typeof M.write=="function"&&(this._write=M.write),typeof M.writev=="function"&&(this._writev=M.writev),typeof M.destroy=="function"&&(this._destroy=M.destroy),typeof M.final=="function"&&(this._final=M.final)),void $.call(this)):new y(M)}function E(M,W){var G=new X;ee(M,G),d.nextTick(W,G)}function L(M,W,G,ne){var N;return G===null?N=new ve:typeof G!="string"&&!W.objectMode&&(N=new be("chunk",["string","Buffer"],G)),!N||(ee(M,N),d.nextTick(ne,N),!1)}function v(M,W,G){return M.objectMode||M.decodeStrings===!1||typeof W!="string"||(W=F.from(W,G)),W}function A(M,W,G,ne,N,a){if(!G){var h=v(W,ne,N);ne!==h&&(G=!0,N="buffer",ne=h)}var b=W.objectMode?1:ne.length;W.length+=b;var I=W.length<W.highWaterMark;if(I||(W.needDrain=!0),W.writing||W.corked){var O=W.lastBufferedRequest;W.lastBufferedRequest={chunk:ne,encoding:N,isBuf:G,callback:a,next:null},O?O.next=W.lastBufferedRequest:W.bufferedRequest=W.lastBufferedRequest,W.bufferedRequestCount+=1}else m(M,W,!1,b,ne,N,a);return I}function m(M,W,G,ne,N,a,h){W.writelen=ne,W.writecb=h,W.writing=!0,W.sync=!0,W.destroyed?W.onwrite(new xe("write")):G?M._writev(N,W.onwrite):M._write(N,a,W.onwrite),W.sync=!1}function k(M,W,G,ne,N){--W.pendingcb,G?(d.nextTick(N,ne),d.nextTick(B,M,W),M._writableState.errorEmitted=!0,ee(M,ne)):(N(ne),M._writableState.errorEmitted=!0,ee(M,ne),B(M,W))}function _(M){M.writing=!1,M.writecb=null,M.length-=M.writelen,M.writelen=0}function T(M,W){var G=M._writableState,ne=G.sync,N=G.writecb;if(typeof N!="function")throw new ce;if(_(G),W)k(M,G,ne,W,N);else{var a=j(G)||M.destroyed;a||G.corked||G.bufferProcessing||!G.bufferedRequest||D(M,G),ne?d.nextTick(S,M,G,a,N):S(M,G,a,N)}}function S(M,W,G,ne){G||C(M,W),W.pendingcb--,ne(),B(M,W)}function C(M,W){W.length===0&&W.needDrain&&(W.needDrain=!1,M.emit("drain"))}function D(M,W){W.bufferProcessing=!0;var G=W.bufferedRequest;if(M._writev&&G&&G.next){var ne=W.bufferedRequestCount,N=Array(ne),a=W.corkedRequestsFree;a.entry=G;for(var h=0,b=!0;G;)N[h]=G,G.isBuf||(b=!1),G=G.next,h+=1;N.allBuffers=b,m(M,W,!0,W.length,N,"",a.finish),W.pendingcb++,W.lastBufferedRequest=null,a.next?(W.corkedRequestsFree=a.next,a.next=null):W.corkedRequestsFree=new p(W),W.bufferedRequestCount=0}else{for(;G;){var I=G.chunk,O=G.encoding,U=G.callback,re=W.objectMode?1:I.length;if(m(M,W,!1,re,I,O,U),G=G.next,W.bufferedRequestCount--,W.writing)break}G===null&&(W.lastBufferedRequest=null)}W.bufferedRequest=G,W.bufferProcessing=!1}function j(M){return M.ending&&M.length===0&&M.bufferedRequest===null&&!M.finished&&!M.writing}function R(M,W){M._final(function(G){W.pendingcb--,G&&ee(M,G),W.prefinished=!0,M.emit("prefinish"),B(M,W)})}function P(M,W){W.prefinished||W.finalCalled||(typeof M._final!="function"||W.destroyed?(W.prefinished=!0,M.emit("prefinish")):(W.pendingcb++,W.finalCalled=!0,d.nextTick(R,M,W)))}function B(M,W){var G=j(W);if(G&&(P(M,W),W.pendingcb===0&&(W.finished=!0,M.emit("finish"),W.autoDestroy))){var ne=M._readableState;(!ne||ne.autoDestroy&&ne.endEmitted)&&M.destroy()}return G}function z(M,W,G){W.ending=!0,B(M,W),G&&(W.finished?d.nextTick(G):M.once("finish",G)),W.ended=!0,M.writable=!1}function q(M,W,G){var ne=M.entry;for(M.entry=null;ne;){var N=ne.callback;W.pendingcb--,N(G),ne=ne.next}W.corkedRequestsFree.next=M}c.exports=y;var H;y.WritableState=x;var J={deprecate:o("util-deprecate")},$=o("./internal/streams/stream"),F=o("buffer").Buffer,V=l.Uint8Array||function(){},se=o("./internal/streams/destroy"),Y=o("./internal/streams/state"),te=Y.getHighWaterMark,Q=o("../errors").codes,be=Q.ERR_INVALID_ARG_TYPE,Ce=Q.ERR_METHOD_NOT_IMPLEMENTED,ce=Q.ERR_MULTIPLE_CALLBACK,ye=Q.ERR_STREAM_CANNOT_PIPE,xe=Q.ERR_STREAM_DESTROYED,ve=Q.ERR_STREAM_NULL_VALUES,X=Q.ERR_STREAM_WRITE_AFTER_END,K=Q.ERR_UNKNOWN_ENCODING,ee=se.errorOrDestroy;o("inherits")(y,$),x.prototype.getBuffer=function(){for(var M=this.bufferedRequest,W=[];M;)W.push(M),M=M.next;return W},(function(){try{Object.defineProperty(x.prototype,"buffer",{get:J.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var ae;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(ae=Function.prototype[Symbol.hasInstance],Object.defineProperty(y,Symbol.hasInstance,{value:function(M){return!!ae.call(this,M)||this===y&&M&&M._writableState instanceof x}})):ae=function(M){return M instanceof this},y.prototype.pipe=function(){ee(this,new ye)},y.prototype.write=function(M,W,G){var ne=this._writableState,N=!1,a=!ne.objectMode&&u(M);return a&&!F.isBuffer(M)&&(M=g(M)),typeof W=="function"&&(G=W,W=null),a?W="buffer":!W&&(W=ne.defaultEncoding),typeof G!="function"&&(G=f),ne.ending?E(this,G):(a||L(this,ne,M,G))&&(ne.pendingcb++,N=A(this,ne,a,M,W,G)),N},y.prototype.cork=function(){this._writableState.corked++},y.prototype.uncork=function(){var M=this._writableState;M.corked&&(M.corked--,!M.writing&&!M.corked&&!M.bufferProcessing&&M.bufferedRequest&&D(this,M))},y.prototype.setDefaultEncoding=function(M){if(typeof M=="string"&&(M=M.toLowerCase()),!(-1<["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((M+"").toLowerCase())))throw new K(M);return this._writableState.defaultEncoding=M,this},Object.defineProperty(y.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),y.prototype._write=function(M,W,G){G(new Ce("_write()"))},y.prototype._writev=null,y.prototype.end=function(M,W,G){var ne=this._writableState;return typeof M=="function"?(G=M,M=null,W=null):typeof W=="function"&&(G=W,W=null),M!=null&&this.write(M,W),ne.corked&&(ne.corked=1,this.uncork()),ne.ending||z(this,ne,G),this},Object.defineProperty(y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(y.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState!==void 0&&this._writableState.destroyed},set:function(M){this._writableState&&(this._writableState.destroyed=M)}}),y.prototype.destroy=se.destroy,y.prototype._undestroy=se.undestroy,y.prototype._destroy=function(M,W){W(M)}}).call(this)}).call(this,o("_process"),typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{"../errors":15,"./_stream_duplex":16,"./internal/streams/destroy":23,"./internal/streams/state":27,"./internal/streams/stream":28,_process:12,buffer:3,inherits:10,"util-deprecate":32}],21:[function(o,c){(function(d){(function(){function l(C,D,j){return D in C?Object.defineProperty(C,D,{value:j,enumerable:!0,configurable:!0,writable:!0}):C[D]=j,C}function p(C,D){return{value:C,done:D}}function g(C){var D=C[E];if(D!==null){var j=C[_].read();j!==null&&(C[m]=null,C[E]=null,C[L]=null,D(p(j,!1)))}}function u(C){d.nextTick(g,C)}function f(C,D){return function(j,R){C.then(function(){return D[A]?void j(p(void 0,!0)):void D[k](j,R)},R)}}var x,y=o("./end-of-stream"),E=Symbol("lastResolve"),L=Symbol("lastReject"),v=Symbol("error"),A=Symbol("ended"),m=Symbol("lastPromise"),k=Symbol("handlePromise"),_=Symbol("stream"),T=Object.getPrototypeOf(function(){}),S=Object.setPrototypeOf((x={get stream(){return this[_]},next:function(){var C=this,D=this[v];if(D!==null)return Promise.reject(D);if(this[A])return Promise.resolve(p(void 0,!0));if(this[_].destroyed)return new Promise(function(B,z){d.nextTick(function(){C[v]?z(C[v]):B(p(void 0,!0))})});var j,R=this[m];if(R)j=new Promise(f(R,this));else{var P=this[_].read();if(P!==null)return Promise.resolve(p(P,!1));j=new Promise(this[k])}return this[m]=j,j}},l(x,Symbol.asyncIterator,function(){return this}),l(x,"return",function(){var C=this;return new Promise(function(D,j){C[_].destroy(null,function(R){return R?void j(R):void D(p(void 0,!0))})})}),x),T);c.exports=function(C){var D,j=Object.create(S,(D={},l(D,_,{value:C,writable:!0}),l(D,E,{value:null,writable:!0}),l(D,L,{value:null,writable:!0}),l(D,v,{value:null,writable:!0}),l(D,A,{value:C._readableState.endEmitted,writable:!0}),l(D,k,{value:function(R,P){var B=j[_].read();B?(j[m]=null,j[E]=null,j[L]=null,R(p(B,!1))):(j[E]=R,j[L]=P)},writable:!0}),D));return j[m]=null,y(C,function(R){if(R&&R.code!=="ERR_STREAM_PREMATURE_CLOSE"){var P=j[L];return P!==null&&(j[m]=null,j[E]=null,j[L]=null,P(R)),void(j[v]=R)}var B=j[E];B!==null&&(j[m]=null,j[E]=null,j[L]=null,B(p(void 0,!0))),j[A]=!0}),C.on("readable",u.bind(null,j)),j}}).call(this)}).call(this,o("_process"))},{"./end-of-stream":24,_process:12}],22:[function(o,c){function d(m,k){var _=Object.keys(m);if(Object.getOwnPropertySymbols){var T=Object.getOwnPropertySymbols(m);k&&(T=T.filter(function(S){return Object.getOwnPropertyDescriptor(m,S).enumerable})),_.push.apply(_,T)}return _}function l(m){for(var k,_=1;_<arguments.length;_++)k=arguments[_]==null?{}:arguments[_],_%2?d(Object(k),!0).forEach(function(T){p(m,T,k[T])}):Object.getOwnPropertyDescriptors?Object.defineProperties(m,Object.getOwnPropertyDescriptors(k)):d(Object(k)).forEach(function(T){Object.defineProperty(m,T,Object.getOwnPropertyDescriptor(k,T))});return m}function p(m,k,_){return k in m?Object.defineProperty(m,k,{value:_,enumerable:!0,configurable:!0,writable:!0}):m[k]=_,m}function g(m,k){if(!(m instanceof k))throw new TypeError("Cannot call a class as a function")}function u(m,k){for(var _,T=0;T<k.length;T++)_=k[T],_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(m,_.key,_)}function f(m,k,_){return k&&u(m.prototype,k),m}function x(m,k,_){E.prototype.copy.call(m,k,_)}var y=o("buffer"),E=y.Buffer,L=o("util"),v=L.inspect,A=v&&v.custom||"inspect";c.exports=(function(){function m(){g(this,m),this.head=null,this.tail=null,this.length=0}return f(m,[{key:"push",value:function(k){var _={data:k,next:null};0<this.length?this.tail.next=_:this.head=_,this.tail=_,++this.length}},{key:"unshift",value:function(k){var _={data:k,next:this.head};this.length===0&&(this.tail=_),this.head=_,++this.length}},{key:"shift",value:function(){if(this.length!==0){var k=this.head.data;return this.head=this.length===1?this.tail=null:this.head.next,--this.length,k}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(k){if(this.length===0)return"";for(var _=this.head,T=""+_.data;_=_.next;)T+=k+_.data;return T}},{key:"concat",value:function(k){if(this.length===0)return E.alloc(0);for(var _=E.allocUnsafe(k>>>0),T=this.head,S=0;T;)x(T.data,_,S),S+=T.data.length,T=T.next;return _}},{key:"consume",value:function(k,_){var T;return k<this.head.data.length?(T=this.head.data.slice(0,k),this.head.data=this.head.data.slice(k)):k===this.head.data.length?T=this.shift():T=_?this._getString(k):this._getBuffer(k),T}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(k){var _=this.head,T=1,S=_.data;for(k-=S.length;_=_.next;){var C=_.data,D=k>C.length?C.length:k;if(S+=D===C.length?C:C.slice(0,k),k-=D,k===0){D===C.length?(++T,this.head=_.next?_.next:this.tail=null):(this.head=_,_.data=C.slice(D));break}++T}return this.length-=T,S}},{key:"_getBuffer",value:function(k){var _=E.allocUnsafe(k),T=this.head,S=1;for(T.data.copy(_),k-=T.data.length;T=T.next;){var C=T.data,D=k>C.length?C.length:k;if(C.copy(_,_.length-k,0,D),k-=D,k===0){D===C.length?(++S,this.head=T.next?T.next:this.tail=null):(this.head=T,T.data=C.slice(D));break}++S}return this.length-=S,_}},{key:A,value:function(k,_){return v(this,l({},_,{depth:0,customInspect:!1}))}}]),m})()},{buffer:3,util:2}],23:[function(o,c){(function(d){(function(){function l(u,f){g(u,f),p(u)}function p(u){u._writableState&&!u._writableState.emitClose||u._readableState&&!u._readableState.emitClose||u.emit("close")}function g(u,f){u.emit("error",f)}c.exports={destroy:function(u,f){var x=this,y=this._readableState&&this._readableState.destroyed,E=this._writableState&&this._writableState.destroyed;return y||E?(f?f(u):u&&(this._writableState?!this._writableState.errorEmitted&&(this._writableState.errorEmitted=!0,d.nextTick(g,this,u)):d.nextTick(g,this,u)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(u||null,function(L){!f&&L?x._writableState?x._writableState.errorEmitted?d.nextTick(p,x):(x._writableState.errorEmitted=!0,d.nextTick(l,x,L)):d.nextTick(l,x,L):f?(d.nextTick(p,x),f(L)):d.nextTick(p,x)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(u,f){var x=u._readableState,y=u._writableState;x&&x.autoDestroy||y&&y.autoDestroy?u.destroy(f):u.emit("error",f)}}}).call(this)}).call(this,o("_process"))},{_process:12}],24:[function(o,c){function d(f){var x=!1;return function(){if(!x){x=!0;for(var y=arguments.length,E=Array(y),L=0;L<y;L++)E[L]=arguments[L];f.apply(this,E)}}}function l(){}function p(f){return f.setHeader&&typeof f.abort=="function"}function g(f,x,y){if(typeof x=="function")return g(f,null,x);x||(x={}),y=d(y||l);var E=x.readable||x.readable!==!1&&f.readable,L=x.writable||x.writable!==!1&&f.writable,v=function(){f.writable||m()},A=f._writableState&&f._writableState.finished,m=function(){L=!1,A=!0,E||y.call(f)},k=f._readableState&&f._readableState.endEmitted,_=function(){E=!1,k=!0,L||y.call(f)},T=function(D){y.call(f,D)},S=function(){var D;return E&&!k?(f._readableState&&f._readableState.ended||(D=new u),y.call(f,D)):L&&!A?(f._writableState&&f._writableState.ended||(D=new u),y.call(f,D)):void 0},C=function(){f.req.on("finish",m)};return p(f)?(f.on("complete",m),f.on("abort",S),f.req?C():f.on("request",C)):L&&!f._writableState&&(f.on("end",v),f.on("close",v)),f.on("end",_),f.on("finish",m),x.error!==!1&&f.on("error",T),f.on("close",S),function(){f.removeListener("complete",m),f.removeListener("abort",S),f.removeListener("request",C),f.req&&f.req.removeListener("finish",m),f.removeListener("end",v),f.removeListener("close",v),f.removeListener("finish",m),f.removeListener("end",_),f.removeListener("error",T),f.removeListener("close",S)}}var u=o("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;c.exports=g},{"../../../errors":15}],25:[function(o,c){c.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],26:[function(o,c){function d(A){var m=!1;return function(){m||(m=!0,A.apply(void 0,arguments))}}function l(A){if(A)throw A}function p(A){return A.setHeader&&typeof A.abort=="function"}function g(A,m,k,_){_=d(_);var T=!1;A.on("close",function(){T=!0}),y===void 0&&(y=o("./end-of-stream")),y(A,{readable:m,writable:k},function(C){return C?_(C):(T=!0,void _())});var S=!1;return function(C){if(!T)return S?void 0:(S=!0,p(A)?A.abort():typeof A.destroy=="function"?A.destroy():void _(C||new v("pipe")))}}function u(A){A()}function f(A,m){return A.pipe(m)}function x(A){return A.length&&typeof A[A.length-1]=="function"?A.pop():l}var y,E=o("../../../errors").codes,L=E.ERR_MISSING_ARGS,v=E.ERR_STREAM_DESTROYED;c.exports=function(){for(var A=arguments.length,m=Array(A),k=0;k<A;k++)m[k]=arguments[k];var _=x(m);if(Array.isArray(m[0])&&(m=m[0]),2>m.length)throw new L("streams");var T,S=m.map(function(C,D){var j=D<m.length-1;return g(C,j,0<D,function(R){T||(T=R),R&&S.forEach(u),j||(S.forEach(u),_(T))})});return m.reduce(f)}},{"../../../errors":15,"./end-of-stream":24}],27:[function(o,c){function d(p,g,u){return p.highWaterMark==null?g?p[u]:null:p.highWaterMark}var l=o("../../../errors").codes.ERR_INVALID_OPT_VALUE;c.exports={getHighWaterMark:function(p,g,u,f){var x=d(g,f,u);if(x!=null){if(!(isFinite(x)&&s(x)===x)||0>x){var y=f?u:"highWaterMark";throw new l(y,x)}return s(x)}return p.objectMode?16:16384}}},{"../../../errors":15}],28:[function(o,c){c.exports=o("events").EventEmitter},{events:7}],29:[function(o,c,d){d=c.exports=o("./lib/_stream_readable.js"),d.Stream=d,d.Readable=d,d.Writable=o("./lib/_stream_writable.js"),d.Duplex=o("./lib/_stream_duplex.js"),d.Transform=o("./lib/_stream_transform.js"),d.PassThrough=o("./lib/_stream_passthrough.js"),d.finished=o("./lib/internal/streams/end-of-stream.js"),d.pipeline=o("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":16,"./lib/_stream_passthrough.js":17,"./lib/_stream_readable.js":18,"./lib/_stream_transform.js":19,"./lib/_stream_writable.js":20,"./lib/internal/streams/end-of-stream.js":24,"./lib/internal/streams/pipeline.js":26}],30:[function(o,c,d){function l(f,x){for(var y in f)x[y]=f[y]}function p(f,x,y){return u(f,x,y)}/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var g=o("buffer"),u=g.Buffer;u.from&&u.alloc&&u.allocUnsafe&&u.allocUnsafeSlow?c.exports=g:(l(g,d),d.Buffer=p),p.prototype=Object.create(u.prototype),l(u,p),p.from=function(f,x,y){if(typeof f=="number")throw new TypeError("Argument must not be a number");return u(f,x,y)},p.alloc=function(f,x,y){if(typeof f!="number")throw new TypeError("Argument must be a number");var E=u(f);return x===void 0?E.fill(0):typeof y=="string"?E.fill(x,y):E.fill(x),E},p.allocUnsafe=function(f){if(typeof f!="number")throw new TypeError("Argument must be a number");return u(f)},p.allocUnsafeSlow=function(f){if(typeof f!="number")throw new TypeError("Argument must be a number");return g.SlowBuffer(f)}},{buffer:3}],31:[function(o,c,d){function l(S){if(!S)return"utf8";for(var C;;)switch(S){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return S;default:if(C)return;S=(""+S).toLowerCase(),C=!0}}function p(S){var C=l(S);if(typeof C!="string"&&(_.isEncoding===T||!T(S)))throw new Error("Unknown encoding: "+S);return C||S}function g(S){this.encoding=p(S);var C;switch(this.encoding){case"utf16le":this.text=E,this.end=L,C=4;break;case"utf8":this.fillLast=y,C=4;break;case"base64":this.text=v,this.end=A,C=3;break;default:return this.write=m,void(this.end=k)}this.lastNeed=0,this.lastTotal=0,this.lastChar=_.allocUnsafe(C)}function u(S){return 127>=S?0:S>>5==6?2:S>>4==14?3:S>>3==30?4:S>>6==2?-1:-2}function f(S,C,D){var j=C.length-1;if(j<D)return 0;var R=u(C[j]);return 0<=R?(0<R&&(S.lastNeed=R-1),R):--j<D||R===-2?0:(R=u(C[j]),0<=R?(0<R&&(S.lastNeed=R-2),R):--j<D||R===-2?0:(R=u(C[j]),0<=R?(0<R&&(R===2?R=0:S.lastNeed=R-3),R):0))}function x(S,C){if((192&C[0])!=128)return S.lastNeed=0,"�";if(1<S.lastNeed&&1<C.length){if((192&C[1])!=128)return S.lastNeed=1,"�";if(2<S.lastNeed&&2<C.length&&(192&C[2])!=128)return S.lastNeed=2,"�"}}function y(S){var C=this.lastTotal-this.lastNeed,D=x(this,S);return D===void 0?this.lastNeed<=S.length?(S.copy(this.lastChar,C,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(S.copy(this.lastChar,C,0,S.length),void(this.lastNeed-=S.length)):D}function E(S,C){if((S.length-C)%2==0){var D=S.toString("utf16le",C);if(D){var j=D.charCodeAt(D.length-1);if(55296<=j&&56319>=j)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=S[S.length-2],this.lastChar[1]=S[S.length-1],D.slice(0,-1)}return D}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=S[S.length-1],S.toString("utf16le",C,S.length-1)}function L(S){var C=S&&S.length?this.write(S):"";if(this.lastNeed){var D=this.lastTotal-this.lastNeed;return C+this.lastChar.toString("utf16le",0,D)}return C}function v(S,C){var D=(S.length-C)%3;return D==0?S.toString("base64",C):(this.lastNeed=3-D,this.lastTotal=3,D==1?this.lastChar[0]=S[S.length-1]:(this.lastChar[0]=S[S.length-2],this.lastChar[1]=S[S.length-1]),S.toString("base64",C,S.length-D))}function A(S){var C=S&&S.length?this.write(S):"";return this.lastNeed?C+this.lastChar.toString("base64",0,3-this.lastNeed):C}function m(S){return S.toString(this.encoding)}function k(S){return S&&S.length?this.write(S):""}var _=o("safe-buffer").Buffer,T=_.isEncoding||function(S){switch(S=""+S,S&&S.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};d.StringDecoder=g,g.prototype.write=function(S){if(S.length===0)return"";var C,D;if(this.lastNeed){if(C=this.fillLast(S),C===void 0)return"";D=this.lastNeed,this.lastNeed=0}else D=0;return D<S.length?C?C+this.text(S,D):this.text(S,D):C||""},g.prototype.end=function(S){var C=S&&S.length?this.write(S):"";return this.lastNeed?C+"�":C},g.prototype.text=function(S,C){var D=f(this,S,C);if(!this.lastNeed)return S.toString("utf8",C);this.lastTotal=D;var j=S.length-(D-this.lastNeed);return S.copy(this.lastChar,0,j),S.toString("utf8",C,j)},g.prototype.fillLast=function(S){return this.lastNeed<=S.length?(S.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(S.copy(this.lastChar,this.lastTotal-this.lastNeed,0,S.length),void(this.lastNeed-=S.length))}},{"safe-buffer":30}],32:[function(o,c){(function(d){(function(){function l(p){try{if(!d.localStorage)return!1}catch{return!1}var g=d.localStorage[p];return g!=null&&(g+"").toLowerCase()==="true"}c.exports=function(p,g){function u(){if(!f){if(l("throwDeprecation"))throw new Error(g);l("traceDeprecation")?console.trace(g):console.warn(g),f=!0}return p.apply(this,arguments)}if(l("noDeprecation"))return p;var f=!1;return u}}).call(this)}).call(this,typeof et>"u"?typeof self>"u"?typeof window>"u"?{}:window:self:et)},{}],"/":[function(o,c){function d(A){return A.replace(/a=ice-options:trickle\s\n/g,"")}function l(A){console.warn(A)}/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const p=o("debug")("simple-peer"),g=o("get-browser-rtc"),u=o("randombytes"),f=o("readable-stream"),x=o("queue-microtask"),y=o("err-code"),{Buffer:E}=o("buffer"),L=65536;class v extends f.Duplex{constructor(m){if(m=Object.assign({allowHalfOpen:!1},m),super(m),this._id=u(4).toString("hex").slice(0,7),this._debug("new peer %o",m),this.channelName=m.initiator?m.channelName||u(20).toString("hex"):null,this.initiator=m.initiator||!1,this.channelConfig=m.channelConfig||v.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},v.config,m.config),this.offerOptions=m.offerOptions||{},this.answerOptions=m.answerOptions||{},this.sdpTransform=m.sdpTransform||(k=>k),this.streams=m.streams||(m.stream?[m.stream]:[]),this.trickle=m.trickle===void 0||m.trickle,this.allowHalfTrickle=m.allowHalfTrickle!==void 0&&m.allowHalfTrickle,this.iceCompleteTimeout=m.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=m.wrtc&&typeof m.wrtc=="object"?m.wrtc:g(),!this._wrtc)throw y(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(k){return void this.destroy(y(k,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=k=>{this._onIceCandidate(k)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(k=>{this.destroy(y(k,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=k=>{this._setupData(k)},this.streams&&this.streams.forEach(k=>{this.addStream(k)}),this._pc.ontrack=k=>{this._onTrack(k)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof m=="string")try{m=JSON.parse(m)}catch{m={}}this._debug("signal()"),m.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),m.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(m.transceiverRequest.kind,m.transceiverRequest.init)),m.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(m.candidate):this._pendingCandidates.push(m.candidate)),m.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(m)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(k=>{this._addIceCandidate(k)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(k=>{this.destroy(y(k,"ERR_SET_REMOTE_DESCRIPTION"))}),m.sdp||m.candidate||m.renegotiate||m.transceiverRequest||this.destroy(y(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(m){const k=new this._wrtc.RTCIceCandidate(m);this._pc.addIceCandidate(k).catch(_=>{!k.address||k.address.endsWith(".local")?l("Ignoring unsupported ICE candidate."):this.destroy(y(_,"ERR_ADD_ICE_CANDIDATE"))})}send(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(m)}}addTransceiver(m,k){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(m,k),this._needsNegotiation()}catch(_){this.destroy(y(_,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:m,init:k}})}}addStream(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),m.getTracks().forEach(k=>{this.addTrack(k,m)})}}addTrack(m,k){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const _=this._senderMap.get(m)||new Map;let T=_.get(k);if(!T)T=this._pc.addTrack(m,k),_.set(k,T),this._senderMap.set(m,_),this._needsNegotiation();else throw T.removed?y(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):y(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(m,k,_){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const T=this._senderMap.get(m),S=T?T.get(_):null;if(!S)throw y(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");k&&this._senderMap.set(k,T),S.replaceTrack==null?this.destroy(y(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK")):S.replaceTrack(k)}removeTrack(m,k){if(this.destroying)return;if(this.destroyed)throw y(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const _=this._senderMap.get(m),T=_?_.get(k):null;if(!T)throw y(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{T.removed=!0,this._pc.removeTrack(T)}catch(S){S.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(T):this.destroy(y(S,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(m){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),m.getTracks().forEach(k=>{this.removeTrack(k,m)})}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,x(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw y(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(m){this._destroy(m,()=>{})}_destroy(m,k){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",m&&(m.message||m)),x(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",m&&(m.message||m)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,m&&this.emit("error",m),this.emit("close"),k()}))}_setupData(m){if(!m.channel)return this.destroy(y(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=m.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=L),this.channelName=this._channel.label,this._channel.onmessage=_=>{this._onChannelMessage(_)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=_=>{const T=_.error instanceof Error?_.error:new Error(`Datachannel error: ${_.message} ${_.filename}:${_.lineno}:${_.colno}`);this.destroy(y(T,"ERR_DATA_CHANNEL"))};let k=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(k&&this._onChannelClose(),k=!0):k=!1},5e3)}_read(){}_write(m,k,_){if(this.destroyed)return _(y(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(m)}catch(T){return this.destroy(y(T,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>L?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=_):_(null)}else this._debug("write before connect"),this._chunk=m,this._cb=_}_onFinish(){if(!this.destroyed){const m=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?m():this.once("connect",m)}}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(m=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(m.sdp=d(m.sdp)),m.sdp=this.sdpTransform(m.sdp);const k=()=>{if(!this.destroyed){const _=this._pc.localDescription||m;this._debug("signal"),this.emit("signal",{type:_.type,sdp:_.sdp})}};this._pc.setLocalDescription(m).then(()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?k():this.once("_iceComplete",k))}).catch(_=>{this.destroy(y(_,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(m=>{this.destroy(y(m,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(m=>{m.mid||!m.sender.track||m.requested||(m.requested=!0,this.addTransceiver(m.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(m=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(m.sdp=d(m.sdp)),m.sdp=this.sdpTransform(m.sdp);const k=()=>{if(!this.destroyed){const _=this._pc.localDescription||m;this._debug("signal"),this.emit("signal",{type:_.type,sdp:_.sdp}),this.initiator||this._requestMissingTransceivers()}};this._pc.setLocalDescription(m).then(()=>{this.destroyed||(this.trickle||this._iceComplete?k():this.once("_iceComplete",k))}).catch(_=>{this.destroy(y(_,"ERR_SET_LOCAL_DESCRIPTION"))})}).catch(m=>{this.destroy(y(m,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(y(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const m=this._pc.iceConnectionState,k=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",m,k),this.emit("iceStateChange",m,k),(m==="connected"||m==="completed")&&(this._pcReady=!0,this._maybeReady()),m==="failed"&&this.destroy(y(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),m==="closed"&&this.destroy(y(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(m){const k=_=>(Object.prototype.toString.call(_.values)==="[object Array]"&&_.values.forEach(T=>{Object.assign(_,T)}),_);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(_=>{const T=[];_.forEach(S=>{T.push(k(S))}),m(null,T)},_=>m(_)):0<this._pc.getStats.length?this._pc.getStats(_=>{if(this.destroyed)return;const T=[];_.result().forEach(S=>{const C={};S.names().forEach(D=>{C[D]=S.stat(D)}),C.id=S.id,C.type=S.type,C.timestamp=S.timestamp,T.push(k(C))}),m(null,T)},_=>m(_)):m(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const m=()=>{this.destroyed||this.getStats((k,_)=>{if(this.destroyed)return;k&&(_=[]);const T={},S={},C={};let D=!1;_.forEach(R=>{(R.type==="remotecandidate"||R.type==="remote-candidate")&&(T[R.id]=R),(R.type==="localcandidate"||R.type==="local-candidate")&&(S[R.id]=R),(R.type==="candidatepair"||R.type==="candidate-pair")&&(C[R.id]=R)});const j=R=>{D=!0;let P=S[R.localCandidateId];P&&(P.ip||P.address)?(this.localAddress=P.ip||P.address,this.localPort=+P.port):P&&P.ipAddress?(this.localAddress=P.ipAddress,this.localPort=+P.portNumber):typeof R.googLocalAddress=="string"&&(P=R.googLocalAddress.split(":"),this.localAddress=P[0],this.localPort=+P[1]),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let B=T[R.remoteCandidateId];B&&(B.ip||B.address)?(this.remoteAddress=B.ip||B.address,this.remotePort=+B.port):B&&B.ipAddress?(this.remoteAddress=B.ipAddress,this.remotePort=+B.portNumber):typeof R.googRemoteAddress=="string"&&(B=R.googRemoteAddress.split(":"),this.remoteAddress=B[0],this.remotePort=+B[1]),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(_.forEach(R=>{R.type==="transport"&&R.selectedCandidatePairId&&j(C[R.selectedCandidatePairId]),(R.type==="googCandidatePair"&&R.googActiveConnection==="true"||(R.type==="candidatepair"||R.type==="candidate-pair")&&R.selected)&&j(R)}),!D&&(!Object.keys(C).length||Object.keys(S).length))return void setTimeout(m,100);if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(P){return this.destroy(y(P,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const R=this._cb;this._cb=null,R(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};m()}_onInterval(){this._cb&&this._channel&&!(this._channel.bufferedAmount>L)&&this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(m=>{this._pc.removeTrack(m),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(m){this.destroyed||(m.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:m.candidate.candidate,sdpMLineIndex:m.candidate.sdpMLineIndex,sdpMid:m.candidate.sdpMid}}):!m.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),m.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(m){if(this.destroyed)return;let k=m.data;k instanceof ArrayBuffer&&(k=E.from(k)),this.push(k)}_onChannelBufferedAmountLow(){if(!this.destroyed&&this._cb){this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const m=this._cb;this._cb=null,m(null)}}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(m){this.destroyed||m.streams.forEach(k=>{this._debug("on track"),this.emit("track",m.track,k),this._remoteTracks.push({track:m.track,stream:k}),this._remoteStreams.some(_=>_.id===k.id)||(this._remoteStreams.push(k),x(()=>{this._debug("on stream"),this.emit("stream",k)}))})}_debug(){const m=[].slice.call(arguments);m[0]="["+this._id+"] "+m[0],p.apply(null,m)}}v.WEBRTC_SUPPORT=!!g(),v.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},v.channelConfig={},c.exports=v},{buffer:3,debug:4,"err-code":6,"get-browser-rtc":8,"queue-microtask":13,randombytes:14,"readable-stream":29}]},{},[])("/")})})(Yn)),Yn.exports}var Fh=Uh();const $h=El(Fh),ii=0,oi=1,Ka=2,Ja=(t,e)=>{ie(t,ii);const s=pu(e);je(t,s)},Xa=(t,e,s)=>{ie(t,oi),je(t,Jr(e,s))},zh=(t,e,s)=>Xa(e,s,Ie(t)),Qa=(t,e,s,r)=>{try{ma(e,Ie(t),s)}catch(i){r!=null&&r(i),console.error("Caught error while handling a Yjs update",i)}},Hh=(t,e)=>{ie(t,Ka),je(t,e)},Vh=Qa,Gh=(t,e,s,r,i)=>{const o=de(t);switch(o){case ii:zh(t,e,s);break;case oi:Qa(t,s,r,i);break;case Ka:Vh(t,s,r,i);break;default:throw new Error("Unknown message type")}return o},Kn=3e4;class qh extends Lr{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const s=dt();this.getLocalState()!==null&&Kn/2<=s-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((i,o)=>{o!==this.clientID&&Kn<=s-i.lastUpdated&&this.states.has(o)&&r.push(o)}),r.length>0&&mr(this,r,"timeout")},Xe(Kn/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const s=this.clientID,r=this.meta.get(s),i=r===void 0?0:r.clock+1,o=this.states.get(s);e===null?this.states.delete(s):this.states.set(s,e),this.meta.set(s,{clock:i,lastUpdated:dt()});const c=[],d=[],l=[],p=[];e===null?p.push(s):o==null?e!=null&&c.push(s):(d.push(s),Ut(o,e)||l.push(s)),(c.length>0||l.length>0||p.length>0)&&this.emit("change",[{added:c,updated:l,removed:p},"local"]),this.emit("update",[{added:c,updated:d,removed:p},"local"])}setLocalStateField(e,s){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[e]:s})}getStates(){return this.states}}const mr=(t,e,s)=>{const r=[];for(let i=0;i<e.length;i++){const o=e[i];if(t.states.has(o)){if(t.states.delete(o),o===t.clientID){const c=t.meta.get(o);t.meta.set(o,{clock:c.clock+1,lastUpdated:dt()})}r.push(o)}}r.length>0&&(t.emit("change",[{added:[],updated:[],removed:r},s]),t.emit("update",[{added:[],updated:[],removed:r},s]))},ln=(t,e,s=t.states)=>{const r=e.length,i=De();ie(i,r);for(let o=0;o<r;o++){const c=e[o],d=s.get(c)||null,l=t.meta.get(c).clock;ie(i,c),ie(i,l),st(i,JSON.stringify(d))}return Se(i)},Yh=(t,e,s)=>{const r=it(e),i=dt(),o=[],c=[],d=[],l=[],p=de(r);for(let g=0;g<p;g++){const u=de(r);let f=de(r);const x=JSON.parse(lt(r)),y=t.meta.get(u),E=t.states.get(u),L=y===void 0?0:y.clock;(L<f||L===f&&x===null&&t.states.has(u))&&(x===null?u===t.clientID&&t.getLocalState()!=null?f++:t.states.delete(u):t.states.set(u,x),t.meta.set(u,{clock:f,lastUpdated:i}),y===void 0&&x!==null?o.push(u):y!==void 0&&x===null?l.push(u):x!==null&&(Ut(x,E)||d.push(u),c.push(u)))}(o.length>0||d.length>0||l.length>0)&&t.emit("change",[{added:o,updated:d,removed:l},s]),(o.length>0||c.length>0||l.length>0)&&t.emit("update",[{added:o,updated:c,removed:l},s])},Kh=(t,e)=>{const s=or(t).buffer,r=or(e).buffer;return crypto.subtle.importKey("raw",s,"PBKDF2",!1,["deriveKey"]).then(i=>crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:1e5,hash:"SHA-256"},i,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]))},Za=(t,e)=>{if(!e)return Wr(t);const s=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:s},e,t).then(r=>{const i=De();return st(i,"AES-GCM"),je(i,s),je(i,new Uint8Array(r)),Se(i)})},Jh=(t,e)=>{const s=De();return Gt(s,t),Za(Se(s),e)},el=(t,e)=>{if(!e)return Wr(t);const s=it(t);lt(s)!=="AES-GCM"&&Bc(Ge("Unknown encryption algorithm"));const i=Ie(s),o=Ie(s);return crypto.subtle.decrypt({name:"AES-GCM",iv:i},e,o).then(c=>new Uint8Array(c))},Xh=(t,e)=>el(t,e).then(s=>qt(it(new Uint8Array(s)))),ze=Xd("y-webrtc"),Ht=0,tl=3,Ss=1,ai=4,cn=new Map,jt=new Map,sl=t=>{let e=!0;t.webrtcConns.forEach(s=>{s.synced||(e=!1)}),(!e&&t.synced||e&&!t.synced)&&(t.synced=e,t.provider.emit("synced",[{synced:e}]),ze("synced ",Je,t.name,Nt," with all peers"))},nl=(t,e,s)=>{const r=it(e),i=De(),o=de(r);if(t===void 0)return null;const c=t.awareness,d=t.doc;let l=!1;switch(o){case Ht:{ie(i,Ht);const p=Gh(r,i,d,t);p===oi&&!t.synced&&s(),p===ii&&(l=!0);break}case tl:ie(i,Ss),je(i,ln(c,Array.from(c.getStates().keys()))),l=!0;break;case Ss:Yh(c,Ie(r),t);break;case ai:{const p=Et(r)===1,g=lt(r);if(g!==t.peerId&&(t.bcConns.has(g)&&!p||!t.bcConns.has(g)&&p)){const u=[],f=[];p?(t.bcConns.add(g),f.push(g)):(t.bcConns.delete(g),u.push(g)),t.provider.emit("peers",[{added:f,removed:u,webrtcPeers:Array.from(t.webrtcConns.keys()),bcPeers:Array.from(t.bcConns)}]),rl(t)}break}default:return console.error("Unable to compute message"),i}return l?i:null},Qh=(t,e)=>{const s=t.room;return ze("received message from ",Je,t.remotePeerId,Gr," (",s.name,")",Nt,Cn),nl(s,e,()=>{t.synced=!0,ze("synced ",Je,s.name,Nt," with ",Je,t.remotePeerId),sl(s)})},Jn=(t,e)=>{ze("send message to ",Je,t.remotePeerId,Nt,Gr," (",t.room.name,")",Cn);try{t.peer.send(Se(e))}catch{}},Zh=(t,e)=>{ze("broadcast message in ",Je,t.name,Nt),t.webrtcConns.forEach(s=>{try{s.peer.send(e)}catch{}})};class Bi{constructor(e,s,r,i){ze("establishing connection to ",Je,r),this.room=i,this.remotePeerId=r,this.glareToken=void 0,this.closed=!1,this.connected=!1,this.synced=!1,this.peer=new $h({initiator:s,...i.provider.peerOpts}),this.peer.on("signal",o=>{this.glareToken===void 0&&(this.glareToken=Date.now()+Math.random()),li(e,i,{to:r,from:i.peerId,type:"signal",token:this.glareToken,signal:o})}),this.peer.on("connect",()=>{ze("connected to ",Je,r),this.connected=!0;const c=i.provider.doc,d=i.awareness,l=De();ie(l,Ht),Ja(l,c),Jn(this,l);const p=d.getStates();if(p.size>0){const g=De();ie(g,Ss),je(g,ln(d,Array.from(p.keys()))),Jn(this,g)}}),this.peer.on("close",()=>{this.connected=!1,this.closed=!0,i.webrtcConns.has(this.remotePeerId)&&(i.webrtcConns.delete(this.remotePeerId),i.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}])),sl(i),this.peer.destroy(),ze("closed connection to ",Je,r),gr(i)}),this.peer.on("error",o=>{ze("Error in connection to ",Je,r,": ",o),gr(i)}),this.peer.on("data",o=>{const c=Qh(this,o);c!==null&&Jn(this,c)})}destroy(){this.peer.destroy()}}const pt=(t,e)=>Za(e,t.key).then(s=>t.mux(()=>Wh(t.name,s))),Ui=(t,e)=>{t.bcconnected&&pt(t,e),Zh(t,e)},gr=t=>{cn.forEach(e=>{e.connected&&(e.send({type:"subscribe",topics:[t.name]}),t.webrtcConns.size<t.provider.maxConns&&li(e,t,{type:"announce",from:t.peerId}))})},rl=t=>{if(t.provider.filterBcConns){const e=De();ie(e,ai),ys(e,1),st(e,t.peerId),pt(t,Se(e))}};class ef{constructor(e,s,r,i){this.peerId=Eo(),this.doc=e,this.awareness=s.awareness,this.provider=s,this.synced=!1,this.name=r,this.key=i,this.webrtcConns=new Map,this.bcConns=new Set,this.mux=Bh(),this.bcconnected=!1,this._bcSubscriber=o=>el(new Uint8Array(o),i).then(c=>this.mux(()=>{const d=nl(this,c,()=>{});d&&pt(this,Se(d))})),this._docUpdateHandler=(o,c)=>{const d=De();ie(d,Ht),Hh(d,o),Ui(this,Se(d))},this._awarenessUpdateHandler=({added:o,updated:c,removed:d},l)=>{const p=o.concat(c).concat(d),g=De();ie(g,Ss),je(g,ln(this.awareness,p)),Ui(this,Se(g))},this._beforeUnloadHandler=()=>{mr(this.awareness,[e.clientID],"window unload"),jt.forEach(o=>{o.disconnect()})},typeof window<"u"?window.addEventListener("beforeunload",this._beforeUnloadHandler):typeof process<"u"&&process.on("exit",this._beforeUnloadHandler)}connect(){this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),gr(this);const e=this.name;Oh(e,this._bcSubscriber),this.bcconnected=!0,rl(this);const s=De();ie(s,Ht),Ja(s,this.doc),pt(this,Se(s));const r=De();ie(r,Ht),Xa(r,this.doc),pt(this,Se(r));const i=De();ie(i,tl),pt(this,Se(i));const o=De();ie(o,Ss),je(o,ln(this.awareness,[this.doc.clientID])),pt(this,Se(o))}disconnect(){cn.forEach(s=>{s.connected&&s.send({type:"unsubscribe",topics:[this.name]})}),mr(this.awareness,[this.doc.clientID],"disconnect");const e=De();ie(e,ai),ys(e,0),st(e,this.peerId),pt(this,Se(e)),Ph(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 tf=(t,e,s,r)=>{if(jt.has(s))throw Ge(`A Yjs Doc connected to room "${s}" already exists!`);const i=new ef(t,e,s,r);return jt.set(s,i),i},li=(t,e,s)=>{e.key?Jh(s,e.key).then(r=>{t.send({type:"publish",topic:e.name,data:Mo(r)})}):t.send({type:"publish",topic:e.name,data:s})};class sf extends Ih{constructor(e){super(e),this.providers=new Set,this.on("connect",()=>{ze(`connected (${e})`);const s=Array.from(jt.keys());this.send({type:"subscribe",topics:s}),jt.forEach(r=>li(this,r,{type:"announce",from:r.peerId}))}),this.on("message",s=>{switch(s.type){case"publish":{const r=s.topic,i=jt.get(r);if(i==null||typeof r!="string")return;const o=c=>{const d=i.webrtcConns,l=i.peerId;if(c==null||c.from===l||c.to!==void 0&&c.to!==l||i.bcConns.has(c.from))return;const p=d.has(c.from)?()=>{}:()=>i.provider.emit("peers",[{removed:[],added:[c.from],webrtcPeers:Array.from(i.webrtcConns.keys()),bcPeers:Array.from(i.bcConns)}]);switch(c.type){case"announce":d.size<i.provider.maxConns&&(Ve(d,c.from,()=>new Bi(this,!0,c.from,i)),p());break;case"signal":if(c.signal.type==="offer"){const g=d.get(c.from);if(g){const u=c.token,f=g.glareToken;if(f&&f>u){ze("offer rejected: ",c.from);return}g.glareToken=void 0}}if(c.signal.type==="answer"){ze("offer answered by: ",c.from);const g=d.get(c.from);g.glareToken=void 0}c.to===l&&(Ve(d,c.from,()=>new Bi(this,!1,c.from,i)).peer.signal(c.signal),p());break}};i.key?typeof s.data=="string"&&Xh(Oo(s.data),i.key).then(o):o(s.data)}}}),this.on("disconnect",()=>ze(`disconnect (${e})`))}}const Xn=t=>{t.emit("status",[{connected:t.connected}])};class nf extends wo{constructor(e,s,{signaling:r=["wss://y-webrtc-eu.fly.dev"],password:i=null,awareness:o=new qh(s),maxConns:c=20+Xe(Pc()*15),filterBcConns:d=!0,peerOpts:l={}}={}){super(),this.roomName=e,this.doc=s,this.filterBcConns=d,this.awareness=o,this.shouldConnect=!1,this.signalingUrls=r,this.signalingConns=[],this.maxConns=c,this.peerOpts=l,this.key=i?Kh(i,e):Wr(null),this.room=null,this.key.then(p=>{this.room=tf(s,this,e,p),this.shouldConnect?this.room.connect():this.room.disconnect(),Xn(this)}),this.connect(),this.destroy=this.destroy.bind(this),s.on("destroy",this.destroy)}get connected(){return this.room!==null&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach(e=>{const s=Ve(cn,e,()=>new sf(e));this.signalingConns.push(s),s.providers.add(this)}),this.room&&(this.room.connect(),Xn(this))}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach(e=>{e.providers.delete(this),e.providers.size===0&&(e.destroy(),cn.delete(e.url))}),this.room&&(this.room.disconnect(),Xn(this))}destroy(){this.doc.off("destroy",this.destroy),this.key.then(()=>{this.room.destroy(),jt.delete(this.roomName)}),super.destroy()}}const us=new Map,dn=new Map,yr=new Map;function rf(){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem("titan2:webrtc"))==="1"}catch{return!1}}function of(t){if(!us.has(t)){const e=new rs({guid:`titan-space-${t}`});us.set(t,e);const s=new Rh(`titan-space-${t}`,e);if(dn.set(t,s),rf())try{const r=new nf(`titan-space-${t}`,e,{signaling:["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com"]});yr.set(t,r)}catch{}}return us.get(t)}function af(t){const{widgets:e}=wt(t),s=new Set,r=[];e.forEach((i,o)=>{const c=i.get("id");typeof c!="string"||s.has(c)?r.push(o):s.add(c)});for(let i=r.length-1;i>=0;i--)e.delete(r[i],1);return r.length}function wt(t){const e=of(t),s=e.getArray("widgets"),r=e.getMap("meta"),i=dn.get(t);return{widgets:s,meta:r,doc:e,whenSynced:i!=null&&i.synced?Promise.resolve():new Promise(o=>{const c=()=>{i==null||i.off("synced",c),o()};i==null||i.on("synced",c),setTimeout(()=>o(),2e3)})}}function lf(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 il(t){const e=new Tt;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 cf(t){try{const e=typeof localStorage<"u"?localStorage.getItem("titan2-spaces"):null;if(!e)return null;const r=JSON.parse(e).find(o=>o.id===t);if(!r)return null;const i=new Set;for(const o of r.widgets||[])o&&typeof o.id=="string"&&i.add(o.id);return i}catch{return null}}const un=new Map;function df(t,e){let s=un.get(t);s||(s=new Set,un.set(t,s)),s.add(e)}function uf(t,e){var s;return((s=un.get(t))==null?void 0:s.has(e))??!1}function ol(t){un.delete(t)}function hf(t,e){const{widgets:s}=wt(t),r=new Map,i=()=>{const c=new Set,d=cf(t),l=[];s.forEach(p=>{const g=lf(p);if(!g.id||c.has(g.id))return;const u=g.format==="system",f=typeof g.source=="string"&&g.source.trim()!=="";!u&&!f||d&&!d.has(g.id)&&!uf(t,g.id)||(c.add(g.id),l.push(g))}),e(l)},o=()=>{const c=new Set;s.forEach(d=>c.add(d));for(const[d,l]of r)c.has(d)||(d.unobserve(l),r.delete(d));for(const d of c)if(!r.has(d)){const l=()=>i();d.observe(l),r.set(d,l)}i()};return s.observe(o),o(),()=>{s.unobserve(o);for(const[c,d]of r)c.unobserve(d);r.clear()}}function ff(t,e){const{widgets:s}=wt(t),r={...e,id:`widget_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,createdAt:Date.now(),updatedAt:Date.now()};return df(t,r.id),s.push([il(r)]),r}function pf(t,e){const{widgets:s}=wt(t);let r=-1;s.forEach((i,o)=>{i.get("id")===e&&(r=o)}),r>=0&&s.delete(r,1)}function Fi(t,e,s){const{widgets:r}=wt(t);r.forEach(i=>{if(i.get("id")===e){for(const[o,c]of Object.entries(s))i.set(o,c);i.set("updatedAt",Date.now())}})}function mf(t){const{widgets:e}=wt(t);e.delete(0,e.length),ol(t)}function gf(t){var e,s,r;(e=dn.get(t))==null||e.destroy(),(s=yr.get(t))==null||s.destroy(),(r=us.get(t))==null||r.destroy(),dn.delete(t),yr.delete(t),us.delete(t),ol(t)}const hs="titan2-spaces",yf=!0;function he(t,e,s,r,i,o,c){return{id:t,name:e,format:"system",source:s,x:r,y:i,w:o,h:c,createdAt:Date.now(),updatedAt:Date.now()}}const Os=[{id:"home",name:"Home",icon:"Home",color:"#6366f1",widgets:[he("home-welcome","Welcome","system:soma",0,0,6,5),he("home-voice","Voice","system:voice",6,0,6,5),he("home-overview","Overview","system:overview",0,5,6,5),he("home-sessions","Sessions","system:sessions",6,5,6,5),he("home-watch","Watch","system:watch",0,10,12,7)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"soma",name:"SOMA",icon:"Brain",color:"#8b5cf6",widgets:[he("soma-main","SOMA","system:soma",0,0,8,8),he("soma-memory","Memory Graph","system:memory-graph",8,0,4,8)],agentInstructions:"This is the SOMA consciousness space. Help the user explore consciousness, memory, and self-improvement.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"command",name:"Command Post",icon:"Terminal",color:"#ef4444",widgets:[he("cp-hub","Command Post","system:command-post",0,0,12,10),he("cp-proposals","Self-Proposals","system:self-proposals",0,10,12,6)],agentInstructions:"This is the Command Post. Help the user manage agents, runs, and operations.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"intelligence",name:"Intelligence",icon:"Network",color:"#10b981",widgets:[he("intel-autopilot","Autopilot","system:intelligence-autopilot",0,0,6,5),he("intel-workflows","Workflows","system:intelligence-workflows",6,0,6,5),he("intel-learning","Learning","system:intelligence-learning",0,5,6,5),he("intel-memory","Memory Graph","system:memory-graph",6,5,6,5),he("intel-selfimprove","Self-Improve","system:intelligence-self-improve",0,10,6,5),he("intel-personas","Personas","system:intelligence-personas",6,10,6,5),he("intel-wiki","Memory Wiki","system:memory-wiki",0,15,6,6),he("intel-autoresearch","Autoresearch","system:autoresearch",6,15,6,6)],agentInstructions:"This is the Intelligence space. Help the user explore memory graphs, wiki, and knowledge.",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"infra",name:"Infrastructure",icon:"Server",color:"#f59e0b",widgets:[he("infra-homelab","Homelab","system:infra-homelab",0,0,6,6),he("infra-gpu","GPU / NVIDIA","system:infra-gpu",6,0,6,6),he("infra-files","Files","system:infra-files",0,6,4,5),he("infra-logs","Logs","system:infra-logs",4,6,4,5),he("infra-telemetry","Telemetry","system:infra-telemetry",8,6,4,5),he("infra-vram","VRAM","system:vram",0,11,6,5),he("infra-fleet","Fleet","system:fleet",6,11,6,5)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"tools",name:"Tools",icon:"Wrench",color:"#06b6d4",widgets:[he("tools-skills","Skills","system:tools-skills",0,0,6,6),he("tools-mcp","MCP Servers","system:tools-mcp",6,0,6,6),he("tools-integrations","Integrations","system:tools-integrations",0,6,4,5),he("tools-channels","Channels","system:tools-channels",4,6,4,5),he("tools-mesh","Mesh Network","system:tools-mesh",8,6,4,5),he("tools-recipes","Recipes","system:recipes",0,11,6,5),he("tools-browser","Browser","system:browser",6,11,6,5),he("tools-cron","Cron","system:cron",0,16,6,5)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},{id:"settings",name:"Settings",icon:"Settings",color:"#6b7280",widgets:[he("settings-specialists","Specialist Models","system:settings-specialists",0,0,6,8),he("settings-privacy","Privacy & Telemetry","system:settings-privacy",6,0,6,8),he("settings-general","General","system:settings-general",0,8,6,8),he("settings-security","Security","system:settings-security",6,8,6,8),he("settings-audit","Audit Log","system:settings-audit",0,16,12,6)],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}],br=11,al={home:new Set(["home-chat"]),tools:new Set(["tools-paperclip"])},xr=new Set(["system:paperclip","system:daemon"]);function bf(t,e){const{widgets:s,meta:r,whenSynced:i}=wt(t.id);i.then(()=>{try{const o=af(t.id);o>0&&console.info(`[SpaceEngine] healed ${o} duplicate widget(s) in "${t.id}"`);const c=al[t.id]??new Set;if(c.size>0||xr.size>0)for(let d=s.length-1;d>=0;d--){const l=s.get(d),p=l==null?void 0:l.get("id"),g=l==null?void 0:l.get("source"),u=typeof p=="string"&&c.has(p),f=typeof g=="string"&&xr.has(g);(u||f)&&s.delete(d,1)}if(e){for(let p=s.length-1;p>=0;p--){const g=s.get(p),u=g==null?void 0:g.get("source");(typeof u!="string"||u.trim()==="")&&s.delete(p,1)}const d=new Map;for(const p of t.widgets)d.set(p.id,p);const l=new Set;s.forEach(p=>{const g=p.get("id");if(typeof g=="string"&&d.has(g)){l.add(g);const u=d.get(g);p.set("x",u.x),p.set("y",u.y),p.set("w",u.w),p.set("h",u.h)}});for(const p of t.widgets)l.has(p.id)||s.push([il(p)]);r.set("seedVersion",br)}}catch(o){console.warn(`[SpaceEngine] healYSpaceOnSync failed for "${t.id}":`,o)}})}function xf(){try{const t=localStorage.getItem(hs),s=parseInt(localStorage.getItem(`${hs}-version`)||"0",10)<br;if(yf)for(const o of Os)bf(o,s);if(!t||s){localStorage.setItem(`${hs}-version`,String(br));const o=Os.map(c=>({...c,widgets:[...c.widgets]}));return kt(o),o}const r=JSON.parse(t);for(const o of r)Array.isArray(o.widgets)||(o.widgets=[]),o.widgets=o.widgets.filter(c=>c&&typeof c.id=="string").filter(c=>{var d;return!(((d=al[o.id])==null?void 0:d.has(c.id))??!1)}).filter(c=>!(typeof c.source=="string"&&xr.has(c.source))).map(c=>({...c,x:Number.isFinite(c.x)?Math.max(0,Math.floor(c.x)):0,y:Number.isFinite(c.y)?Math.max(0,Math.floor(c.y)):0,w:Number.isFinite(c.w)?Math.max(1,Math.floor(c.w)):4,h:Number.isFinite(c.h)?Math.max(1,Math.floor(c.h)):4}));for(const o of r){const c=new Set;o.widgets=o.widgets.filter(d=>c.has(d.id)?!1:(c.add(d.id),!0))}const i=new Map(r.map(o=>[o.id,o]));return Os.forEach(o=>{i.get(o.id)||i.set(o.id,{...o,widgets:[...o.widgets]})}),Array.from(i.values())}catch{return Os.map(t=>({...t,widgets:[...t.widgets]}))}}let Qn=null;function kt(t){Qn&&clearTimeout(Qn),Qn=setTimeout(()=>{localStorage.setItem(hs,JSON.stringify(t))},250)}let qe=null;const ke={list(){return qe||(qe=xf()),qe},get(t){return this.list().find(e=>e.id===t)},create(t){const e={id:`space_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,name:t,widgets:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return qe=[...this.list(),e],kt(qe),e},save(t){t.updatedAt=new Date().toISOString(),qe=this.list().map(e=>e.id===t.id?t:e),kt(qe)},remove(t){qe=this.list().filter(e=>e.id!==t),kt(qe)},addWidget(t,e){if(!e.source||e.source.trim()==="")throw new Error("Widget source cannot be empty");{const s=ff(t,e);try{const r=localStorage.getItem(hs),i=r?JSON.parse(r):[],o=i.find(c=>c.id===t);if(o)new Set((o.widgets||[]).map(d=>d.id)).has(s.id)||(o.widgets=[...o.widgets||[],s]),o.updatedAt=new Date().toISOString(),qe=i,kt(i);else{const c={id:t,name:t,widgets:[s],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};qe=[...i,c],kt(qe)}}catch{}return s}},updateWidget(t,e,s){Fi(t,e,s);const r=this.get(t);r&&(r.widgets=r.widgets.map(i=>i.id===e?{...i,...s,updatedAt:Date.now()}:i),this.save(r))},removeWidget(t,e){pf(t,e);const s=this.get(t);s&&(s.widgets=s.widgets.filter(r=>r.id!==e),this.save(s))},updateLayout(t,e){for(const r of e)Fi(t,r.i,{x:r.x,y:r.y,w:r.w,h:r.h});const s=this.get(t);s&&(s.widgets=s.widgets.map(r=>{const i=e.find(o=>o&&o.i===r.id);return i?{...r,x:Number.isFinite(i.x)?Math.max(0,Math.floor(i.x)):0,y:Number.isFinite(i.y)?Math.max(0,Math.floor(i.y)):0,w:Number.isFinite(i.w)?Math.max(1,Math.floor(i.w)):4,h:Number.isFinite(i.h)?Math.max(1,Math.floor(i.h)):4,updatedAt:Date.now()}:r}),this.save(s))},observe(t,e){return hf(t,e)},async clearSpace(t){{const{whenSynced:r}=wt(t);await r,mf(t),gf(t);try{const i=indexedDB.deleteDatabase(`titan-space-${t}`);await new Promise((o,c)=>{i.onsuccess=()=>o(),i.onerror=()=>c(i.error),i.onblocked=()=>o()})}catch{}}const e=this.list(),s=e.find(r=>r.id===t);s&&(s.widgets=[],kt(e))}};let as=null;function wf(){if(as)return as;const t=async e=>{const s=await fetch(e,{credentials:"same-origin"});if(!s.ok)throw new Error(`Failed to load ${e}: ${s.status} ${s.statusText}`);return s.text()};return as=Promise.all([t("/react.development.js"),t("/react-dom.development.js"),t("/babel.min.js")]).then(([e,s,r])=>({react:e,reactDom:s,babel:r})).catch(e=>{throw as=null,e}),as}function vf(t){const e=_f;return`<!DOCTYPE html><html><head><meta charset="UTF-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'unsafe-inline'; img-src blob: data:; font-src data:;"><style>* { box-sizing: border-box; } html, body { margin: 0; padding: 0; height: 100%; } body { background: transparent; color: #e5e7eb; font-family: system-ui, -apple-system, sans-serif; font-size: 13px; overflow: hidden; } #root { width: 100%; height: 100%; }</style></head><body><div id="root"><div id="sandbox-loading" style="padding:16px;font-family:monospace;font-size:12px;color:#52525b;"><div>Booting widget…</div></div></div><script>`+t.react+"<\/script><script>"+t.reactDom+"<\/script><script>"+t.babel+"<\/script>"+e}const _f=`
38
38
  <script>
39
39
  (function() {
40
40
  'use strict';
@@ -339,14 +339,14 @@ Use Chrome, Firefox or Internet Explorer 11`)}}).call(this)}).call(this,o("_proc
339
339
  })();
340
340
  <\/script>
341
341
  </body>
342
- </html>`;class al{constructor(e,s){$e(this,"iframe",null);$e(this,"pending",new Map);$e(this,"msgId",0);$e(this,"ready",!1);$e(this,"readyQueue",[]);$e(this,"onLog");$e(this,"messageHandler");$e(this,"messageListener");$e(this,"observer");this.iframe=e,this.onLog=s==null?void 0:s.onLog,this.init()}init(){const e=this.iframe;yf().then(i=>{!this.iframe||!document.contains(e)||(e.srcdoc=bf(i))}).catch(i=>{console.error("[sandbox] vendor scripts failed to load",i);for(const[o,c]of this.pending)c.reject(new Error("Sandbox boot failed: "+i.message)),this.pending.delete(o)});const s=i=>{const o=i.data;if(!(!o||typeof o!="object"||!o.type||typeof o.type!="string"||!["ready","rendered","error","result","fetch","api","state","canvas","log","import"].includes(o.type))){if((o==null?void 0:o.type)==="ready"){this.ready=!0,this.readyQueue.forEach(d=>d()),this.readyQueue=[];return}if(typeof(o==null?void 0:o.id)=="number"&&this.pending.has(o.id)){const d=this.pending.get(o.id);this.pending.delete(o.id),o.type==="error"?d.reject(new Error(o.error||"Sandbox error")):d.resolve(o.payload);return}if((o==null?void 0:o.type)==="fetch"||(o==null?void 0:o.type)==="api"||(o==null?void 0:o.type)==="state"||(o==null?void 0:o.type)==="canvas"||(o==null?void 0:o.type)==="log"||(o==null?void 0:o.type)==="import"){this.handleIframeRequest(o.type,o.id,o.payload);return}}};this.messageListener=s,window.addEventListener("message",s);const r=new MutationObserver(()=>{document.contains(e)||this.destroy()});this.observer=r,e.parentNode&&r.observe(e.parentNode,{childList:!0,subtree:!0})}async handleIframeRequest(e,s,r){var o;const i=this.iframe;if(i!=null&&i.contentWindow)try{let c;if(e==="log")(o=this.onLog)==null||o.call(this,(r==null?void 0:r.args)||[]),c={ok:!0};else if(e==="fetch"){const{url:d,options:l}=r||{},p=localStorage.getItem("titan-token"),g={...(l==null?void 0:l.headers)||{}};let u=!1;try{typeof d=="string"&&(d.startsWith("/")?u=!0:u=new URL(d,window.location.href).origin===window.location.origin)}catch{}p&&u&&(g.Authorization=`Bearer ${p}`);const f=await fetch(d,{...l,headers:g}),x=await f.text();let y;try{y=JSON.parse(x)}catch{}c={ok:f.ok,status:f.status,text:x,json:y}}else if(e==="api"){const{endpoint:d,body:l}=r||{},p=localStorage.getItem("titan-token"),g={"Content-Type":"application/json"};let u="POST",f=l;if(l&&typeof l=="object"&&("method"in l||"headers"in l)&&!("content"in l)&&!("message"in l)&&!("action"in l)){const m=l;typeof m.method=="string"&&(u=m.method.toUpperCase()),m.headers&&Object.assign(g,m.headers),f=m.body}p&&(g.Authorization=`Bearer ${p}`);let x=typeof d=="string"?d:"";x.startsWith("/api/")||(x.startsWith("/")?x="/api"+x:x="/api/"+x);const y={method:u,headers:g};u!=="GET"&&u!=="HEAD"&&f!==void 0&&(y.body=typeof f=="string"?f:JSON.stringify(f));const E=await fetch(x,y),I=await E.text();let v;try{v=JSON.parse(I)}catch{}c={...v&&typeof v=="object"&&!Array.isArray(v)?v:{},status:E.status,body:v??I,ok:E.ok}}else if(e==="state"){const{action:d,key:l,value:p}=r||{};if(d==="get"){const g=localStorage.getItem("titan:sandbox:"+l);c=g?JSON.parse(g):void 0}else d==="set"&&(localStorage.setItem("titan:sandbox:"+l,JSON.stringify(p)),c={ok:!0})}else e==="canvas"?this.messageHandler?c=await this.messageHandler({type:e,payload:r}):c={ok:!1,error:"Canvas operations not configured"}:e==="import"&&(c={ok:!1,error:"Dynamic imports not supported in sandbox"});i.contentWindow.postMessage({type:"result",id:s,payload:c},"*")}catch(c){i.contentWindow.postMessage({type:"error",id:s,error:c.message||String(c)},"*")}}whenReady(){return this.ready?Promise.resolve():new Promise((e,s)=>{const r=setTimeout(()=>{s(new Error("Sandbox iframe failed to become ready within 30s. React, ReactDOM, or Babel scripts may have failed to load."))},3e4);this.readyQueue.push(()=>{clearTimeout(r),e()})})}post(e,s){return new Promise((r,i)=>{const o=++this.msgId;this.pending.set(o,{resolve:r,reject:i}),this.whenReady().then(()=>{var c,d;(d=(c=this.iframe)==null?void 0:c.contentWindow)==null||d.postMessage({type:e,id:o,payload:s},"*")}).catch(i)})}async render(e,s){await this.post("render",{format:e,source:s})}async execute(e){return this.post("execute",{code:e})}setMessageHandler(e){this.messageHandler=e}destroy(){this.observer&&(this.observer.disconnect(),this.observer=void 0),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.iframe=null,this.pending.clear(),this.readyQueue=[],this.ready=!1,this.messageHandler=void 0}}function wf(t=3e5){const[e,s]=w.useState(null),[r,i]=w.useState(!1),o=w.useCallback(async()=>{i(!0);try{const l=await ge("/api/update");if(l.ok){const p=await l.json();s(p)}}catch{}finally{i(!1)}},[]);w.useEffect(()=>{o();const l=setInterval(o,t);return()=>clearInterval(l)},[o,t]);const c=w.useCallback(async(l=!0)=>{try{return await(await ge("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restart:l})})).json()}catch(p){return{ok:!1,error:p.message}}},[]),d=w.useCallback(async(l,p=3e4)=>{const g=Date.now(),u=1500;for(;Date.now()-g<p;){await new Promise(f=>setTimeout(f,u));try{const f=await ge("/api/update");if(f.ok){const x=await f.json();if(x.current&&x.current!==l)return s(x),x.current}}catch{}}return null},[]);return{info:e,checking:r,triggerUpdate:c,waitForReload:d}}function vf(t){const e=w.useCallback(s=>{const r=s.target;if(!(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))for(const i of t){const o=s.key.toLowerCase()===i.key.toLowerCase(),c=!!i.ctrl===(s.ctrlKey||s.metaKey),d=!!i.shift===s.shiftKey,l=!!i.alt===s.altKey;if(o&&c&&d&&l){s.preventDefault(),i.action();return}}},[t]);w.useEffect(()=>(window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)),[e])}const _f=[{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 kf({open:t,onClose:e}){return t?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:e,children:n.jsxs("div",{className:"bg-zinc-900 border border-zinc-700 rounded-lg p-6 max-w-md w-full shadow-xl",onClick:s=>s.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold text-white mb-4",children:"Keyboard Shortcuts"}),n.jsx("div",{className:"space-y-2",children:_f.map(s=>n.jsxs("div",{className:"flex justify-between text-sm",children:[n.jsx("span",{className:"text-zinc-300",children:s.description}),n.jsx("kbd",{className:"px-2 py-0.5 bg-zinc-800 rounded text-zinc-400 font-mono text-xs",children:s.key})]},s.key+s.description))}),n.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"Press Escape to close"})]})}):null}const Sf={Home:n.jsx(Sl,{className:"w-3.5 h-3.5"}),Brain:n.jsx(yt,{className:"w-3.5 h-3.5"}),Terminal:n.jsx(ro,{className:"w-3.5 h-3.5"}),Network:n.jsx(no,{className:"w-3.5 h-3.5"}),Server:n.jsx(Rr,{className:"w-3.5 h-3.5"}),Wrench:n.jsx(jr,{className:"w-3.5 h-3.5"}),Settings:n.jsx(Sr,{className:"w-3.5 h-3.5"}),FileText:n.jsx(pn,{className:"w-3.5 h-3.5"})};function ll({currentSpaceId:t,onSpaceSelect:e}){const[s,r]=w.useState(!1),[i,o]=w.useState(""),c=ke.list(),d=()=>{if(!i.trim())return;const l=ke.create(i.trim());o(""),e(l.id)};return n.jsxs("div",{className:"bg-[#18181b]/95 backdrop-blur-xl border border-[#27272a]/60 rounded-2xl shadow-2xl shadow-black/40 overflow-hidden min-w-[180px]",children:[n.jsxs("button",{onClick:()=>r(l=>!l),className:"w-full flex items-center justify-between px-3 py-2.5 hover:bg-[#27272a]/40 transition-colors",children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-[#52525b]",children:"Spaces"}),n.jsx(Ol,{className:`w-3.5 h-3.5 text-[#3f3f46] transition-transform ${s?"":"rotate-180"}`})]}),s&&n.jsxs("div",{className:"px-2 pb-2",children:[n.jsx("div",{className:"space-y-0.5",children:c.map(l=>n.jsxs("button",{onClick:()=>e(l.id),className:`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-left text-[11px] transition-colors ${l.id===t?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#71717a] hover:bg-[#27272a]/40 hover:text-[#a1a1aa]"}`,children:[n.jsx("span",{style:{color:l.color||"#52525b"},children:Sf[l.icon||""]||n.jsx("div",{className:"w-3.5 h-3.5 rounded-full",style:{background:l.color||"#52525b"}})}),n.jsx("span",{className:"truncate",children:l.name})]},l.id))}),n.jsxs("div",{className:"mt-2 pt-2 border-t border-[#27272a]/40 flex gap-1.5",children:[n.jsx("input",{value:i,onChange:l=>o(l.target.value),onKeyDown:l=>l.key==="Enter"&&d(),placeholder:"New space...",className:"flex-1 min-w-0 px-2 py-1 rounded-lg bg-[#0a0a0f] border border-[#27272a] text-[11px] text-[#a1a1aa] placeholder:text-[#3f3f46] outline-none focus:border-[#6366f1]/30"}),n.jsx("button",{onClick:d,disabled:!i.trim(),className:"p-1.5 rounded-lg bg-[#6366f1]/10 border border-[#6366f1]/20 text-[#818cf8] hover:bg-[#6366f1]/20 disabled:opacity-30 transition-colors",children:n.jsx(Pl,{className:"w-3.5 h-3.5"})})]})]})]})}const wr=["_____javascript","_____react","_____tool","_____widget","_____canvas","_____framework","_____transient"];function cl(t,e){let s=e;for(;s>0&&t[s-1]!==`
343
- `&&t[s-1]!=="\r";)s--;return s}function dl(t,e){let s=e;for(;s<t.length&&t[s]!==`
344
- `&&t[s]!=="\r";)s++;return s}function vr(t,e,s){const r=cl(t,e),i=dl(t,e+s.length);return!t.slice(r,e).trim()&&!t.slice(e+s.length,i).trim()}function jf(t){return t.replace(/\n_+\s*$/g,"").trimEnd()}function Ef(t){const e=t.trim();if(!e)return null;if(e.startsWith("{"))try{return JSON.parse(e)}catch{return null}return{format:"react",source:e}}function ul(t){if(t.gate==="_____react")return{type:"render_widget",widget:{format:"react",source:t.code.trim()}};if(t.gate==="_____javascript")return{type:"run_javascript",code:t.code};if(t.gate==="_____tool")try{return{type:"tool_request",payload:JSON.parse(t.code)}}catch{return}if(t.gate==="_____widget"){const e=Ef(t.code);if(typeof(e==null?void 0:e.source)!="string"||!e.source.trim())return;if(typeof e.id=="string"&&e.id.trim()){const{id:s,...r}=e;return{type:"update_widget",widgetId:s,patch:r}}return{type:"render_widget",widget:{...e,source:e.source}}}}function Nf(t){const e=t.trim();if(!e)return[];try{const s=JSON.parse(e);return Array.isArray(s)?s.filter(r=>r&&typeof r=="object"&&typeof r.action=="string"):[]}catch{return[]}}function Cf(t){const e=[];let s=0;for(;s<t.length;){let r=null,i=-1;for(const u of wr){const f=t.indexOf(u,s);f!==-1&&(i===-1||f<i)&&vr(t,f,u)&&(i=f,r=u)}if(!r||i===-1)break;if(r==="_____framework"||r==="_____transient"){s=i+r.length;continue}const o=cl(t,i);let d=dl(t,i+r.length);t.startsWith(`\r
342
+ </html>`;class ll{constructor(e,s){$e(this,"iframe",null);$e(this,"pending",new Map);$e(this,"msgId",0);$e(this,"ready",!1);$e(this,"readyQueue",[]);$e(this,"onLog");$e(this,"messageHandler");$e(this,"messageListener");$e(this,"observer");this.iframe=e,this.onLog=s==null?void 0:s.onLog,this.init()}init(){const e=this.iframe;wf().then(i=>{!this.iframe||!document.contains(e)||(e.srcdoc=vf(i))}).catch(i=>{console.error("[sandbox] vendor scripts failed to load",i);for(const[o,c]of this.pending)c.reject(new Error("Sandbox boot failed: "+i.message)),this.pending.delete(o)});const s=i=>{const o=i.data;if(!(!o||typeof o!="object"||!o.type||typeof o.type!="string"||!["ready","rendered","error","result","fetch","api","state","canvas","log","import"].includes(o.type))){if((o==null?void 0:o.type)==="ready"){this.ready=!0,this.readyQueue.forEach(d=>d()),this.readyQueue=[];return}if(typeof(o==null?void 0:o.id)=="number"&&this.pending.has(o.id)){const d=this.pending.get(o.id);this.pending.delete(o.id),o.type==="error"?d.reject(new Error(o.error||"Sandbox error")):d.resolve(o.payload);return}if((o==null?void 0:o.type)==="fetch"||(o==null?void 0:o.type)==="api"||(o==null?void 0:o.type)==="state"||(o==null?void 0:o.type)==="canvas"||(o==null?void 0:o.type)==="log"||(o==null?void 0:o.type)==="import"){this.handleIframeRequest(o.type,o.id,o.payload);return}}};this.messageListener=s,window.addEventListener("message",s);const r=new MutationObserver(()=>{document.contains(e)||this.destroy()});this.observer=r,e.parentNode&&r.observe(e.parentNode,{childList:!0,subtree:!0})}async handleIframeRequest(e,s,r){var o;const i=this.iframe;if(i!=null&&i.contentWindow)try{let c;if(e==="log")(o=this.onLog)==null||o.call(this,(r==null?void 0:r.args)||[]),c={ok:!0};else if(e==="fetch"){const{url:d,options:l}=r||{},p=localStorage.getItem("titan-token"),g={...(l==null?void 0:l.headers)||{}};let u=!1;try{typeof d=="string"&&(d.startsWith("/")?u=!0:u=new URL(d,window.location.href).origin===window.location.origin)}catch{}p&&u&&(g.Authorization=`Bearer ${p}`);const f=await fetch(d,{...l,headers:g}),x=await f.text();let y;try{y=JSON.parse(x)}catch{}c={ok:f.ok,status:f.status,text:x,json:y}}else if(e==="api"){const{endpoint:d,body:l}=r||{},p=localStorage.getItem("titan-token"),g={"Content-Type":"application/json"};let u="POST",f=l;if(l&&typeof l=="object"&&("method"in l||"headers"in l)&&!("content"in l)&&!("message"in l)&&!("action"in l)){const m=l;typeof m.method=="string"&&(u=m.method.toUpperCase()),m.headers&&Object.assign(g,m.headers),f=m.body}p&&(g.Authorization=`Bearer ${p}`);let x=typeof d=="string"?d:"";x.startsWith("/api/")||(x.startsWith("/")?x="/api"+x:x="/api/"+x);const y={method:u,headers:g};u!=="GET"&&u!=="HEAD"&&f!==void 0&&(y.body=typeof f=="string"?f:JSON.stringify(f));const E=await fetch(x,y),L=await E.text();let v;try{v=JSON.parse(L)}catch{}c={...v&&typeof v=="object"&&!Array.isArray(v)?v:{},status:E.status,body:v??L,ok:E.ok}}else if(e==="state"){const{action:d,key:l,value:p}=r||{};if(d==="get"){const g=localStorage.getItem("titan:sandbox:"+l);c=g?JSON.parse(g):void 0}else d==="set"&&(localStorage.setItem("titan:sandbox:"+l,JSON.stringify(p)),c={ok:!0})}else e==="canvas"?this.messageHandler?c=await this.messageHandler({type:e,payload:r}):c={ok:!1,error:"Canvas operations not configured"}:e==="import"&&(c={ok:!1,error:"Dynamic imports not supported in sandbox"});i.contentWindow.postMessage({type:"result",id:s,payload:c},"*")}catch(c){i.contentWindow.postMessage({type:"error",id:s,error:c.message||String(c)},"*")}}whenReady(){return this.ready?Promise.resolve():new Promise((e,s)=>{const r=setTimeout(()=>{s(new Error("Sandbox iframe failed to become ready within 30s. React, ReactDOM, or Babel scripts may have failed to load."))},3e4);this.readyQueue.push(()=>{clearTimeout(r),e()})})}post(e,s){return new Promise((r,i)=>{const o=++this.msgId;this.pending.set(o,{resolve:r,reject:i}),this.whenReady().then(()=>{var c,d;(d=(c=this.iframe)==null?void 0:c.contentWindow)==null||d.postMessage({type:e,id:o,payload:s},"*")}).catch(i)})}async render(e,s){await this.post("render",{format:e,source:s})}async execute(e){return this.post("execute",{code:e})}setMessageHandler(e){this.messageHandler=e}destroy(){this.observer&&(this.observer.disconnect(),this.observer=void 0),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.iframe=null,this.pending.clear(),this.readyQueue=[],this.ready=!1,this.messageHandler=void 0}}function kf(t=3e5){const[e,s]=w.useState(null),[r,i]=w.useState(!1),o=w.useCallback(async()=>{i(!0);try{const l=await ge("/api/update");if(l.ok){const p=await l.json();s(p)}}catch{}finally{i(!1)}},[]);w.useEffect(()=>{o();const l=setInterval(o,t);return()=>clearInterval(l)},[o,t]);const c=w.useCallback(async(l=!0)=>{try{return await(await ge("/api/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restart:l})})).json()}catch(p){return{ok:!1,error:p.message}}},[]),d=w.useCallback(async(l,p=3e4)=>{const g=Date.now(),u=1500;for(;Date.now()-g<p;){await new Promise(f=>setTimeout(f,u));try{const f=await ge("/api/update");if(f.ok){const x=await f.json();if(x.current&&x.current!==l)return s(x),x.current}}catch{}}return null},[]);return{info:e,checking:r,triggerUpdate:c,waitForReload:d}}function Sf(t){const e=w.useCallback(s=>{const r=s.target;if(!(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))for(const i of t){const o=s.key.toLowerCase()===i.key.toLowerCase(),c=!!i.ctrl===(s.ctrlKey||s.metaKey),d=!!i.shift===s.shiftKey,l=!!i.alt===s.altKey;if(o&&c&&d&&l){s.preventDefault(),i.action();return}}},[t]);w.useEffect(()=>(window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)),[e])}const jf=[{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 Ef({open:t,onClose:e}){return t?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:e,children:n.jsxs("div",{className:"bg-zinc-900 border border-zinc-700 rounded-lg p-6 max-w-md w-full shadow-xl",onClick:s=>s.stopPropagation(),children:[n.jsx("h2",{className:"text-lg font-semibold text-white mb-4",children:"Keyboard Shortcuts"}),n.jsx("div",{className:"space-y-2",children:jf.map(s=>n.jsxs("div",{className:"flex justify-between text-sm",children:[n.jsx("span",{className:"text-zinc-300",children:s.description}),n.jsx("kbd",{className:"px-2 py-0.5 bg-zinc-800 rounded text-zinc-400 font-mono text-xs",children:s.key})]},s.key+s.description))}),n.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"Press Escape to close"})]})}):null}const Nf={Home:n.jsx(Nl,{className:"w-3.5 h-3.5"}),Brain:n.jsx(yt,{className:"w-3.5 h-3.5"}),Terminal:n.jsx(io,{className:"w-3.5 h-3.5"}),Network:n.jsx(ro,{className:"w-3.5 h-3.5"}),Server:n.jsx(Rr,{className:"w-3.5 h-3.5"}),Wrench:n.jsx(jr,{className:"w-3.5 h-3.5"}),Settings:n.jsx(Sr,{className:"w-3.5 h-3.5"}),FileText:n.jsx(pn,{className:"w-3.5 h-3.5"})};function cl({currentSpaceId:t,onSpaceSelect:e}){const[s,r]=w.useState(!1),[i,o]=w.useState(""),c=ke.list(),d=()=>{if(!i.trim())return;const l=ke.create(i.trim());o(""),e(l.id)};return n.jsxs("div",{className:"bg-[#18181b]/95 backdrop-blur-xl border border-[#27272a]/60 rounded-2xl shadow-2xl shadow-black/40 overflow-hidden min-w-[180px]",children:[n.jsxs("button",{onClick:()=>r(l=>!l),className:"w-full flex items-center justify-between px-3 py-2.5 hover:bg-[#27272a]/40 transition-colors",children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-[#52525b]",children:"Spaces"}),n.jsx(Bl,{className:`w-3.5 h-3.5 text-[#3f3f46] transition-transform ${s?"":"rotate-180"}`})]}),s&&n.jsxs("div",{className:"px-2 pb-2",children:[n.jsx("div",{className:"space-y-0.5",children:c.map(l=>n.jsxs("button",{onClick:()=>e(l.id),className:`w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg text-left text-[11px] transition-colors ${l.id===t?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#71717a] hover:bg-[#27272a]/40 hover:text-[#a1a1aa]"}`,children:[n.jsx("span",{style:{color:l.color||"#52525b"},children:Nf[l.icon||""]||n.jsx("div",{className:"w-3.5 h-3.5 rounded-full",style:{background:l.color||"#52525b"}})}),n.jsx("span",{className:"truncate",children:l.name})]},l.id))}),n.jsxs("div",{className:"mt-2 pt-2 border-t border-[#27272a]/40 flex gap-1.5",children:[n.jsx("input",{value:i,onChange:l=>o(l.target.value),onKeyDown:l=>l.key==="Enter"&&d(),placeholder:"New space...",className:"flex-1 min-w-0 px-2 py-1 rounded-lg bg-[#0a0a0f] border border-[#27272a] text-[11px] text-[#a1a1aa] placeholder:text-[#3f3f46] outline-none focus:border-[#6366f1]/30"}),n.jsx("button",{onClick:d,disabled:!i.trim(),className:"p-1.5 rounded-lg bg-[#6366f1]/10 border border-[#6366f1]/20 text-[#818cf8] hover:bg-[#6366f1]/20 disabled:opacity-30 transition-colors",children:n.jsx(Ul,{className:"w-3.5 h-3.5"})})]})]})]})}const wr=["_____javascript","_____react","_____tool","_____widget","_____canvas","_____framework","_____transient"];function dl(t,e){let s=e;for(;s>0&&t[s-1]!==`
343
+ `&&t[s-1]!=="\r";)s--;return s}function ul(t,e){let s=e;for(;s<t.length&&t[s]!==`
344
+ `&&t[s]!=="\r";)s++;return s}function vr(t,e,s){const r=dl(t,e),i=ul(t,e+s.length);return!t.slice(r,e).trim()&&!t.slice(e+s.length,i).trim()}function Cf(t){return t.replace(/\n_+\s*$/g,"").trimEnd()}function Tf(t){const e=t.trim();if(!e)return null;if(e.startsWith("{"))try{return JSON.parse(e)}catch{return null}return{format:"react",source:e}}function hl(t){if(t.gate==="_____react")return{type:"render_widget",widget:{format:"react",source:t.code.trim()}};if(t.gate==="_____javascript")return{type:"run_javascript",code:t.code};if(t.gate==="_____tool")try{return{type:"tool_request",payload:JSON.parse(t.code)}}catch{return}if(t.gate==="_____widget"){const e=Tf(t.code);if(typeof(e==null?void 0:e.source)!="string"||!e.source.trim())return;if(typeof e.id=="string"&&e.id.trim()){const{id:s,...r}=e;return{type:"update_widget",widgetId:s,patch:r}}return{type:"render_widget",widget:{...e,source:e.source}}}}function Rf(t){const e=t.trim();if(!e)return[];try{const s=JSON.parse(e);return Array.isArray(s)?s.filter(r=>r&&typeof r=="object"&&typeof r.action=="string"):[]}catch{return[]}}function Af(t){const e=[];let s=0;for(;s<t.length;){let r=null,i=-1;for(const u of wr){const f=t.indexOf(u,s);f!==-1&&(i===-1||f<i)&&vr(t,f,u)&&(i=f,r=u)}if(!r||i===-1)break;if(r==="_____framework"||r==="_____transient"){s=i+r.length;continue}const o=dl(t,i);let d=ul(t,i+r.length);t.startsWith(`\r
345
345
  `,d)?d+=2:(t[d]===`
346
- `||t[d]==="\r")&&(d+=1);let l=t.length;for(const u of wr){const f=t.indexOf(u,d);f!==-1&&f<l&&vr(t,f,u)&&(l=f)}let p=t.slice(d,l).trimEnd();p=jf(p);const g={gate:r,code:p,leadingText:t.slice(s,o).trim()};g.action=ul(g),e.push(g),s=l}return e.length===0&&t.trim()&&e.push({gate:"_____transient",code:"",leadingText:t.trim()}),e}function Tf(t){return t.map(e=>{const s=[];return s.push(`execution ${e.status}`),e.logs.forEach(r=>s.push(`${r.level}: ${r.text}`)),e.result!==void 0&&e.result!==null&&s.push(`result: ${e.resultText}`),e.error&&s.push(`error: ${e.error.text}`),s.join(`
346
+ `||t[d]==="\r")&&(d+=1);let l=t.length;for(const u of wr){const f=t.indexOf(u,d);f!==-1&&f<l&&vr(t,f,u)&&(l=f)}let p=t.slice(d,l).trimEnd();p=Cf(p);const g={gate:r,code:p,leadingText:t.slice(s,o).trim()};g.action=hl(g),e.push(g),s=l}return e.length===0&&t.trim()&&e.push({gate:"_____transient",code:"",leadingText:t.trim()}),e}function Lf(t){return t.map(e=>{const s=[];return s.push(`execution ${e.status}`),e.logs.forEach(r=>s.push(`${r.level}: ${r.text}`)),e.result!==void 0&&e.result!==null&&s.push(`result: ${e.resultText}`),e.error&&s.push(`error: ${e.error.text}`),s.join(`
347
347
  `)}).join(`
348
348
 
349
- `)}function Rf(t){return{role:"framework",content:Tf(t),timestamp:Date.now(),executions:t}}function Af(t,e){let s=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)vr(t,r,e)&&s++,r+=e.length;return s}function Lf(t){const s=wr.filter(r=>r!=="_____framework"&&r!=="_____transient").map(r=>({gate:r,count:Af(t,r)})).find(r=>r.count>1);return s?{valid:!1,error:`Execution messages may contain ${s.gate} at most once, and it must appear on its own line.`}:{valid:!0}}function Gs(t,e,s){if(!t||t.length===0)return{x:0,y:0};const i=Math.max(...t.map(o=>o.y+o.h),0);for(let o=0;o<=i+s;o++)for(let c=0;c<=12-e;c++)if(!t.some(l=>c<l.x+l.w&&c+e>l.x&&o<l.y+l.h&&o+s>l.y))return{x:c,y:o};return{x:0,y:i+s}}function If(t){const e=t.widgets||[],s=e.length>0?e.map(l=>{const p=l.source?l.source.slice(0,150).replace(/\n/g," ").replace(/\s+/g," ").trim():"(no source)";return`- ${l.name} (id: ${l.id}, format: ${l.format}, ${l.w}x${l.h}) — "${p}…"`}).join(`
349
+ `)}function If(t){return{role:"framework",content:Lf(t),timestamp:Date.now(),executions:t}}function Df(t,e){let s=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)vr(t,r,e)&&s++,r+=e.length;return s}function Mf(t){const s=wr.filter(r=>r!=="_____framework"&&r!=="_____transient").map(r=>({gate:r,count:Df(t,r)})).find(r=>r.count>1);return s?{valid:!1,error:`Execution messages may contain ${s.gate} at most once, and it must appear on its own line.`}:{valid:!0}}function Gs(t,e,s){if(!t||t.length===0)return{x:0,y:0};const i=Math.max(...t.map(o=>o.y+o.h),0);for(let o=0;o<=i+s;o++)for(let c=0;c<=12-e;c++)if(!t.some(l=>c<l.x+l.w&&c+e>l.x&&o<l.y+l.h&&o+s>l.y))return{x:c,y:o};return{x:0,y:i+s}}function Of(t){const e=t.widgets||[],s=e.length>0?e.map(l=>{const p=l.source?l.source.slice(0,150).replace(/\n/g," ").replace(/\s+/g," ").trim():"(no source)";return`- ${l.name} (id: ${l.id}, format: ${l.format}, ${l.w}x${l.h}) — "${p}…"`}).join(`
350
350
  `):"(none yet — the canvas is empty)",r=new Date,i=Intl.DateTimeFormat().resolvedOptions().timeZone,o=typeof window<"u"?window.location.href:"",c=typeof window<"u"?window.location.pathname:"",d=e.length>0?`${e.length} widget${e.length===1?"":"s"} on canvas (system: ${e.filter(l=>l.format==="system").length}, generated: ${e.filter(l=>l.format!=="system").length})`:"canvas is empty";return`BASE LAW — These rules override all other instructions:
351
351
  1. The user is NOT technical. They do NOT know about React, widgets, gates, or code. NEVER use technical jargon in responses.
352
352
  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.
@@ -762,8 +762,8 @@ REMINDER — BASE LAW:
762
762
  2. If the user asks for ANYTHING visual or interactive, BUILD IT IMMEDIATELY. Do not ask permission.
763
763
  3. USE AN EXECUTION GATE for all browser work.
764
764
  4. One staging sentence, then the gate.
765
- 5. Update existing widgets by id — never create duplicates.`}function hl({space:t,onClose:e,onMascotState:s}){const[r,i]=w.useState([]),[o,c]=w.useState(""),[d,l]=w.useState(!1),[p,g]=w.useState([]),u=8,[f,x]=w.useState(null),y=w.useRef(null),E=w.useRef(null),I=w.useRef(null),v=w.useRef(null),A=w.useRef(t);w.useEffect(()=>{A.current=t},[t]);const m=w.useCallback(j=>{const R=A.current;if(j.type==="render_widget"){const P=j.widget,B=Number.isFinite(P.w)?Number(P.w):4,z=Number.isFinite(P.h)?Number(P.h):4,q=Number.isFinite(P.x)&&Number.isFinite(P.y)?{x:Number(P.x),y:Number(P.y)}:Gs(R.widgets||[],B,z),H=ke.addWidget(R.id,{name:P.name||"Widget",format:P.format||"react",source:P.source,x:q.x,y:q.y,w:B,h:z});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),H.id}return j.type==="update_widget"?(ke.updateWidget(R.id,j.widgetId,j.patch||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),j.widgetId):j.type==="remove_widget"?(ke.removeWidget(R.id,j.widgetId),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),j.widgetId):j.type==="set_runtime_state"?(localStorage.setItem(`titan:runtime:${R.id}:${j.key}`,JSON.stringify(j.value)),j.key):j.type==="emit_event"?(window.dispatchEvent(new CustomEvent(j.eventName,{detail:j.detail})),j.eventName):null},[]),k=w.useCallback(j=>{var R,P;m({type:"render_widget",widget:{name:j.templateName,format:j.format,source:j.source,w:((R=j.defaultSize)==null?void 0:R.w)??4,h:((P=j.defaultSize)==null?void 0:P.h)??4}})},[m]);w.useEffect(()=>{var j;(j=y.current)==null||j.scrollIntoView({behavior:"smooth"})},[r]),w.useEffect(()=>{const j=P=>{var z;const B=(z=P.detail)==null?void 0:z.text;typeof B=="string"&&T(B)},R=P=>{const B=P.detail;B!=null&&B.source&&k(B)};return window.addEventListener("titan:chat:prompt",j),window.addEventListener("titan:gallery:run-template",R),()=>{window.removeEventListener("titan:chat:prompt",j),window.removeEventListener("titan:gallery:run-template",R)}},[k]),w.useEffect(()=>{if(!I.current||v.current)return;const j=new al(I.current,{onLog:R=>console.log("[Sandbox]",R)});return j.setMessageHandler(R=>{var B,z,q,H;const P=A.current;if(R.type==="canvas"&&((B=R.payload)==null?void 0:B.action)==="createWidget"){const J=R.payload.def;if(!J)return{ok:!1,error:"createWidget requires a `def` object"};const $=Number.isFinite(J.w)?J.w:4,F=Number.isFinite(J.h)?J.h:4,V=Number.isFinite(J.x)&&Number.isFinite(J.y)?{x:J.x,y:J.y}:Gs(P.widgets||[],$,F);try{const se=ke.addWidget(P.id,{name:J.name||"Agent Widget",format:J.format||"react",source:J.source||"",x:V.x,y:V.y,w:$,h:F});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0,widgetId:se.id}}catch(se){return{ok:!1,error:se.message}}}if(R.type==="canvas"&&((z=R.payload)==null?void 0:z.action)==="updateWidget"){const{id:J,patch:$}=R.payload;return J?(ke.updateWidget(P.id,J,$||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0,id:J}):{ok:!1,error:"updateWidget requires an `id`"}}if(R.type==="canvas"&&((q=R.payload)==null?void 0:q.action)==="listWidgets")return{ok:!0,widgets:P.widgets||[]};if(R.type==="canvas"&&((H=R.payload)==null?void 0:H.action)==="removeWidget"){const J=R.payload.id;return J?(ke.removeWidget(P.id,J),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}}),v.current=j,()=>{j.destroy(),v.current=null}},[]);const _=w.useCallback(async(j,R)=>{const P=v.current;if(!P)return{status:"error",logs:[{level:"error",text:"Sandbox not ready"}],resultText:"",runId:Date.now(),error:{message:"Sandbox not ready",name:"SandboxError",stack:"",text:"Sandbox not ready"}};if(j==="_____javascript")try{const B=await P.execute(R);return{status:B.status==="success"?"success":"error",logs:B.logs||[],result:B.result,resultText:B.resultText||String(B.result??""),runId:Date.now(),error:B.error?{message:B.error.message||String(B.error),name:"ExecutionError",stack:"",text:String(B.error)}:void 0}}catch(B){return{status:"error",logs:[{level:"error",text:B.message||String(B)}],resultText:"",runId:Date.now(),error:{message:B.message||String(B),name:"ExecutionError",stack:"",text:String(B)}}}if(j==="_____react"){let B=4,z=4;const q=R.match(/\/\/\s*__WIDGET_META__\s+w=(\d+)\s+h=(\d+)/);q&&(B=parseInt(q[1],10)||4,z=parseInt(q[2],10)||4);try{const H=m({type:"render_widget",widget:{name:"React Widget",format:"react",source:R,w:B,h:z}});return{status:"success",logs:[{level:"info",text:`Created widget ${H}`}],result:{widgetId:H},resultText:`Created widget ${H}`,runId:Date.now()}}catch(H){return{status:"error",logs:[{level:"error",text:H.message||String(H)}],resultText:"",runId:Date.now(),error:{message:H.message||String(H),name:"WidgetError",stack:"",text:String(H)}}}}if(j==="_____widget"){const B=ul({gate:"_____widget",code:R,leadingText:""});if(!B)return{status:"error",logs:[{level:"error",text:"Invalid widget payload"}],resultText:"",runId:Date.now(),error:{message:"Invalid widget payload",name:"WidgetError",stack:"",text:"Invalid widget payload"}};try{const z=m(B),q=B.type==="update_widget"?"Updated":"Created";return{status:"success",logs:[{level:"info",text:`${q} widget ${z}`}],result:z?{widgetId:z}:void 0,resultText:`${q} widget ${z??""}`.trim(),runId:Date.now()}}catch(z){return{status:"error",logs:[{level:"error",text:z.message||String(z)}],resultText:"",runId:Date.now(),error:{message:z.message||String(z),name:"WidgetError",stack:"",text:String(z)}}}}if(j==="_____canvas"){const B=Nf(R);if(B.length===0)return{status:"error",logs:[{level:"error",text:"Empty or invalid _____canvas payload (expected JSON array of {action, ...})"}],resultText:"",runId:Date.now(),error:{message:"Invalid canvas payload",name:"CanvasFenceError",stack:"",text:"Empty or invalid _____canvas payload"}};const z=[],q=[];for(const J of B)try{if(J.action==="create_widget"){if(!J.source){q.push("create_widget: missing source");continue}const $=m({type:"render_widget",widget:{name:J.name||"Widget",title:J.title,format:J.format||"react",source:J.source,w:J.w,h:J.h,x:J.x,y:J.y,metadata:J.metadata}});z.push(`created ${$}`)}else if(J.action==="update_widget"){if(!J.id){q.push("update_widget: missing id");continue}const $=J.patch??{};m({type:"update_widget",widgetId:J.id,patch:$}),z.push(`updated ${J.id}`)}else if(J.action==="remove_widget"){if(!J.id){q.push("remove_widget: missing id");continue}m({type:"remove_widget",widgetId:J.id}),z.push(`removed ${J.id}`)}else q.push(`unknown action: ${String(J.action)}`)}catch($){q.push($.message||String($))}const H=q.length===0?"success":z.length===0?"error":"success";return{status:H,logs:[...z.map(J=>({level:"info",text:J})),...q.map(J=>({level:"error",text:J}))],resultText:z.length?z.join("; "):"No actions applied",runId:Date.now(),...H==="error"?{error:{message:q.join("; "),name:"CanvasFenceError",stack:"",text:q.join("; ")}}:{}}}return j==="_____tool"?{status:"error",logs:[{level:"error",text:"_____tool gate not supported in Canvas chat"}],resultText:"",runId:Date.now(),error:{message:"_____tool gate not supported",name:"NotSupported",stack:"",text:"_____tool gate not supported in Canvas chat"}}:{status:"error",logs:[{level:"error",text:`Unknown gate: ${j}`}],resultText:"",runId:Date.now(),error:{message:`Unknown gate: ${j}`,name:"UnknownGate",stack:"",text:`Unknown gate: ${j}`}}},[]),T=w.useCallback(async j=>{var q;const R=j.trim();if(!R)return;if(d){g(H=>H.length>=u?H:[...H,R]),c("");return}const P={role:"user",content:R,timestamp:Date.now()};i(H=>[...H,P]),c(""),l(!0),x(null),s==null||s("thinking");const B=new AbortController;E.current=B;let z="";try{const H=If(A.current),J=`canvas-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await jl(R,J,V=>{if(V.type==="token")z+=V.data,i(se=>{const Y=se[se.length-1];return Y&&Y.role==="assistant"?[...se.slice(0,-1),{...Y,content:z}]:[...se,{role:"assistant",content:z,timestamp:Date.now()}]});else if(V.type==="widget"){const se=V.widgetMode||"create",Y=V.widget||{},te=A.current;try{if(se==="remove"&&Y.id)ke.removeWidget(te.id,Y.id);else if(se==="update"&&Y.id){const Q={};typeof Y.name=="string"&&Y.name&&(Q.name=Y.name),typeof Y.title=="string"&&(Q.title=Y.title),typeof Y.source=="string"&&Y.source&&(Q.source=Y.source),typeof Y.format=="string"&&(Q.format=Y.format),typeof Y.w=="number"&&(Q.w=Y.w),typeof Y.h=="number"&&(Q.h=Y.h),ke.updateWidget(te.id,Y.id,Q)}else if(Y.source){const Q=typeof Y.w=="number"?Y.w:4,be=typeof Y.h=="number"?Y.h:4,Ce=typeof Y.x=="number"&&typeof Y.y=="number"?{x:Y.x,y:Y.y}:Gs(te.widgets||[],Q,be);ke.addWidget(te.id,{name:Y.name||"Widget",title:Y.title,format:Y.format||"react",source:Y.source,x:Ce.x,y:Ce.y,w:Q,h:be,metadata:Y.metadata})}window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:te.id}}))}catch(Q){console.error("[ChatWidget] widget side-channel handler failed",Q)}}else if(V.type==="done"){const se=V.data||z;z=se,i(Y=>{const te=Y[Y.length-1];return te&&te.role==="assistant"?[...Y.slice(0,-1),{...te,content:se}]:[...Y,{role:"assistant",content:se,timestamp:Date.now()}]})}else V.type==="error"&&x(V.data)},B.signal,{systemPromptAppendix:H});const F=Cf(z).filter(V=>V.gate!=="_____transient"&&V.gate!=="_____framework");if(F.length>0){s==null||s("executing");const V=[];for(const te of F){const Q=Lf(`${te.gate}
766
- ${te.code}`);if(!Q.valid){V.push({status:"error",logs:[{level:"error",text:Q.error||"Invalid execution"}],resultText:"",runId:Date.now(),error:{message:Q.error||"Invalid execution",name:"ValidationError",stack:"",text:Q.error||""}});continue}const be=await _(te.gate,te.code);V.push(be)}const se=Rf(V);i(te=>[...te,se]);const Y=V.find(te=>te.status==="error");Y&&x(((q=Y.error)==null?void 0:q.text)||"Execution failed")}}catch(H){H.name!=="AbortError"&&x(H.message||"Request failed")}finally{l(!1),E.current=null,s==null||s("idle")}},[d,s,_]),S=w.useCallback(()=>{var j;(j=E.current)==null||j.abort(),E.current=null,l(!1),g([]),s==null||s("idle")},[s]);w.useEffect(()=>{if(d||p.length===0)return;const[j,...R]=p;g(R),T(j)},[d,p,T]);const C=w.useCallback(j=>{g(R=>R.filter((P,B)=>B!==j))},[]),D=w.useCallback(j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),T(o))},[o,T]);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:[n.jsx("iframe",{ref:I,style:{position:"absolute",width:0,height:0,border:0,visibility:"hidden"},sandbox:"allow-scripts"}),n.jsxs("div",{style:{flex:1,overflowY:"auto",padding:12},children:[r.map((j,R)=>n.jsxs("div",{style:{marginBottom:8,padding:8,borderRadius:8,background:j.role==="user"?"rgba(59,130,246,0.15)":j.role==="framework"?"rgba(245,158,11,0.1)":"rgba(255,255,255,0.05)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[n.jsx("div",{style:{fontSize:10,opacity:.6,marginBottom:4,textTransform:"uppercase"},children:j.role}),n.jsx("div",{style:{fontSize:13,lineHeight:1.5},children:j.content}),j.executions&&j.executions.length>0&&n.jsx("div",{style:{marginTop:4,fontSize:11,opacity:.7},children:j.executions.map((P,B)=>n.jsxs("span",{style:{marginRight:8},children:[P.status==="success"?"✓":"✗"," execution ",B+1]},B))})]},R)),d&&n.jsx("div",{style:{fontSize:12,opacity:.5,padding:8},children:"Thinking…"}),f&&n.jsx("div",{style:{color:"#ef4444",fontSize:12,padding:8,background:"rgba(239,68,68,0.1)",borderRadius:6},children:f}),n.jsx("div",{ref:y})]}),p.length>0&&n.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid rgba(255,255,255,0.08)",display:"flex",flexWrap:"wrap",gap:6,background:"rgba(99,102,241,0.06)"},children:[n.jsxs("span",{style:{fontSize:10,opacity:.7,alignSelf:"center",textTransform:"uppercase",letterSpacing:.5},children:["Queued (",p.length,")"]}),p.map((j,R)=>n.jsxs("span",{title:j,style:{fontSize:11,padding:"3px 8px",background:"rgba(99,102,241,0.18)",border:"1px solid rgba(99,102,241,0.4)",borderRadius:999,color:"#e0e7ff",display:"inline-flex",alignItems:"center",gap:6,maxWidth:220},children:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j}),n.jsx("button",{onClick:()=>C(R),title:"Remove from queue",style:{border:"none",background:"transparent",color:"#c7d2fe",cursor:"pointer",padding:0,fontSize:12,lineHeight:1},children:"×"})]},R))]}),n.jsxs("div",{style:{padding:12,borderTop:"1px solid rgba(255,255,255,0.08)",display:"flex",gap:8},children:[n.jsx("input",{type:"text",value:o,onChange:j=>c(j.target.value),onKeyDown:D,placeholder:d?p.length>=u?`Queue full (${u}) — wait for TITAN to catch up…`:"TITAN is thinking — type to steer or queue a follow-up…":"Ask TITAN to create an agent, run a task, or build a widget…",style:{flex:1,background:"rgba(255,255,255,0.06)",border:d?"1px solid rgba(99,102,241,0.4)":"1px solid rgba(255,255,255,0.1)",borderRadius:8,padding:"8px 12px",color:"#fff",fontSize:13,outline:"none"}}),d?n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>T(o),disabled:!o.trim()||p.length>=u,title:"Queue this message for after the current turn",style:{padding:"8px 14px",borderRadius:8,border:"none",background:o.trim()&&p.length<u?"#6366f1":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:o.trim()&&p.length<u?"pointer":"not-allowed"},children:"Queue"}),n.jsx("button",{onClick:S,title:"Stop the current turn and clear the queue",style:{padding:"8px 14px",borderRadius:8,border:"none",background:"#ef4444",color:"#fff",fontSize:13,cursor:"pointer"},children:"Stop"})]}):n.jsx("button",{onClick:()=>T(o),disabled:!o.trim(),style:{padding:"8px 14px",borderRadius:8,border:"none",background:o.trim()?"#3b82f6":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:o.trim()?"pointer":"not-allowed"},children:"Send"})]})]})}const $i={idle:{eye:"#c4a35a",glow:"#f3d27a",ring:"#a47a3a",body:"#3a2410"},thinking:{eye:"#d4b06a",glow:"#e7c68a",ring:"#b4863a",body:"#3a2410"},executing:{eye:"#d4a040",glow:"#f0c060",ring:"#a47a3a",body:"#3a2410"},listening:{eye:"#8ab8c4",glow:"#a8c8d8",ring:"#6a8a98",body:"#2a2010"},error:{eye:"#c45a30",glow:"#e08050",ring:"#a04a20",body:"#3a1810"}},Z={brassDark:"#7a5a2a",brassMid:"#b8902f",brassBright:"#e8c478",brassHi:"#f7e3a8",woodDark:"#3a2412",woodMid:"#5a3818",glassDark:"#0e1612",glassMid:"#1c2820",steam:"#e6d8b8",bolt:"#2a1808"},Df=9e4;function Mf({state:t="idle",mood:e="neutral",size:s=116,quip:r=null,bubblePhase:i=null,followCursor:o=!0,somaActive:c=!1,somaPoll:d=!0,sleepAfterMs:l=Df,className:p="",onClick:g,edgeRotate:u=0,faceFlip:f=!1,edgeHidden:x=!1}){const[y,E]=w.useState(null),I=y??e,v=$i[t]??$i.idle,[A,m]=w.useState({x:0,y:0}),[k,_]=w.useState(!1),[T,S]=w.useState(!1),[C,D]=w.useState(!1),[j,R]=w.useState(!1),[P,B]=w.useState(0),[z,q]=w.useState(!1),[H,J]=w.useState(!1),$=w.useRef(null),F=w.useRef(Date.now());w.useEffect(()=>{const ce=window.matchMedia("(prefers-reduced-motion: reduce)");J(ce.matches);const ye=xe=>J(xe.matches);return ce.addEventListener("change",ye),()=>ce.removeEventListener("change",ye)},[]),w.useEffect(()=>{F.current=Date.now(),t!=="idle"&&(D(!1),S(!1))},[t]),w.useEffect(()=>{const ce=()=>{F.current=Date.now()};return window.addEventListener("mousemove",ce,{passive:!0}),window.addEventListener("keydown",ce,{passive:!0}),window.addEventListener("click",ce,{passive:!0}),()=>{window.removeEventListener("mousemove",ce),window.removeEventListener("keydown",ce),window.removeEventListener("click",ce)}},[]),w.useEffect(()=>{if(t==="error"||C){_(!1);return}let ce=!1,ye=null;const xe=()=>{if(ce)return;const ve=2500+Math.random()*4e3;setTimeout(()=>{ce||(_(!0),ye=window.setTimeout(()=>{ye=null,ce||_(!1)},140),xe())},ve)};return xe(),()=>{ce=!0,ye&&clearTimeout(ye)}},[t,C]),w.useEffect(()=>{if(t!=="idle"||C){S(!1);return}let ce=!1,ye=null;const xe=()=>{const ve=18e3+Math.random()*17e3;setTimeout(()=>{ce||(S(!0),ye=window.setTimeout(()=>{ye=null,ce||S(!1)},1600),xe())},ve)};return xe(),()=>{ce=!0,ye&&clearTimeout(ye)}},[t,C]),w.useEffect(()=>{if(t!=="idle"){D(!1);return}let ce=!1;const ye=()=>{const ve=Date.now()-F.current;if(ve>=l)ce||D(!0);else{const X=l-ve;return setTimeout(()=>{ce||ye()},Math.min(X,5e3))}},xe=ye();return()=>{ce=!0,xe&&clearTimeout(xe)}},[t,l]),w.useEffect(()=>{if(!d){E(null);return}let ce=!1;const ye=(X,K,ee)=>{if((ee.curiosity??.5)>.65&&(ee.satisfaction??.5)>.6)return"excited";switch(X){case"curiosity":return K<0?"curious":"happy";case"focus":return"focused";case"fatigue":return"tired";case"satisfaction":return K>0?"happy":"neutral";case"frustration":return"frustrated";case"hunger":return K<0?"tired":"happy";case"safety":return K<0?"frustrated":"happy";case"social":return K<0?"curious":"happy";case"purpose":return K<0?"curious":"focused";default:return"neutral"}},xe=async()=>{try{const X=typeof localStorage<"u"?localStorage.getItem("titan-token"):null,K={};X&&(K.Authorization=`Bearer ${X}`);const ee=await fetch("/api/soma/drives",{headers:K});if(!ee.ok)return;const ae=await ee.json();if(ce)return;if(!ae.dominant||ae.dominant.drive==="neutral"||!ae.current){E(null);return}E(ye(ae.dominant.drive,ae.dominant.delta,ae.current))}catch{}};xe();const ve=setInterval(xe,1e4);return()=>{ce=!0,clearInterval(ve)}},[d]),w.useEffect(()=>{if(t!=="listening"){R(!1);return}R(!0);const ce=setTimeout(()=>R(!1),1200);return()=>clearTimeout(ce)},[t]),w.useEffect(()=>{if(!o||!$.current||H)return;const ce=$.current,ye=220,xe=5,ve={x:0,y:0,has:!1},X=M=>{ve.x=M.clientX,ve.y=M.clientY,ve.has=!0};let K=0,ee=!1;const ae=()=>{if(!ee){if(ve.has){const M=ce.getBoundingClientRect(),W=M.left+M.width/2,G=M.top+M.height*.28,ne=(ve.x-W)/ye,N=(ve.y-G)/ye,a=L=>Math.max(-1,Math.min(1,L)),h=a(ne)*xe,b=a(N)*xe*.6;m(L=>Math.abs(L.x-h)<.05&&Math.abs(L.y-b)<.05?L:{x:h,y:b})}K=requestAnimationFrame(ae)}};return K=requestAnimationFrame(ae),window.addEventListener("mousemove",X,{passive:!0}),()=>{ee=!0,cancelAnimationFrame(K),window.removeEventListener("mousemove",X)}},[o,H]);const V=w.useCallback(()=>{q(!0),B(ce=>ce+1),setTimeout(()=>q(!1),520),g==null||g()},[g]),se=k?.6:T?5.5:4.5,Y=k?.4:T?3:5.5,te=(()=>{switch(I){case"happy":return{browL:"M 35 33 Q 42 30 47 33",browR:"M 53 33 Q 58 30 65 33",mouthD:"M 42 56 Q 50 62 58 56",eyeSquintTop:!0,bodyLean:0};case"focused":return{browL:"M 35 33 L 47 35",browR:"M 53 35 L 65 33",mouthD:"M 44 58 L 56 58",eyeSquintTop:!1,bodyLean:2.5};case"tired":return{browL:"M 35 35 Q 41 35 47 36",browR:"M 53 36 Q 59 35 65 35",mouthD:"M 44 58 Q 50 58 56 58",eyeSquintTop:!0,bodyLean:-1.5};case"curious":return{browL:"M 35 32 Q 41 28 47 32",browR:"M 53 33 Q 58 31 65 33",mouthD:"M 46 58 Q 50 59 54 58",eyeSquintTop:!1,bodyLean:1};case"excited":return{browL:"M 35 31 Q 41 27 47 31",browR:"M 53 31 Q 58 27 65 31",mouthD:"M 40 55 Q 50 64 60 55",eyeSquintTop:!1,bodyLean:0};case"frustrated":return{browL:"M 35 32 L 47 36",browR:"M 53 36 L 65 32",mouthD:"M 42 60 Q 50 56 58 60",eyeSquintTop:!1,bodyLean:0};case"proud":return{browL:"M 35 33 Q 41 31 47 33",browR:"M 53 33 Q 58 31 65 33",mouthD:"M 43 56 Q 50 59 57 56",eyeSquintTop:!1,bodyLean:-1};case"neutral":default:return{browL:"M 35 34 L 47 34",browR:"M 53 34 L 65 34",mouthD:null,eyeSquintTop:!1,bodyLean:0}}})(),Q=s,be=i?`mascot-bubble mascot-bubble--${i}`:"mascot-bubble",Ce=r?`bubble-${r}-${Date.now()}`:"no-bubble";return n.jsxs("div",{ref:$,className:p,style:{width:Q,height:Q*1.38},children:[n.jsx("style",{children:`
765
+ 5. Update existing widgets by id — never create duplicates.`}function fl({space:t,onClose:e,onMascotState:s}){const[r,i]=w.useState([]),[o,c]=w.useState(""),[d,l]=w.useState(!1),[p,g]=w.useState([]),u=8,[f,x]=w.useState(null),y=w.useRef(null),E=w.useRef(null),L=w.useRef(null),v=w.useRef(null),A=w.useRef(t);w.useEffect(()=>{A.current=t},[t]);const m=w.useCallback(j=>{const R=A.current;if(j.type==="render_widget"){const P=j.widget,B=Number.isFinite(P.w)?Number(P.w):4,z=Number.isFinite(P.h)?Number(P.h):4,q=Number.isFinite(P.x)&&Number.isFinite(P.y)?{x:Number(P.x),y:Number(P.y)}:Gs(R.widgets||[],B,z),H=ke.addWidget(R.id,{name:P.name||"Widget",format:P.format||"react",source:P.source,x:q.x,y:q.y,w:B,h:z});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),H.id}return j.type==="update_widget"?(ke.updateWidget(R.id,j.widgetId,j.patch||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),j.widgetId):j.type==="remove_widget"?(ke.removeWidget(R.id,j.widgetId),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:R.id}})),j.widgetId):j.type==="set_runtime_state"?(localStorage.setItem(`titan:runtime:${R.id}:${j.key}`,JSON.stringify(j.value)),j.key):j.type==="emit_event"?(window.dispatchEvent(new CustomEvent(j.eventName,{detail:j.detail})),j.eventName):null},[]),k=w.useCallback(j=>{var R,P;m({type:"render_widget",widget:{name:j.templateName,format:j.format,source:j.source,w:((R=j.defaultSize)==null?void 0:R.w)??4,h:((P=j.defaultSize)==null?void 0:P.h)??4}})},[m]);w.useEffect(()=>{var j;(j=y.current)==null||j.scrollIntoView({behavior:"smooth"})},[r]),w.useEffect(()=>{const j=P=>{var z;const B=(z=P.detail)==null?void 0:z.text;typeof B=="string"&&T(B)},R=P=>{const B=P.detail;B!=null&&B.source&&k(B)};return window.addEventListener("titan:chat:prompt",j),window.addEventListener("titan:gallery:run-template",R),()=>{window.removeEventListener("titan:chat:prompt",j),window.removeEventListener("titan:gallery:run-template",R)}},[k]),w.useEffect(()=>{if(!L.current||v.current)return;const j=new ll(L.current,{onLog:R=>console.log("[Sandbox]",R)});return j.setMessageHandler(R=>{var B,z,q,H;const P=A.current;if(R.type==="canvas"&&((B=R.payload)==null?void 0:B.action)==="createWidget"){const J=R.payload.def;if(!J)return{ok:!1,error:"createWidget requires a `def` object"};const $=Number.isFinite(J.w)?J.w:4,F=Number.isFinite(J.h)?J.h:4,V=Number.isFinite(J.x)&&Number.isFinite(J.y)?{x:J.x,y:J.y}:Gs(P.widgets||[],$,F);try{const se=ke.addWidget(P.id,{name:J.name||"Agent Widget",format:J.format||"react",source:J.source||"",x:V.x,y:V.y,w:$,h:F});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0,widgetId:se.id}}catch(se){return{ok:!1,error:se.message}}}if(R.type==="canvas"&&((z=R.payload)==null?void 0:z.action)==="updateWidget"){const{id:J,patch:$}=R.payload;return J?(ke.updateWidget(P.id,J,$||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0,id:J}):{ok:!1,error:"updateWidget requires an `id`"}}if(R.type==="canvas"&&((q=R.payload)==null?void 0:q.action)==="listWidgets")return{ok:!0,widgets:P.widgets||[]};if(R.type==="canvas"&&((H=R.payload)==null?void 0:H.action)==="removeWidget"){const J=R.payload.id;return J?(ke.removeWidget(P.id,J),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:P.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}}),v.current=j,()=>{j.destroy(),v.current=null}},[]);const _=w.useCallback(async(j,R)=>{const P=v.current;if(!P)return{status:"error",logs:[{level:"error",text:"Sandbox not ready"}],resultText:"",runId:Date.now(),error:{message:"Sandbox not ready",name:"SandboxError",stack:"",text:"Sandbox not ready"}};if(j==="_____javascript")try{const B=await P.execute(R);return{status:B.status==="success"?"success":"error",logs:B.logs||[],result:B.result,resultText:B.resultText||String(B.result??""),runId:Date.now(),error:B.error?{message:B.error.message||String(B.error),name:"ExecutionError",stack:"",text:String(B.error)}:void 0}}catch(B){return{status:"error",logs:[{level:"error",text:B.message||String(B)}],resultText:"",runId:Date.now(),error:{message:B.message||String(B),name:"ExecutionError",stack:"",text:String(B)}}}if(j==="_____react"){let B=4,z=4;const q=R.match(/\/\/\s*__WIDGET_META__\s+w=(\d+)\s+h=(\d+)/);q&&(B=parseInt(q[1],10)||4,z=parseInt(q[2],10)||4);try{const H=m({type:"render_widget",widget:{name:"React Widget",format:"react",source:R,w:B,h:z}});return{status:"success",logs:[{level:"info",text:`Created widget ${H}`}],result:{widgetId:H},resultText:`Created widget ${H}`,runId:Date.now()}}catch(H){return{status:"error",logs:[{level:"error",text:H.message||String(H)}],resultText:"",runId:Date.now(),error:{message:H.message||String(H),name:"WidgetError",stack:"",text:String(H)}}}}if(j==="_____widget"){const B=hl({gate:"_____widget",code:R,leadingText:""});if(!B)return{status:"error",logs:[{level:"error",text:"Invalid widget payload"}],resultText:"",runId:Date.now(),error:{message:"Invalid widget payload",name:"WidgetError",stack:"",text:"Invalid widget payload"}};try{const z=m(B),q=B.type==="update_widget"?"Updated":"Created";return{status:"success",logs:[{level:"info",text:`${q} widget ${z}`}],result:z?{widgetId:z}:void 0,resultText:`${q} widget ${z??""}`.trim(),runId:Date.now()}}catch(z){return{status:"error",logs:[{level:"error",text:z.message||String(z)}],resultText:"",runId:Date.now(),error:{message:z.message||String(z),name:"WidgetError",stack:"",text:String(z)}}}}if(j==="_____canvas"){const B=Rf(R);if(B.length===0)return{status:"error",logs:[{level:"error",text:"Empty or invalid _____canvas payload (expected JSON array of {action, ...})"}],resultText:"",runId:Date.now(),error:{message:"Invalid canvas payload",name:"CanvasFenceError",stack:"",text:"Empty or invalid _____canvas payload"}};const z=[],q=[];for(const J of B)try{if(J.action==="create_widget"){if(!J.source){q.push("create_widget: missing source");continue}const $=m({type:"render_widget",widget:{name:J.name||"Widget",title:J.title,format:J.format||"react",source:J.source,w:J.w,h:J.h,x:J.x,y:J.y,metadata:J.metadata}});z.push(`created ${$}`)}else if(J.action==="update_widget"){if(!J.id){q.push("update_widget: missing id");continue}const $=J.patch??{};m({type:"update_widget",widgetId:J.id,patch:$}),z.push(`updated ${J.id}`)}else if(J.action==="remove_widget"){if(!J.id){q.push("remove_widget: missing id");continue}m({type:"remove_widget",widgetId:J.id}),z.push(`removed ${J.id}`)}else q.push(`unknown action: ${String(J.action)}`)}catch($){q.push($.message||String($))}const H=q.length===0?"success":z.length===0?"error":"success";return{status:H,logs:[...z.map(J=>({level:"info",text:J})),...q.map(J=>({level:"error",text:J}))],resultText:z.length?z.join("; "):"No actions applied",runId:Date.now(),...H==="error"?{error:{message:q.join("; "),name:"CanvasFenceError",stack:"",text:q.join("; ")}}:{}}}return j==="_____tool"?{status:"error",logs:[{level:"error",text:"_____tool gate not supported in Canvas chat"}],resultText:"",runId:Date.now(),error:{message:"_____tool gate not supported",name:"NotSupported",stack:"",text:"_____tool gate not supported in Canvas chat"}}:{status:"error",logs:[{level:"error",text:`Unknown gate: ${j}`}],resultText:"",runId:Date.now(),error:{message:`Unknown gate: ${j}`,name:"UnknownGate",stack:"",text:`Unknown gate: ${j}`}}},[]),T=w.useCallback(async j=>{var q;const R=j.trim();if(!R)return;if(d){g(H=>H.length>=u?H:[...H,R]),c("");return}const P={role:"user",content:R,timestamp:Date.now()};i(H=>[...H,P]),c(""),l(!0),x(null),s==null||s("thinking");const B=new AbortController;E.current=B;let z="";try{const H=Of(A.current),J=`canvas-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await Cl(R,J,V=>{if(V.type==="token")z+=V.data,i(se=>{const Y=se[se.length-1];return Y&&Y.role==="assistant"?[...se.slice(0,-1),{...Y,content:z}]:[...se,{role:"assistant",content:z,timestamp:Date.now()}]});else if(V.type==="widget"){const se=V.widgetMode||"create",Y=V.widget||{},te=A.current;try{if(se==="remove"&&Y.id)ke.removeWidget(te.id,Y.id);else if(se==="update"&&Y.id){const Q={};typeof Y.name=="string"&&Y.name&&(Q.name=Y.name),typeof Y.title=="string"&&(Q.title=Y.title),typeof Y.source=="string"&&Y.source&&(Q.source=Y.source),typeof Y.format=="string"&&(Q.format=Y.format),typeof Y.w=="number"&&(Q.w=Y.w),typeof Y.h=="number"&&(Q.h=Y.h),ke.updateWidget(te.id,Y.id,Q)}else if(Y.source){const Q=typeof Y.w=="number"?Y.w:4,be=typeof Y.h=="number"?Y.h:4,Ce=typeof Y.x=="number"&&typeof Y.y=="number"?{x:Y.x,y:Y.y}:Gs(te.widgets||[],Q,be);ke.addWidget(te.id,{name:Y.name||"Widget",title:Y.title,format:Y.format||"react",source:Y.source,x:Ce.x,y:Ce.y,w:Q,h:be,metadata:Y.metadata})}window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:te.id}}))}catch(Q){console.error("[ChatWidget] widget side-channel handler failed",Q)}}else if(V.type==="done"){const se=V.data||z;z=se,i(Y=>{const te=Y[Y.length-1];return te&&te.role==="assistant"?[...Y.slice(0,-1),{...te,content:se}]:[...Y,{role:"assistant",content:se,timestamp:Date.now()}]})}else V.type==="error"&&x(V.data)},B.signal,{systemPromptAppendix:H});const F=Af(z).filter(V=>V.gate!=="_____transient"&&V.gate!=="_____framework");if(F.length>0){s==null||s("executing");const V=[];for(const te of F){const Q=Mf(`${te.gate}
766
+ ${te.code}`);if(!Q.valid){V.push({status:"error",logs:[{level:"error",text:Q.error||"Invalid execution"}],resultText:"",runId:Date.now(),error:{message:Q.error||"Invalid execution",name:"ValidationError",stack:"",text:Q.error||""}});continue}const be=await _(te.gate,te.code);V.push(be)}const se=If(V);i(te=>[...te,se]);const Y=V.find(te=>te.status==="error");Y&&x(((q=Y.error)==null?void 0:q.text)||"Execution failed")}}catch(H){H.name!=="AbortError"&&x(H.message||"Request failed")}finally{l(!1),E.current=null,s==null||s("idle")}},[d,s,_]),S=w.useCallback(()=>{var j;(j=E.current)==null||j.abort(),E.current=null,l(!1),g([]),s==null||s("idle")},[s]);w.useEffect(()=>{if(d||p.length===0)return;const[j,...R]=p;g(R),T(j)},[d,p,T]);const C=w.useCallback(j=>{g(R=>R.filter((P,B)=>B!==j))},[]),D=w.useCallback(j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),T(o))},[o,T]);return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",width:"100%"},children:[n.jsx("iframe",{ref:L,style:{position:"absolute",width:0,height:0,border:0,visibility:"hidden"},sandbox:"allow-scripts"}),n.jsxs("div",{style:{flex:1,overflowY:"auto",padding:12},children:[r.map((j,R)=>n.jsxs("div",{style:{marginBottom:8,padding:8,borderRadius:8,background:j.role==="user"?"rgba(59,130,246,0.15)":j.role==="framework"?"rgba(245,158,11,0.1)":"rgba(255,255,255,0.05)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[n.jsx("div",{style:{fontSize:10,opacity:.6,marginBottom:4,textTransform:"uppercase"},children:j.role}),n.jsx("div",{style:{fontSize:13,lineHeight:1.5},children:j.content}),j.executions&&j.executions.length>0&&n.jsx("div",{style:{marginTop:4,fontSize:11,opacity:.7},children:j.executions.map((P,B)=>n.jsxs("span",{style:{marginRight:8},children:[P.status==="success"?"✓":"✗"," execution ",B+1]},B))})]},R)),d&&n.jsx("div",{style:{fontSize:12,opacity:.5,padding:8},children:"Thinking…"}),f&&n.jsx("div",{style:{color:"#ef4444",fontSize:12,padding:8,background:"rgba(239,68,68,0.1)",borderRadius:6},children:f}),n.jsx("div",{ref:y})]}),p.length>0&&n.jsxs("div",{style:{padding:"6px 12px",borderTop:"1px solid rgba(255,255,255,0.08)",display:"flex",flexWrap:"wrap",gap:6,background:"rgba(99,102,241,0.06)"},children:[n.jsxs("span",{style:{fontSize:10,opacity:.7,alignSelf:"center",textTransform:"uppercase",letterSpacing:.5},children:["Queued (",p.length,")"]}),p.map((j,R)=>n.jsxs("span",{title:j,style:{fontSize:11,padding:"3px 8px",background:"rgba(99,102,241,0.18)",border:"1px solid rgba(99,102,241,0.4)",borderRadius:999,color:"#e0e7ff",display:"inline-flex",alignItems:"center",gap:6,maxWidth:220},children:[n.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:j}),n.jsx("button",{onClick:()=>C(R),title:"Remove from queue",style:{border:"none",background:"transparent",color:"#c7d2fe",cursor:"pointer",padding:0,fontSize:12,lineHeight:1},children:"×"})]},R))]}),n.jsxs("div",{style:{padding:12,borderTop:"1px solid rgba(255,255,255,0.08)",display:"flex",gap:8},children:[n.jsx("input",{type:"text",value:o,onChange:j=>c(j.target.value),onKeyDown:D,placeholder:d?p.length>=u?`Queue full (${u}) — wait for TITAN to catch up…`:"TITAN is thinking — type to steer or queue a follow-up…":"Ask TITAN to create an agent, run a task, or build a widget…",style:{flex:1,background:"rgba(255,255,255,0.06)",border:d?"1px solid rgba(99,102,241,0.4)":"1px solid rgba(255,255,255,0.1)",borderRadius:8,padding:"8px 12px",color:"#fff",fontSize:13,outline:"none"}}),d?n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>T(o),disabled:!o.trim()||p.length>=u,title:"Queue this message for after the current turn",style:{padding:"8px 14px",borderRadius:8,border:"none",background:o.trim()&&p.length<u?"#6366f1":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:o.trim()&&p.length<u?"pointer":"not-allowed"},children:"Queue"}),n.jsx("button",{onClick:S,title:"Stop the current turn and clear the queue",style:{padding:"8px 14px",borderRadius:8,border:"none",background:"#ef4444",color:"#fff",fontSize:13,cursor:"pointer"},children:"Stop"})]}):n.jsx("button",{onClick:()=>T(o),disabled:!o.trim(),style:{padding:"8px 14px",borderRadius:8,border:"none",background:o.trim()?"#3b82f6":"rgba(255,255,255,0.1)",color:"#fff",fontSize:13,cursor:o.trim()?"pointer":"not-allowed"},children:"Send"})]})]})}const $i={idle:{eye:"#c4a35a",glow:"#f3d27a",ring:"#a47a3a",body:"#3a2410"},thinking:{eye:"#d4b06a",glow:"#e7c68a",ring:"#b4863a",body:"#3a2410"},executing:{eye:"#d4a040",glow:"#f0c060",ring:"#a47a3a",body:"#3a2410"},listening:{eye:"#8ab8c4",glow:"#a8c8d8",ring:"#6a8a98",body:"#2a2010"},error:{eye:"#c45a30",glow:"#e08050",ring:"#a04a20",body:"#3a1810"}},Z={brassDark:"#7a5a2a",brassMid:"#b8902f",brassBright:"#e8c478",brassHi:"#f7e3a8",woodDark:"#3a2412",woodMid:"#5a3818",glassDark:"#0e1612",glassMid:"#1c2820",steam:"#e6d8b8",bolt:"#2a1808"},Pf=9e4;function Wf({state:t="idle",mood:e="neutral",size:s=116,quip:r=null,bubblePhase:i=null,followCursor:o=!0,somaActive:c=!1,somaPoll:d=!0,sleepAfterMs:l=Pf,className:p="",onClick:g,edgeRotate:u=0,faceFlip:f=!1,edgeHidden:x=!1}){const[y,E]=w.useState(null),L=y??e,v=$i[t]??$i.idle,[A,m]=w.useState({x:0,y:0}),[k,_]=w.useState(!1),[T,S]=w.useState(!1),[C,D]=w.useState(!1),[j,R]=w.useState(!1),[P,B]=w.useState(0),[z,q]=w.useState(!1),[H,J]=w.useState(!1),$=w.useRef(null),F=w.useRef(Date.now());w.useEffect(()=>{const ce=window.matchMedia("(prefers-reduced-motion: reduce)");J(ce.matches);const ye=xe=>J(xe.matches);return ce.addEventListener("change",ye),()=>ce.removeEventListener("change",ye)},[]),w.useEffect(()=>{F.current=Date.now(),t!=="idle"&&(D(!1),S(!1))},[t]),w.useEffect(()=>{const ce=()=>{F.current=Date.now()};return window.addEventListener("mousemove",ce,{passive:!0}),window.addEventListener("keydown",ce,{passive:!0}),window.addEventListener("click",ce,{passive:!0}),()=>{window.removeEventListener("mousemove",ce),window.removeEventListener("keydown",ce),window.removeEventListener("click",ce)}},[]),w.useEffect(()=>{if(t==="error"||C){_(!1);return}let ce=!1,ye=null;const xe=()=>{if(ce)return;const ve=2500+Math.random()*4e3;setTimeout(()=>{ce||(_(!0),ye=window.setTimeout(()=>{ye=null,ce||_(!1)},140),xe())},ve)};return xe(),()=>{ce=!0,ye&&clearTimeout(ye)}},[t,C]),w.useEffect(()=>{if(t!=="idle"||C){S(!1);return}let ce=!1,ye=null;const xe=()=>{const ve=18e3+Math.random()*17e3;setTimeout(()=>{ce||(S(!0),ye=window.setTimeout(()=>{ye=null,ce||S(!1)},1600),xe())},ve)};return xe(),()=>{ce=!0,ye&&clearTimeout(ye)}},[t,C]),w.useEffect(()=>{if(t!=="idle"){D(!1);return}let ce=!1;const ye=()=>{const ve=Date.now()-F.current;if(ve>=l)ce||D(!0);else{const X=l-ve;return setTimeout(()=>{ce||ye()},Math.min(X,5e3))}},xe=ye();return()=>{ce=!0,xe&&clearTimeout(xe)}},[t,l]),w.useEffect(()=>{if(!d){E(null);return}let ce=!1;const ye=(X,K,ee)=>{if((ee.curiosity??.5)>.65&&(ee.satisfaction??.5)>.6)return"excited";switch(X){case"curiosity":return K<0?"curious":"happy";case"focus":return"focused";case"fatigue":return"tired";case"satisfaction":return K>0?"happy":"neutral";case"frustration":return"frustrated";case"hunger":return K<0?"tired":"happy";case"safety":return K<0?"frustrated":"happy";case"social":return K<0?"curious":"happy";case"purpose":return K<0?"curious":"focused";default:return"neutral"}},xe=async()=>{try{const X=typeof localStorage<"u"?localStorage.getItem("titan-token"):null,K={};X&&(K.Authorization=`Bearer ${X}`);const ee=await fetch("/api/soma/drives",{headers:K});if(!ee.ok)return;const ae=await ee.json();if(ce)return;if(!ae.dominant||ae.dominant.drive==="neutral"||!ae.current){E(null);return}E(ye(ae.dominant.drive,ae.dominant.delta,ae.current))}catch{}};xe();const ve=setInterval(xe,1e4);return()=>{ce=!0,clearInterval(ve)}},[d]),w.useEffect(()=>{if(t!=="listening"){R(!1);return}R(!0);const ce=setTimeout(()=>R(!1),1200);return()=>clearTimeout(ce)},[t]),w.useEffect(()=>{if(!o||!$.current||H)return;const ce=$.current,ye=220,xe=5,ve={x:0,y:0,has:!1},X=M=>{ve.x=M.clientX,ve.y=M.clientY,ve.has=!0};let K=0,ee=!1;const ae=()=>{if(!ee){if(ve.has){const M=ce.getBoundingClientRect(),W=M.left+M.width/2,G=M.top+M.height*.28,ne=(ve.x-W)/ye,N=(ve.y-G)/ye,a=I=>Math.max(-1,Math.min(1,I)),h=a(ne)*xe,b=a(N)*xe*.6;m(I=>Math.abs(I.x-h)<.05&&Math.abs(I.y-b)<.05?I:{x:h,y:b})}K=requestAnimationFrame(ae)}};return K=requestAnimationFrame(ae),window.addEventListener("mousemove",X,{passive:!0}),()=>{ee=!0,cancelAnimationFrame(K),window.removeEventListener("mousemove",X)}},[o,H]);const V=w.useCallback(()=>{q(!0),B(ce=>ce+1),setTimeout(()=>q(!1),520),g==null||g()},[g]),se=k?.6:T?5.5:4.5,Y=k?.4:T?3:5.5,te=(()=>{switch(L){case"happy":return{browL:"M 35 33 Q 42 30 47 33",browR:"M 53 33 Q 58 30 65 33",mouthD:"M 42 56 Q 50 62 58 56",eyeSquintTop:!0,bodyLean:0};case"focused":return{browL:"M 35 33 L 47 35",browR:"M 53 35 L 65 33",mouthD:"M 44 58 L 56 58",eyeSquintTop:!1,bodyLean:2.5};case"tired":return{browL:"M 35 35 Q 41 35 47 36",browR:"M 53 36 Q 59 35 65 35",mouthD:"M 44 58 Q 50 58 56 58",eyeSquintTop:!0,bodyLean:-1.5};case"curious":return{browL:"M 35 32 Q 41 28 47 32",browR:"M 53 33 Q 58 31 65 33",mouthD:"M 46 58 Q 50 59 54 58",eyeSquintTop:!1,bodyLean:1};case"excited":return{browL:"M 35 31 Q 41 27 47 31",browR:"M 53 31 Q 58 27 65 31",mouthD:"M 40 55 Q 50 64 60 55",eyeSquintTop:!1,bodyLean:0};case"frustrated":return{browL:"M 35 32 L 47 36",browR:"M 53 36 L 65 32",mouthD:"M 42 60 Q 50 56 58 60",eyeSquintTop:!1,bodyLean:0};case"proud":return{browL:"M 35 33 Q 41 31 47 33",browR:"M 53 33 Q 58 31 65 33",mouthD:"M 43 56 Q 50 59 57 56",eyeSquintTop:!1,bodyLean:-1};case"neutral":default:return{browL:"M 35 34 L 47 34",browR:"M 53 34 L 65 34",mouthD:null,eyeSquintTop:!1,bodyLean:0}}})(),Q=s,be=i?`mascot-bubble mascot-bubble--${i}`:"mascot-bubble",Ce=r?`bubble-${r}-${Date.now()}`:"no-bubble";return n.jsxs("div",{ref:$,className:p,style:{width:Q,height:Q*1.38},children:[n.jsx("style",{children:`
767
767
  /* v6.0.4 — Space Agent-style multi-axis float. Bigger
768
768
  translations + a wider rotation range so the mascot feels
769
769
  like it's drifting on a tether instead of pulsing in
@@ -931,14 +931,14 @@ ${te.code}`);if(!Q.valid){V.push({status:"error",logs:[{level:"error",text:Q.err
931
931
  animation: none !important;
932
932
  }
933
933
  }
934
- `}),r&&n.jsxs("div",{className:`${be} absolute left-1/2 px-2.5 py-1.5 rounded-xl bg-[#fdf6e3] border border-[#d4c5a8] text-[11px] text-[#2a2210] whitespace-nowrap shadow-lg`,style:{top:-8,maxWidth:s*2.2,lineHeight:1.35},children:[r,n.jsx("span",{className:"absolute left-1/2 -translate-x-1/2 -bottom-1.5 w-2.5 h-2.5 rotate-45 bg-[#fdf6e3] border-r border-b border-[#d4c5a8]"})]},Ce),n.jsx("div",{className:"mascot-root absolute inset-x-0 bottom-0",style:{"--glow":v.glow,cursor:g?"pointer":"default",pointerEvents:g?"auto":"none"},onClick:V,children:n.jsx("div",{style:{width:Q,height:Q*1.38,transform:`rotate(${u}deg) scaleX(${f?-1:1})`,transformOrigin:"center",transition:"transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)"},children:n.jsxs("svg",{viewBox:"0 0 100 138",width:Q,height:Q*1.38,className:["mascot-body",t,`mood-${I}`,C?"sleeping":"",z?"poking":""].join(" ").trim(),style:{display:"block",overflow:"visible",transform:`rotate(${te.bodyLean}deg)`,transformOrigin:"50% 110%",transition:"transform 600ms cubic-bezier(0.34, 1.2, 0.64, 1)"},children:[n.jsxs("defs",{children:[n.jsxs("radialGradient",{id:`mascot-glow-${t}`,cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:v.glow,stopOpacity:t==="executing"?.45:.22}),n.jsx("stop",{offset:"100%",stopColor:v.glow,stopOpacity:0})]}),n.jsxs("linearGradient",{id:`mascot-body-${t}`,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[n.jsx("stop",{offset:"0%",stopColor:v.body}),n.jsx("stop",{offset:"50%",stopColor:"#0a0614"}),n.jsx("stop",{offset:"100%",stopColor:"#050208"})]}),n.jsx("filter",{id:`mascot-shadow-${t}`,children:n.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"3",floodColor:v.ring,floodOpacity:x?"0":"0.35"})})]}),C&&n.jsxs("g",{fontFamily:"ui-sans-serif, system-ui",fontWeight:"700",fill:v.glow,opacity:"0.85",children:[n.jsx("text",{className:"mascot-zzz",x:"66",y:"22",fontSize:"9",style:{animationDelay:"0s"},children:"z"}),n.jsx("text",{className:"mascot-zzz",x:"70",y:"14",fontSize:"11",style:{animationDelay:"0.7s"},children:"Z"}),n.jsx("text",{className:"mascot-zzz",x:"74",y:"6",fontSize:"13",style:{animationDelay:"1.4s"},children:"Z"})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#mascot-glow-${t})`,opacity:"0.9"}),t==="listening"&&n.jsxs(n.Fragment,{children:[n.jsx("circle",{cx:"50",cy:"40",r:"14",className:"mascot-listen-ring",stroke:v.glow,strokeWidth:"1.5"}),n.jsx("circle",{cx:"50",cy:"40",r:"14",className:"mascot-listen-ring",stroke:v.glow,strokeWidth:"1.5",style:{animationDelay:"0.5s"}})]}),n.jsx("ellipse",{cx:"50",cy:"42",rx:"34",ry:"14",fill:"none",stroke:v.ring,strokeWidth:"1.5",strokeOpacity:"0.32",className:`mascot-halo ${t} ${c?"soma":""}`}),n.jsx("path",{d:"M48 18 Q52 16 48 14 Q52 12 48 10",stroke:Z.brassMid,strokeWidth:"1.3",fill:"none",strokeLinecap:"round"}),n.jsx("line",{x1:"50",y1:"11",x2:"50",y2:"6",stroke:Z.brassDark,strokeWidth:"1.4",strokeLinecap:"round"}),n.jsx("ellipse",{cx:"50",cy:"5",rx:"3.4",ry:"3.8",fill:Z.glassMid,stroke:Z.brassBright,strokeWidth:"0.7",opacity:"0.9"}),n.jsx("circle",{cx:"50",cy:"5",r:"2",fill:v.glow,opacity:"0.95",children:!H&&n.jsx("animate",{attributeName:"r",values:"1.6;2.4;1.6",dur:t==="executing"?"0.7s":c?"3.2s":"2.6s",repeatCount:"indefinite"})}),n.jsx("circle",{cx:"50",cy:"5",r:"5.5",fill:v.glow,opacity:"0.18",children:!H&&n.jsx("animate",{attributeName:"opacity",values:"0.08;0.32;0.08",dur:"2.6s",repeatCount:"indefinite"})}),n.jsx("path",{d:"M48.5 3.5 Q49.5 3 50.5 3.6",stroke:"#fff7d8",strokeWidth:"0.7",fill:"none",opacity:"0.85"}),!H&&n.jsxs("g",{opacity:"0.7",children:[n.jsx("circle",{className:"mascot-steam",cx:"63",cy:"20",r:"2.4",fill:Z.steam,style:{animationDelay:"0s"}}),n.jsx("circle",{className:"mascot-steam",cx:"66",cy:"22",r:"1.8",fill:Z.steam,style:{animationDelay:"1.1s"}}),n.jsx("circle",{className:"mascot-steam",cx:"60",cy:"19",r:"2.0",fill:Z.steam,style:{animationDelay:"2.0s"}})]}),n.jsx("path",{d:"M60 22 L62 19 L66 19 L68 22 Z",fill:Z.brassMid,stroke:Z.brassDark,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"64",cy:"22",rx:"4",ry:"1",fill:Z.brassDark}),n.jsx("rect",{x:"32",y:"44",width:"36",height:"22",rx:"6",fill:Z.brassDark,stroke:Z.bolt,strokeWidth:"0.7"}),n.jsx("rect",{x:"34",y:"46",width:"32",height:"18",rx:"5",fill:Z.brassMid,opacity:"0.85"}),n.jsx("line",{x1:"32",y1:"55",x2:"68",y2:"55",stroke:Z.brassDark,strokeWidth:"0.6",opacity:"0.7"}),n.jsx("g",{className:"mascot-piston",children:n.jsx("rect",{x:"36",y:"40",width:"3",height:"6",rx:"0.8",fill:Z.brassBright,stroke:Z.bolt,strokeWidth:"0.4"})}),n.jsx("g",{className:"mascot-piston",style:{animationDelay:"0.7s"},children:n.jsx("rect",{x:"61",y:"40",width:"3",height:"6",rx:"0.8",fill:Z.brassBright,stroke:Z.bolt,strokeWidth:"0.4"})}),n.jsxs("g",{filter:`url(#mascot-shadow-${t})`,children:[n.jsx("circle",{cx:"50",cy:"38",r:"23",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.9"}),n.jsx("path",{d:"M32 32 Q50 12 68 32",stroke:Z.brassHi,strokeWidth:"1.4",fill:"none",opacity:"0.55"}),n.jsx("circle",{cx:"50",cy:"38",r:"19",fill:Z.brassDark}),n.jsx("circle",{cx:"50",cy:"38",r:"17.5",fill:Z.glassDark}),n.jsxs("g",{fill:Z.bolt,opacity:"0.85",children:[n.jsx("circle",{cx:"32",cy:"38",r:"1.1"}),n.jsx("circle",{cx:"68",cy:"38",r:"1.1"}),n.jsx("circle",{cx:"37",cy:"22",r:"1.0"}),n.jsx("circle",{cx:"63",cy:"22",r:"1.0",className:"mascot-bolt-glint"}),n.jsx("circle",{cx:"37",cy:"54",r:"1.0"}),n.jsx("circle",{cx:"63",cy:"54",r:"1.0"})]})]}),n.jsx("ellipse",{cx:"50",cy:"39",rx:"16",ry:"13",fill:v.body,stroke:Z.brassBright,strokeWidth:"0.9"}),n.jsx("ellipse",{cx:"50",cy:"39",rx:"15",ry:"12",fill:v.glow,opacity:"0.12"}),n.jsx("line",{x1:"34",y1:"39",x2:"66",y2:"39",stroke:Z.brassDark,strokeWidth:"0.35",opacity:"0.45"}),n.jsx("line",{x1:"50",y1:"26",x2:"50",y2:"52",stroke:Z.brassDark,strokeWidth:"0.35",opacity:"0.45"}),n.jsx("path",{d:"M37 31 Q41 27 49 27",stroke:"#fff7d8",strokeWidth:"1.7",strokeLinecap:"round",fill:"none",opacity:"0.55"}),n.jsx("path",{d:"M55 28 Q58 28 60 29.5",stroke:"#fff7d8",strokeWidth:"1.0",strokeLinecap:"round",fill:"none",opacity:"0.4"}),n.jsxs("g",{transform:`translate(${f?-A.x:A.x}, ${A.y})`,children:[n.jsxs("ellipse",{cx:"50",cy:"40",rx:se,ry:Y,fill:v.eye,style:{transition:"rx 140ms ease-out, ry 140ms ease-out"},children:[t==="thinking"&&!C&&!H&&n.jsx("animate",{attributeName:"cx",values:"46;54;46",dur:"1.6s",repeatCount:"indefinite"}),t==="executing"&&!H&&n.jsx("animate",{attributeName:"rx",values:"4.5;6.5;4.5",dur:"0.8s",repeatCount:"indefinite"})]}),te.eyeSquintTop&&!k&&!T&&n.jsx("rect",{x:"43",y:"36",width:"14",height:"2.2",rx:"1",fill:v.body,opacity:"0.9"}),!C&&n.jsx("circle",{cx:48+(f?-A.x:A.x)*.4,cy:"38.5",r:"1.3",fill:"#ffffff",opacity:"0.9"})]}),!T&&!C&&t!=="error"&&n.jsxs("g",{stroke:v.eye,strokeWidth:"1.4",strokeLinecap:"round",fill:"none",opacity:"0.9",children:[n.jsx("path",{d:te.browL,className:"mascot-eyebrow",transform:"translate(0, -3)"}),n.jsx("path",{d:te.browR,className:"mascot-eyebrow",transform:"translate(0, -3)"})]}),te.mouthD&&!C&&t!=="error"&&n.jsx("path",{d:te.mouthD,stroke:v.eye,strokeWidth:"1.4",strokeLinecap:"round",fill:"none",opacity:"0.9",className:"mascot-mouth",transform:"translate(0, -4)"}),n.jsx("rect",{x:"40",y:"60",width:"20",height:"4.5",rx:"1",fill:Z.brassDark}),n.jsx("rect",{x:"40",y:"60",width:"20",height:"2",rx:"0.6",fill:Z.brassBright,opacity:"0.85"}),n.jsx("ellipse",{cx:"50",cy:"65",rx:"22",ry:"4",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("circle",{cx:"32",cy:"65",r:"0.9",fill:Z.bolt}),n.jsx("circle",{cx:"68",cy:"65",r:"0.9",fill:Z.bolt}),n.jsxs("g",{className:"mascot-torso",children:[n.jsx("path",{d:`M28 66
934
+ `}),r&&n.jsxs("div",{className:`${be} absolute left-1/2 px-2.5 py-1.5 rounded-xl bg-[#fdf6e3] border border-[#d4c5a8] text-[11px] text-[#2a2210] whitespace-nowrap shadow-lg`,style:{top:-8,maxWidth:s*2.2,lineHeight:1.35},children:[r,n.jsx("span",{className:"absolute left-1/2 -translate-x-1/2 -bottom-1.5 w-2.5 h-2.5 rotate-45 bg-[#fdf6e3] border-r border-b border-[#d4c5a8]"})]},Ce),n.jsx("div",{className:"mascot-root absolute inset-x-0 bottom-0",style:{"--glow":v.glow,cursor:g?"pointer":"default",pointerEvents:g?"auto":"none"},onClick:V,children:n.jsx("div",{style:{width:Q,height:Q*1.38,transform:`rotate(${u}deg) scaleX(${f?-1:1})`,transformOrigin:"center",transition:"transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)"},children:n.jsxs("svg",{viewBox:"0 0 100 138",width:Q,height:Q*1.38,className:["mascot-body",t,`mood-${L}`,C?"sleeping":"",z?"poking":""].join(" ").trim(),style:{display:"block",overflow:"visible",transform:`rotate(${te.bodyLean}deg)`,transformOrigin:"50% 110%",transition:"transform 600ms cubic-bezier(0.34, 1.2, 0.64, 1)"},children:[n.jsxs("defs",{children:[n.jsxs("radialGradient",{id:`mascot-glow-${t}`,cx:"50%",cy:"50%",r:"50%",children:[n.jsx("stop",{offset:"0%",stopColor:v.glow,stopOpacity:t==="executing"?.45:.22}),n.jsx("stop",{offset:"100%",stopColor:v.glow,stopOpacity:0})]}),n.jsxs("linearGradient",{id:`mascot-body-${t}`,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[n.jsx("stop",{offset:"0%",stopColor:v.body}),n.jsx("stop",{offset:"50%",stopColor:"#0a0614"}),n.jsx("stop",{offset:"100%",stopColor:"#050208"})]}),n.jsx("filter",{id:`mascot-shadow-${t}`,children:n.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"3",floodColor:v.ring,floodOpacity:x?"0":"0.35"})})]}),C&&n.jsxs("g",{fontFamily:"ui-sans-serif, system-ui",fontWeight:"700",fill:v.glow,opacity:"0.85",children:[n.jsx("text",{className:"mascot-zzz",x:"66",y:"22",fontSize:"9",style:{animationDelay:"0s"},children:"z"}),n.jsx("text",{className:"mascot-zzz",x:"70",y:"14",fontSize:"11",style:{animationDelay:"0.7s"},children:"Z"}),n.jsx("text",{className:"mascot-zzz",x:"74",y:"6",fontSize:"13",style:{animationDelay:"1.4s"},children:"Z"})]}),n.jsx("circle",{cx:"50",cy:"50",r:"48",fill:`url(#mascot-glow-${t})`,opacity:"0.9"}),t==="listening"&&n.jsxs(n.Fragment,{children:[n.jsx("circle",{cx:"50",cy:"40",r:"14",className:"mascot-listen-ring",stroke:v.glow,strokeWidth:"1.5"}),n.jsx("circle",{cx:"50",cy:"40",r:"14",className:"mascot-listen-ring",stroke:v.glow,strokeWidth:"1.5",style:{animationDelay:"0.5s"}})]}),n.jsx("ellipse",{cx:"50",cy:"42",rx:"34",ry:"14",fill:"none",stroke:v.ring,strokeWidth:"1.5",strokeOpacity:"0.32",className:`mascot-halo ${t} ${c?"soma":""}`}),n.jsx("path",{d:"M48 18 Q52 16 48 14 Q52 12 48 10",stroke:Z.brassMid,strokeWidth:"1.3",fill:"none",strokeLinecap:"round"}),n.jsx("line",{x1:"50",y1:"11",x2:"50",y2:"6",stroke:Z.brassDark,strokeWidth:"1.4",strokeLinecap:"round"}),n.jsx("ellipse",{cx:"50",cy:"5",rx:"3.4",ry:"3.8",fill:Z.glassMid,stroke:Z.brassBright,strokeWidth:"0.7",opacity:"0.9"}),n.jsx("circle",{cx:"50",cy:"5",r:"2",fill:v.glow,opacity:"0.95",children:!H&&n.jsx("animate",{attributeName:"r",values:"1.6;2.4;1.6",dur:t==="executing"?"0.7s":c?"3.2s":"2.6s",repeatCount:"indefinite"})}),n.jsx("circle",{cx:"50",cy:"5",r:"5.5",fill:v.glow,opacity:"0.18",children:!H&&n.jsx("animate",{attributeName:"opacity",values:"0.08;0.32;0.08",dur:"2.6s",repeatCount:"indefinite"})}),n.jsx("path",{d:"M48.5 3.5 Q49.5 3 50.5 3.6",stroke:"#fff7d8",strokeWidth:"0.7",fill:"none",opacity:"0.85"}),!H&&n.jsxs("g",{opacity:"0.7",children:[n.jsx("circle",{className:"mascot-steam",cx:"63",cy:"20",r:"2.4",fill:Z.steam,style:{animationDelay:"0s"}}),n.jsx("circle",{className:"mascot-steam",cx:"66",cy:"22",r:"1.8",fill:Z.steam,style:{animationDelay:"1.1s"}}),n.jsx("circle",{className:"mascot-steam",cx:"60",cy:"19",r:"2.0",fill:Z.steam,style:{animationDelay:"2.0s"}})]}),n.jsx("path",{d:"M60 22 L62 19 L66 19 L68 22 Z",fill:Z.brassMid,stroke:Z.brassDark,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"64",cy:"22",rx:"4",ry:"1",fill:Z.brassDark}),n.jsx("rect",{x:"32",y:"44",width:"36",height:"22",rx:"6",fill:Z.brassDark,stroke:Z.bolt,strokeWidth:"0.7"}),n.jsx("rect",{x:"34",y:"46",width:"32",height:"18",rx:"5",fill:Z.brassMid,opacity:"0.85"}),n.jsx("line",{x1:"32",y1:"55",x2:"68",y2:"55",stroke:Z.brassDark,strokeWidth:"0.6",opacity:"0.7"}),n.jsx("g",{className:"mascot-piston",children:n.jsx("rect",{x:"36",y:"40",width:"3",height:"6",rx:"0.8",fill:Z.brassBright,stroke:Z.bolt,strokeWidth:"0.4"})}),n.jsx("g",{className:"mascot-piston",style:{animationDelay:"0.7s"},children:n.jsx("rect",{x:"61",y:"40",width:"3",height:"6",rx:"0.8",fill:Z.brassBright,stroke:Z.bolt,strokeWidth:"0.4"})}),n.jsxs("g",{filter:`url(#mascot-shadow-${t})`,children:[n.jsx("circle",{cx:"50",cy:"38",r:"23",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.9"}),n.jsx("path",{d:"M32 32 Q50 12 68 32",stroke:Z.brassHi,strokeWidth:"1.4",fill:"none",opacity:"0.55"}),n.jsx("circle",{cx:"50",cy:"38",r:"19",fill:Z.brassDark}),n.jsx("circle",{cx:"50",cy:"38",r:"17.5",fill:Z.glassDark}),n.jsxs("g",{fill:Z.bolt,opacity:"0.85",children:[n.jsx("circle",{cx:"32",cy:"38",r:"1.1"}),n.jsx("circle",{cx:"68",cy:"38",r:"1.1"}),n.jsx("circle",{cx:"37",cy:"22",r:"1.0"}),n.jsx("circle",{cx:"63",cy:"22",r:"1.0",className:"mascot-bolt-glint"}),n.jsx("circle",{cx:"37",cy:"54",r:"1.0"}),n.jsx("circle",{cx:"63",cy:"54",r:"1.0"})]})]}),n.jsx("ellipse",{cx:"50",cy:"39",rx:"16",ry:"13",fill:v.body,stroke:Z.brassBright,strokeWidth:"0.9"}),n.jsx("ellipse",{cx:"50",cy:"39",rx:"15",ry:"12",fill:v.glow,opacity:"0.12"}),n.jsx("line",{x1:"34",y1:"39",x2:"66",y2:"39",stroke:Z.brassDark,strokeWidth:"0.35",opacity:"0.45"}),n.jsx("line",{x1:"50",y1:"26",x2:"50",y2:"52",stroke:Z.brassDark,strokeWidth:"0.35",opacity:"0.45"}),n.jsx("path",{d:"M37 31 Q41 27 49 27",stroke:"#fff7d8",strokeWidth:"1.7",strokeLinecap:"round",fill:"none",opacity:"0.55"}),n.jsx("path",{d:"M55 28 Q58 28 60 29.5",stroke:"#fff7d8",strokeWidth:"1.0",strokeLinecap:"round",fill:"none",opacity:"0.4"}),n.jsxs("g",{transform:`translate(${f?-A.x:A.x}, ${A.y})`,children:[n.jsxs("ellipse",{cx:"50",cy:"40",rx:se,ry:Y,fill:v.eye,style:{transition:"rx 140ms ease-out, ry 140ms ease-out"},children:[t==="thinking"&&!C&&!H&&n.jsx("animate",{attributeName:"cx",values:"46;54;46",dur:"1.6s",repeatCount:"indefinite"}),t==="executing"&&!H&&n.jsx("animate",{attributeName:"rx",values:"4.5;6.5;4.5",dur:"0.8s",repeatCount:"indefinite"})]}),te.eyeSquintTop&&!k&&!T&&n.jsx("rect",{x:"43",y:"36",width:"14",height:"2.2",rx:"1",fill:v.body,opacity:"0.9"}),!C&&n.jsx("circle",{cx:48+(f?-A.x:A.x)*.4,cy:"38.5",r:"1.3",fill:"#ffffff",opacity:"0.9"})]}),!T&&!C&&t!=="error"&&n.jsxs("g",{stroke:v.eye,strokeWidth:"1.4",strokeLinecap:"round",fill:"none",opacity:"0.9",children:[n.jsx("path",{d:te.browL,className:"mascot-eyebrow",transform:"translate(0, -3)"}),n.jsx("path",{d:te.browR,className:"mascot-eyebrow",transform:"translate(0, -3)"})]}),te.mouthD&&!C&&t!=="error"&&n.jsx("path",{d:te.mouthD,stroke:v.eye,strokeWidth:"1.4",strokeLinecap:"round",fill:"none",opacity:"0.9",className:"mascot-mouth",transform:"translate(0, -4)"}),n.jsx("rect",{x:"40",y:"60",width:"20",height:"4.5",rx:"1",fill:Z.brassDark}),n.jsx("rect",{x:"40",y:"60",width:"20",height:"2",rx:"0.6",fill:Z.brassBright,opacity:"0.85"}),n.jsx("ellipse",{cx:"50",cy:"65",rx:"22",ry:"4",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("circle",{cx:"32",cy:"65",r:"0.9",fill:Z.bolt}),n.jsx("circle",{cx:"68",cy:"65",r:"0.9",fill:Z.bolt}),n.jsxs("g",{className:"mascot-torso",children:[n.jsx("path",{d:`M28 66
935
935
  Q28 64 32 64
936
936
  L68 64
937
937
  Q72 64 72 66
938
938
  L74 108
939
939
  Q74 116 66 116
940
940
  L34 116
941
- Q26 116 26 108 Z`,fill:Z.woodMid,stroke:Z.bolt,strokeWidth:"0.9",filter:`url(#mascot-shadow-${t})`}),n.jsx("path",{d:"M30 78 Q50 76 70 78",stroke:Z.woodDark,strokeWidth:"0.5",fill:"none",opacity:"0.55"}),n.jsx("path",{d:"M30 100 Q50 98 70 100",stroke:Z.woodDark,strokeWidth:"0.5",fill:"none",opacity:"0.5"}),n.jsx("rect",{x:"34",y:"70",width:"32",height:"38",rx:"3",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.7"}),n.jsx("rect",{x:"35",y:"71",width:"30",height:"2",rx:"1",fill:Z.brassHi,opacity:"0.7"}),n.jsxs("g",{fill:Z.bolt,children:[n.jsx("circle",{cx:"36.5",cy:"72.5",r:"0.9"}),n.jsx("circle",{cx:"63.5",cy:"72.5",r:"0.9"}),n.jsx("circle",{cx:"36.5",cy:"105.5",r:"0.9"}),n.jsx("circle",{cx:"63.5",cy:"105.5",r:"0.9"})]}),n.jsx("circle",{cx:"50",cy:"86",r:"11",fill:Z.glassDark,stroke:Z.brassDark,strokeWidth:"1.2"}),n.jsx("circle",{cx:"50",cy:"86",r:"10",fill:Z.glassMid,opacity:"0.85"}),n.jsx("circle",{cx:"50",cy:"86",r:"9.5",fill:v.glow,opacity:"0.10"}),n.jsxs("g",{className:"mascot-cog",children:[n.jsx("path",{d:"M50 78 L51.6 80 L54 79.4 L54.6 81.8 L56.8 82.4 L56.4 84.8 L58.4 86 L56.4 87.2 L56.8 89.6 L54.6 90.2 L54 92.6 L51.6 92 L50 94 L48.4 92 L46 92.6 L45.4 90.2 L43.2 89.6 L43.6 87.2 L41.6 86 L43.6 84.8 L43.2 82.4 L45.4 81.8 L46 79.4 L48.4 80 Z",fill:Z.brassBright,stroke:Z.brassDark,strokeWidth:"0.5"}),n.jsx("circle",{cx:"50",cy:"86",r:"2.2",fill:Z.brassDark}),n.jsx("circle",{cx:"50",cy:"86",r:"0.8",fill:Z.bolt})]}),n.jsxs("g",{className:"mascot-cog-sm",children:[n.jsx("path",{d:"M57 89 L57.8 90 L59 89.7 L59.3 90.9 L60.4 91.2 L60.2 92.4 L61.2 93 L60.2 93.6 L60.4 94.8 L59.3 95.1 L59 96.3 L57.8 96 L57 97 L56.2 96 L55 96.3 L54.7 95.1 L53.6 94.8 L53.8 93.6 L52.8 93 L53.8 92.4 L53.6 91.2 L54.7 90.9 L55 89.7 L56.2 90 Z",fill:Z.brassMid,stroke:Z.brassDark,strokeWidth:"0.4"}),n.jsx("circle",{cx:"57",cy:"93",r:"1",fill:Z.brassDark})]}),n.jsxs("g",{className:"mascot-pendulum",children:[n.jsx("line",{x1:"50",y1:"78",x2:"50",y2:"93",stroke:Z.brassBright,strokeWidth:"0.9",strokeLinecap:"round"}),n.jsx("circle",{cx:"50",cy:"94.5",r:"1.8",fill:Z.brassDark,stroke:Z.brassHi,strokeWidth:"0.4"})]}),n.jsxs("g",{transform:"translate(60, 102)",children:[n.jsx("circle",{r:"3.5",fill:Z.brassDark,stroke:Z.bolt,strokeWidth:"0.4"}),n.jsx("circle",{r:"2.8",fill:Z.brassHi,opacity:"0.7"}),n.jsx("line",{className:"mascot-gauge",x1:"0",y1:"0",x2:"0",y2:"-2.4",stroke:Z.bolt,strokeWidth:"0.55",strokeLinecap:"round"}),n.jsx("circle",{r:"0.5",fill:Z.bolt})]}),n.jsx("rect",{x:"36",y:"100",width:"14",height:"3",rx:"1",fill:Z.glassDark}),n.jsx("rect",{x:"37",y:"100.6",width:"12",height:"1.8",rx:"0.5",fill:v.glow,children:t==="executing"&&!H&&n.jsx("animate",{attributeName:"opacity",values:"0.4;0.95;0.4",dur:"0.6s",repeatCount:"indefinite"})})]}),n.jsx("g",{transform:"translate(20, 96)",children:n.jsxs("g",{className:"mascot-hand-l",children:[n.jsx("circle",{r:"5.8",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.8"}),n.jsx("circle",{r:"4.2",fill:Z.brassBright,opacity:"0.85"}),n.jsx("circle",{r:"1.8",fill:v.glow,opacity:"0.95"}),n.jsx("circle",{r:"0.6",fill:"#fff7d8",opacity:"0.95"})]})}),n.jsx("g",{transform:"translate(80, 96)",children:n.jsxs("g",{className:`${j?"mascot-hand-r waving":"mascot-hand-r"}`,children:[n.jsx("circle",{r:"5.8",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.8"}),n.jsx("circle",{r:"4.2",fill:Z.brassBright,opacity:"0.85"}),n.jsx("circle",{r:"1.8",fill:v.glow,opacity:"0.95"}),n.jsx("circle",{r:"0.6",fill:"#fff7d8",opacity:"0.95"})]})}),n.jsxs("g",{children:[n.jsx("ellipse",{cx:"42",cy:"118",rx:"6.5",ry:"3.4",fill:Z.woodDark,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"42",cy:"117",rx:"6.5",ry:"1.3",fill:Z.brassMid}),n.jsx("circle",{cx:"39",cy:"117",r:"0.7",fill:Z.bolt}),n.jsx("circle",{cx:"45",cy:"117",r:"0.7",fill:Z.bolt})]}),n.jsxs("g",{children:[n.jsx("ellipse",{cx:"58",cy:"118",rx:"6.5",ry:"3.4",fill:Z.woodDark,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"58",cy:"117",rx:"6.5",ry:"1.3",fill:Z.brassMid}),n.jsx("circle",{cx:"55",cy:"117",r:"0.7",fill:Z.bolt}),n.jsx("circle",{cx:"61",cy:"117",r:"0.7",fill:Z.bolt})]}),t==="thinking"&&n.jsxs("g",{children:[n.jsx("circle",{cx:"60",cy:"14",r:"1.5",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0s"}}),n.jsx("circle",{cx:"66",cy:"10",r:"1.1",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0.4s"}}),n.jsx("circle",{cx:"72",cy:"7",r:"0.8",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0.8s"}})]}),t==="error"&&n.jsxs("g",{stroke:"#ef4444",strokeWidth:"1.8",strokeLinecap:"round",opacity:"0.9",children:[n.jsx("line",{x1:"43",y1:"40",x2:"57",y2:"48"}),n.jsx("line",{x1:"57",y1:"40",x2:"43",y2:"48"})]})]})})})]})}const _r="titan2:chat-dock:hidden-edge";function Of(t=e=>typeof localStorage>"u"?null:localStorage.getItem(e)){try{const e=t(_r);if(e==="left"||e==="right"||e==="top"||e==="bottom")return e;if(e==="visible")return null}catch{}return"right"}function Pf(t,e=(s,r)=>{typeof localStorage>"u"||localStorage.setItem(s,r)}){try{t?e(_r,t):e(_r,"visible")}catch{}}const fl="titan2:chat-dock:pos",pl="titan2:chat-dock:size",ml="titan2:chat-dock:hint-shown",Wf=4,ut=116,es=ut*1.38,Ps=14,Bf=320,Uf=360,Ff=960,$f=900,zf=420,Hf=560,Zn=8,Vf=20,Gf=64,qf="transform 280ms cubic-bezier(0.22, 1, 0.36, 1)",Yf="transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)",Kf=400,Jf=180,Xf=1800,Qf=1e4,Zf=28,ep=260,tp=2e3,sp=3500;function np(){try{const t=localStorage.getItem(pl);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 kr(e)}}catch{}return{w:zf,h:Hf}}function rp(t){try{localStorage.setItem(pl,JSON.stringify(t))}catch{}}function kr(t){return{w:Math.max(Bf,Math.min(t.w,Ff)),h:Math.max(Uf,Math.min(t.h,$f))}}function ip(){try{const s=localStorage.getItem(fl);if(s){const r=JSON.parse(s);if(typeof(r==null?void 0:r.x)=="number"&&typeof(r==null?void 0:r.y)=="number")return r}}catch{}const t=typeof window<"u"?window.innerWidth:1280,e=typeof window<"u"?window.innerHeight:800;return{x:t-ut-32,y:e-es-32}}function op(t){try{localStorage.setItem(fl,JSON.stringify(t))}catch{}}let gl=!1;function zi(){try{return localStorage.getItem(ml)==="1"}catch{return gl}}function Hi(){try{localStorage.setItem(ml,"1")}catch{gl=!0}}function er(t){const e=window.innerWidth,s=window.innerHeight;return{x:Math.max(0,Math.min(t.x,e-ut)),y:Math.max(0,Math.min(t.y,s-es))}}function Vi(t){const e=window.innerWidth,s=window.innerHeight;return t.x<=Zn?"left":t.x>=e-ut-Zn?"right":t.y>=s-es-Zn?"bottom":null}function ap(t,e){if(!t)return"";const s=ut-Vf,r=e?Gf:0;switch(t){case"left":return`translate3d(${-(s-r)}px, 0, 0)`;case"right":return`translate3d(${s-r}px, 0, 0)`;case"top":return`translate3d(0, ${-(s-r)}px, 0)`;case"bottom":return`translate3d(0, ${s-r}px, 0)`;default:return""}}function lp(t){switch(t){case"left":return 90;case"right":return-90;case"top":return 180;case"bottom":return 0;default:return 0}}function cp(t){return t.x>window.innerWidth/2}function dp(t){const e=t.trim().split(/\s+/).filter(Boolean).length,s=Xf+t.length*Zf+e*ep;return Math.min(s,Qf)}function up(t,e){const s=window.innerWidth,r=window.innerHeight,i=s-(t.x+ut),o=r-(t.y+es),c=i>=e.w+Ps?"right":"left",d=o>=e.h+Ps?"below":"above",l=c==="right"?t.x+ut+Ps:t.x-e.w-Ps,p=d==="below"?t.y:t.y+es-e.h;return{left:Math.max(8,Math.min(l,s-e.w-8)),top:Math.max(8,Math.min(p,r-e.h-8)),side:c,vertical:d}}function hp({space:t,somaActive:e,defaultExpanded:s=!1}){const[r,i]=w.useState(!1),o=e??r;w.useEffect(()=>{let X=!1;ge("/api/config").then(ee=>ee.ok?ee.json():null).then(ee=>{var ae;X||i(!!((ae=ee==null?void 0:ee.organism)!=null&&ae.enabled))}).catch(()=>{});const K=ee=>{const ae=ee.detail;typeof(ae==null?void 0:ae.enabled)=="boolean"&&i(ae.enabled)};return window.addEventListener("titan:soma:changed",K),()=>{X=!0,window.removeEventListener("titan:soma:changed",K)}},[]),w.useEffect(()=>{const X=K=>{const ee=K.detail;typeof(ee==null?void 0:ee.open)=="boolean"?u(ee.open):u(ae=>!ae)};return window.addEventListener("titan:chat:toggle",X),()=>window.removeEventListener("titan:chat:toggle",X)},[]);const[c,d]=w.useState(()=>er(ip())),[l,p]=w.useState(()=>np()),[g,u]=w.useState(s),[f,x]=w.useState(!1),[y,E]=w.useState(!1),[I,v]=w.useState("idle"),[A,m]=w.useState(()=>Of()),[k,_]=w.useState(!1),[T,S]=w.useState(!1),[C,D]=w.useState(null),j=w.useRef({}),R=w.useRef(null),P=w.useRef(null),B=w.useRef(!1);w.useEffect(()=>{op(c)},[c]),w.useEffect(()=>{rp(l)},[l]),w.useEffect(()=>{Pf(A)},[A]),w.useEffect(()=>{const X=window.matchMedia("(prefers-reduced-motion: reduce)");S(X.matches);const K=ee=>S(ee.matches);return X.addEventListener("change",K),()=>X.removeEventListener("change",K)},[]),w.useEffect(()=>{let X,K;const ee=()=>{clearTimeout(K),K=window.setTimeout(()=>{d(W=>{const G=er(W),ne=Vi(G);return m(ne),G}),p(W=>kr(W))},50)},ae=()=>{clearTimeout(X),X=window.setTimeout(ee,100)};window.addEventListener("resize",ae),document.addEventListener("visibilitychange",ee),window.addEventListener("focus",ee),window.addEventListener("pageshow",ee);const M=window.setInterval(ee,2e3);return()=>{window.removeEventListener("resize",ae),document.removeEventListener("visibilitychange",ee),window.removeEventListener("focus",ee),window.removeEventListener("pageshow",ee),clearTimeout(X),clearTimeout(K),clearInterval(M)}},[]),w.useEffect(()=>()=>{clearTimeout(j.current.enter),clearTimeout(j.current.exit),clearTimeout(j.current.hide)},[]),w.useEffect(()=>{if(zi())return;let X,K;return X=window.setTimeout(()=>{q("Drag me, tap me."),Hi(),K=window.setTimeout(()=>{H()},sp),j.current.hide=K},tp),()=>{clearTimeout(X),clearTimeout(K)}},[]);const z=w.useCallback(()=>{clearTimeout(j.current.enter),clearTimeout(j.current.exit),clearTimeout(j.current.hide),j.current={}},[]),q=w.useCallback(X=>{z(),D({text:X,phase:"entering"}),j.current.enter=window.setTimeout(()=>{D(ee=>ee&&ee.text===X?{...ee,phase:"visible"}:ee);const K=dp(X);j.current.hide=window.setTimeout(()=>{H()},K)},Kf)},[z]),H=w.useCallback(()=>{z(),D(X=>X?(j.current.exit=window.setTimeout(()=>{D(null)},Jf),{...X,phase:"leaving"}):null)},[z]),J=I==="thinking"?"thinking…":I==="executing"?"working on it":null;w.useEffect(()=>{J?q(J):D(X=>X?((X.text==="thinking…"||X.text==="working on it")&&H(),X):null)},[J]);const $=w.useCallback(X=>{var K,ee;X.button===0&&((ee=(K=X.target).setPointerCapture)==null||ee.call(K,X.pointerId),R.current={pointer:{x:X.clientX,y:X.clientY},pos:c,moved:!1},x(!0),zi()||Hi())},[c]),F=w.useCallback(X=>{const K=R.current;if(!K)return;const ee=X.clientX-K.pointer.x,ae=X.clientY-K.pointer.y;!K.moved&&Math.hypot(ee,ae)<Wf||(K.moved=!0,A&&m(null),d(er({x:K.pos.x+ee,y:K.pos.y+ae})))},[A]),V=w.useCallback(X=>{var ee,ae;const K=R.current;if((ae=(ee=X.target).releasePointerCapture)==null||ae.call(ee,X.pointerId),R.current=null,x(!1),K&&K.moved){const M=Vi(c);m(M||null)}else K&&!K.moved&&(A&&m(null),u(M=>!M))},[c,A]),se=w.useCallback(()=>{A&&_(!0)},[A]),Y=w.useCallback(()=>{_(!1)},[]),te=w.useCallback(X=>{if(X.ctrlKey||f)return;let K=X.target;for(;K&&K!==document.body;){const ee=window.getComputedStyle(K),ae=K.scrollHeight>K.clientHeight,M=ee.overflowY;if(ae&&(M==="auto"||M==="scroll")){K.scrollTop+=X.deltaY,X.preventDefault();return}K=K.parentElement}window.scrollBy({top:X.deltaY,left:X.deltaX,behavior:"auto"}),X.preventDefault()},[f]),Q=up(c,l),be=(C==null?void 0:C.text)??null,Ce=(C==null?void 0:C.phase)??null,ce=w.useCallback(X=>{var K,ee;X.button===0&&(X.stopPropagation(),(ee=(K=X.target).setPointerCapture)==null||ee.call(K,X.pointerId),P.current={pointer:{x:X.clientX,y:X.clientY},size:l,anchorSide:Q.side,anchorVertical:Q.vertical},E(!0))},[l,Q.side,Q.vertical]),ye=w.useCallback(X=>{const K=P.current;if(!K)return;const ee=X.clientX-K.pointer.x,ae=X.clientY-K.pointer.y,M=K.anchorSide==="right"?ee:-ee,W=K.anchorVertical==="below"?ae:-ae;p(kr({w:K.size.w+M,h:K.size.h+W}))},[]),xe=w.useCallback(X=>{var K,ee;(ee=(K=X.target).releasePointerCapture)==null||ee.call(K,X.pointerId),P.current=null,E(!1)},[]),ve=ap(A,k);return n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",left:c.x,top:c.y,width:ut,height:es,zIndex:2147482e3,cursor:f?"grabbing":A?"pointer":"grab",touchAction:"none",userSelect:"none",animation:T?void 0:"titan-dock-in 220ms ease-out both",transform:ve,transition:f?"none":`${qf}, ${Yf}`},onPointerDown:$,onPointerMove:F,onPointerUp:V,onPointerCancel:V,onPointerEnter:se,onPointerLeave:Y,onWheel:te,title:g?"Click to minimize TITAN chat — drag to move":"Click to open TITAN chat — drag to move",children:n.jsx(Mf,{state:I,size:ut,quip:be,bubblePhase:Ce,somaActive:o,followCursor:!f,edgeRotate:lp(A),faceFlip:cp(c),edgeHidden:!!A})}),g&&n.jsxs("div",{style:{position:"fixed",left:Q.left,top:Q.top,width:l.w,height:l.h,zIndex:2147481999,pointerEvents:"auto",borderRadius:14,border:"1px solid rgba(255,255,255,0.08)",background:"rgba(11,11,14,0.72)",backdropFilter:"blur(18px) saturate(1.08)",WebkitBackdropFilter:"blur(18px) saturate(1.08)",boxShadow:"0 18px 44px rgba(0,0,0,0.24)",animation:y||B.current||T?void 0:"titan-dock-panel-in 180ms cubic-bezier(0.2, 0.9, 0.25, 1) both",transformOrigin:`${Q.side==="right"?"left":"right"} ${Q.vertical==="below"?"top":"bottom"}`},children:[n.jsx(hl,{space:t,onClose:()=>u(!1),onMascotState:v}),n.jsx("div",{onPointerDown:ce,onPointerMove:ye,onPointerUp:xe,onPointerCancel:xe,title:"Drag to resize",style:{position:"absolute",[Q.vertical==="below"?"bottom":"top"]:0,[Q.side==="right"?"right":"left"]:0,width:18,height:18,cursor:Q.side==="right"?"nwse-resize":"nesw-resize",touchAction:"none",background:"transparent",zIndex:2},children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 18 18",style:{display:"block",opacity:y?1:.55},children:Q.side==="right"?n.jsxs("g",{stroke:"#6366f1",strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[n.jsx("line",{x1:"5",y1:"14",x2:"14",y2:"14"}),n.jsx("line",{x1:"9",y1:"10",x2:"14",y2:"10"}),n.jsx("line",{x1:"14",y1:"14",x2:"14",y2:"5"})]}):n.jsxs("g",{stroke:"#6366f1",strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[n.jsx("line",{x1:"4",y1:"14",x2:"13",y2:"14"}),n.jsx("line",{x1:"4",y1:"10",x2:"9",y2:"10"}),n.jsx("line",{x1:"4",y1:"14",x2:"4",y2:"5"})]})})})]}),n.jsx("style",{children:`
941
+ Q26 116 26 108 Z`,fill:Z.woodMid,stroke:Z.bolt,strokeWidth:"0.9",filter:`url(#mascot-shadow-${t})`}),n.jsx("path",{d:"M30 78 Q50 76 70 78",stroke:Z.woodDark,strokeWidth:"0.5",fill:"none",opacity:"0.55"}),n.jsx("path",{d:"M30 100 Q50 98 70 100",stroke:Z.woodDark,strokeWidth:"0.5",fill:"none",opacity:"0.5"}),n.jsx("rect",{x:"34",y:"70",width:"32",height:"38",rx:"3",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.7"}),n.jsx("rect",{x:"35",y:"71",width:"30",height:"2",rx:"1",fill:Z.brassHi,opacity:"0.7"}),n.jsxs("g",{fill:Z.bolt,children:[n.jsx("circle",{cx:"36.5",cy:"72.5",r:"0.9"}),n.jsx("circle",{cx:"63.5",cy:"72.5",r:"0.9"}),n.jsx("circle",{cx:"36.5",cy:"105.5",r:"0.9"}),n.jsx("circle",{cx:"63.5",cy:"105.5",r:"0.9"})]}),n.jsx("circle",{cx:"50",cy:"86",r:"11",fill:Z.glassDark,stroke:Z.brassDark,strokeWidth:"1.2"}),n.jsx("circle",{cx:"50",cy:"86",r:"10",fill:Z.glassMid,opacity:"0.85"}),n.jsx("circle",{cx:"50",cy:"86",r:"9.5",fill:v.glow,opacity:"0.10"}),n.jsxs("g",{className:"mascot-cog",children:[n.jsx("path",{d:"M50 78 L51.6 80 L54 79.4 L54.6 81.8 L56.8 82.4 L56.4 84.8 L58.4 86 L56.4 87.2 L56.8 89.6 L54.6 90.2 L54 92.6 L51.6 92 L50 94 L48.4 92 L46 92.6 L45.4 90.2 L43.2 89.6 L43.6 87.2 L41.6 86 L43.6 84.8 L43.2 82.4 L45.4 81.8 L46 79.4 L48.4 80 Z",fill:Z.brassBright,stroke:Z.brassDark,strokeWidth:"0.5"}),n.jsx("circle",{cx:"50",cy:"86",r:"2.2",fill:Z.brassDark}),n.jsx("circle",{cx:"50",cy:"86",r:"0.8",fill:Z.bolt})]}),n.jsxs("g",{className:"mascot-cog-sm",children:[n.jsx("path",{d:"M57 89 L57.8 90 L59 89.7 L59.3 90.9 L60.4 91.2 L60.2 92.4 L61.2 93 L60.2 93.6 L60.4 94.8 L59.3 95.1 L59 96.3 L57.8 96 L57 97 L56.2 96 L55 96.3 L54.7 95.1 L53.6 94.8 L53.8 93.6 L52.8 93 L53.8 92.4 L53.6 91.2 L54.7 90.9 L55 89.7 L56.2 90 Z",fill:Z.brassMid,stroke:Z.brassDark,strokeWidth:"0.4"}),n.jsx("circle",{cx:"57",cy:"93",r:"1",fill:Z.brassDark})]}),n.jsxs("g",{className:"mascot-pendulum",children:[n.jsx("line",{x1:"50",y1:"78",x2:"50",y2:"93",stroke:Z.brassBright,strokeWidth:"0.9",strokeLinecap:"round"}),n.jsx("circle",{cx:"50",cy:"94.5",r:"1.8",fill:Z.brassDark,stroke:Z.brassHi,strokeWidth:"0.4"})]}),n.jsxs("g",{transform:"translate(60, 102)",children:[n.jsx("circle",{r:"3.5",fill:Z.brassDark,stroke:Z.bolt,strokeWidth:"0.4"}),n.jsx("circle",{r:"2.8",fill:Z.brassHi,opacity:"0.7"}),n.jsx("line",{className:"mascot-gauge",x1:"0",y1:"0",x2:"0",y2:"-2.4",stroke:Z.bolt,strokeWidth:"0.55",strokeLinecap:"round"}),n.jsx("circle",{r:"0.5",fill:Z.bolt})]}),n.jsx("rect",{x:"36",y:"100",width:"14",height:"3",rx:"1",fill:Z.glassDark}),n.jsx("rect",{x:"37",y:"100.6",width:"12",height:"1.8",rx:"0.5",fill:v.glow,children:t==="executing"&&!H&&n.jsx("animate",{attributeName:"opacity",values:"0.4;0.95;0.4",dur:"0.6s",repeatCount:"indefinite"})})]}),n.jsx("g",{transform:"translate(20, 96)",children:n.jsxs("g",{className:"mascot-hand-l",children:[n.jsx("circle",{r:"5.8",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.8"}),n.jsx("circle",{r:"4.2",fill:Z.brassBright,opacity:"0.85"}),n.jsx("circle",{r:"1.8",fill:v.glow,opacity:"0.95"}),n.jsx("circle",{r:"0.6",fill:"#fff7d8",opacity:"0.95"})]})}),n.jsx("g",{transform:"translate(80, 96)",children:n.jsxs("g",{className:`${j?"mascot-hand-r waving":"mascot-hand-r"}`,children:[n.jsx("circle",{r:"5.8",fill:Z.brassMid,stroke:Z.bolt,strokeWidth:"0.8"}),n.jsx("circle",{r:"4.2",fill:Z.brassBright,opacity:"0.85"}),n.jsx("circle",{r:"1.8",fill:v.glow,opacity:"0.95"}),n.jsx("circle",{r:"0.6",fill:"#fff7d8",opacity:"0.95"})]})}),n.jsxs("g",{children:[n.jsx("ellipse",{cx:"42",cy:"118",rx:"6.5",ry:"3.4",fill:Z.woodDark,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"42",cy:"117",rx:"6.5",ry:"1.3",fill:Z.brassMid}),n.jsx("circle",{cx:"39",cy:"117",r:"0.7",fill:Z.bolt}),n.jsx("circle",{cx:"45",cy:"117",r:"0.7",fill:Z.bolt})]}),n.jsxs("g",{children:[n.jsx("ellipse",{cx:"58",cy:"118",rx:"6.5",ry:"3.4",fill:Z.woodDark,stroke:Z.bolt,strokeWidth:"0.6"}),n.jsx("ellipse",{cx:"58",cy:"117",rx:"6.5",ry:"1.3",fill:Z.brassMid}),n.jsx("circle",{cx:"55",cy:"117",r:"0.7",fill:Z.bolt}),n.jsx("circle",{cx:"61",cy:"117",r:"0.7",fill:Z.bolt})]}),t==="thinking"&&n.jsxs("g",{children:[n.jsx("circle",{cx:"60",cy:"14",r:"1.5",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0s"}}),n.jsx("circle",{cx:"66",cy:"10",r:"1.1",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0.4s"}}),n.jsx("circle",{cx:"72",cy:"7",r:"0.8",className:"mascot-thinking-particle",fill:v.glow,style:{animationDelay:"0.8s"}})]}),t==="error"&&n.jsxs("g",{stroke:"#ef4444",strokeWidth:"1.8",strokeLinecap:"round",opacity:"0.9",children:[n.jsx("line",{x1:"43",y1:"40",x2:"57",y2:"48"}),n.jsx("line",{x1:"57",y1:"40",x2:"43",y2:"48"})]})]})})})]})}const _r="titan2:chat-dock:hidden-edge";function Bf(t=e=>typeof localStorage>"u"?null:localStorage.getItem(e)){try{const e=t(_r);if(e==="left"||e==="right"||e==="top"||e==="bottom")return e;if(e==="visible")return null}catch{}return"right"}function Uf(t,e=(s,r)=>{typeof localStorage>"u"||localStorage.setItem(s,r)}){try{t?e(_r,t):e(_r,"visible")}catch{}}const pl="titan2:chat-dock:pos",ml="titan2:chat-dock:size",gl="titan2:chat-dock:hint-shown",Ff=4,ut=116,es=ut*1.38,Ps=14,$f=320,zf=360,Hf=960,Vf=900,Gf=420,qf=560,Zn=8,Yf=20,Kf=64,Jf="transform 280ms cubic-bezier(0.22, 1, 0.36, 1)",Xf="transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)",Qf=400,Zf=180,ep=1800,tp=1e4,sp=28,np=260,rp=2e3,ip=3500;function op(){try{const t=localStorage.getItem(ml);if(t){const e=JSON.parse(t);if(typeof(e==null?void 0:e.w)=="number"&&typeof(e==null?void 0:e.h)=="number")return kr(e)}}catch{}return{w:Gf,h:qf}}function ap(t){try{localStorage.setItem(ml,JSON.stringify(t))}catch{}}function kr(t){return{w:Math.max($f,Math.min(t.w,Hf)),h:Math.max(zf,Math.min(t.h,Vf))}}function lp(){try{const s=localStorage.getItem(pl);if(s){const r=JSON.parse(s);if(typeof(r==null?void 0:r.x)=="number"&&typeof(r==null?void 0:r.y)=="number")return r}}catch{}const t=typeof window<"u"?window.innerWidth:1280,e=typeof window<"u"?window.innerHeight:800;return{x:t-ut-32,y:e-es-32}}function cp(t){try{localStorage.setItem(pl,JSON.stringify(t))}catch{}}let yl=!1;function zi(){try{return localStorage.getItem(gl)==="1"}catch{return yl}}function Hi(){try{localStorage.setItem(gl,"1")}catch{yl=!0}}function er(t){const e=window.innerWidth,s=window.innerHeight;return{x:Math.max(0,Math.min(t.x,e-ut)),y:Math.max(0,Math.min(t.y,s-es))}}function Vi(t){const e=window.innerWidth,s=window.innerHeight;return t.x<=Zn?"left":t.x>=e-ut-Zn?"right":t.y>=s-es-Zn?"bottom":null}function dp(t,e){if(!t)return"";const s=ut-Yf,r=e?Kf:0;switch(t){case"left":return`translate3d(${-(s-r)}px, 0, 0)`;case"right":return`translate3d(${s-r}px, 0, 0)`;case"top":return`translate3d(0, ${-(s-r)}px, 0)`;case"bottom":return`translate3d(0, ${s-r}px, 0)`;default:return""}}function up(t){switch(t){case"left":return 90;case"right":return-90;case"top":return 180;case"bottom":return 0;default:return 0}}function hp(t){return t.x>window.innerWidth/2}function fp(t){const e=t.trim().split(/\s+/).filter(Boolean).length,s=ep+t.length*sp+e*np;return Math.min(s,tp)}function pp(t,e){const s=window.innerWidth,r=window.innerHeight,i=s-(t.x+ut),o=r-(t.y+es),c=i>=e.w+Ps?"right":"left",d=o>=e.h+Ps?"below":"above",l=c==="right"?t.x+ut+Ps:t.x-e.w-Ps,p=d==="below"?t.y:t.y+es-e.h;return{left:Math.max(8,Math.min(l,s-e.w-8)),top:Math.max(8,Math.min(p,r-e.h-8)),side:c,vertical:d}}function mp({space:t,somaActive:e,defaultExpanded:s=!1}){const[r,i]=w.useState(!1),o=e??r;w.useEffect(()=>{let X=!1;ge("/api/config").then(ee=>ee.ok?ee.json():null).then(ee=>{var ae;X||i(!!((ae=ee==null?void 0:ee.organism)!=null&&ae.enabled))}).catch(()=>{});const K=ee=>{const ae=ee.detail;typeof(ae==null?void 0:ae.enabled)=="boolean"&&i(ae.enabled)};return window.addEventListener("titan:soma:changed",K),()=>{X=!0,window.removeEventListener("titan:soma:changed",K)}},[]),w.useEffect(()=>{const X=K=>{const ee=K.detail;typeof(ee==null?void 0:ee.open)=="boolean"?u(ee.open):u(ae=>!ae)};return window.addEventListener("titan:chat:toggle",X),()=>window.removeEventListener("titan:chat:toggle",X)},[]);const[c,d]=w.useState(()=>er(lp())),[l,p]=w.useState(()=>op()),[g,u]=w.useState(s),[f,x]=w.useState(!1),[y,E]=w.useState(!1),[L,v]=w.useState("idle"),[A,m]=w.useState(()=>Bf()),[k,_]=w.useState(!1),[T,S]=w.useState(!1),[C,D]=w.useState(null),j=w.useRef({}),R=w.useRef(null),P=w.useRef(null),B=w.useRef(!1);w.useEffect(()=>{cp(c)},[c]),w.useEffect(()=>{ap(l)},[l]),w.useEffect(()=>{Uf(A)},[A]),w.useEffect(()=>{const X=window.matchMedia("(prefers-reduced-motion: reduce)");S(X.matches);const K=ee=>S(ee.matches);return X.addEventListener("change",K),()=>X.removeEventListener("change",K)},[]),w.useEffect(()=>{let X,K;const ee=()=>{clearTimeout(K),K=window.setTimeout(()=>{d(W=>{const G=er(W),ne=Vi(G);return m(ne),G}),p(W=>kr(W))},50)},ae=()=>{clearTimeout(X),X=window.setTimeout(ee,100)};window.addEventListener("resize",ae),document.addEventListener("visibilitychange",ee),window.addEventListener("focus",ee),window.addEventListener("pageshow",ee);const M=window.setInterval(ee,2e3);return()=>{window.removeEventListener("resize",ae),document.removeEventListener("visibilitychange",ee),window.removeEventListener("focus",ee),window.removeEventListener("pageshow",ee),clearTimeout(X),clearTimeout(K),clearInterval(M)}},[]),w.useEffect(()=>()=>{clearTimeout(j.current.enter),clearTimeout(j.current.exit),clearTimeout(j.current.hide)},[]),w.useEffect(()=>{if(zi())return;let X,K;return X=window.setTimeout(()=>{q("Drag me, tap me."),Hi(),K=window.setTimeout(()=>{H()},ip),j.current.hide=K},rp),()=>{clearTimeout(X),clearTimeout(K)}},[]);const z=w.useCallback(()=>{clearTimeout(j.current.enter),clearTimeout(j.current.exit),clearTimeout(j.current.hide),j.current={}},[]),q=w.useCallback(X=>{z(),D({text:X,phase:"entering"}),j.current.enter=window.setTimeout(()=>{D(ee=>ee&&ee.text===X?{...ee,phase:"visible"}:ee);const K=fp(X);j.current.hide=window.setTimeout(()=>{H()},K)},Qf)},[z]),H=w.useCallback(()=>{z(),D(X=>X?(j.current.exit=window.setTimeout(()=>{D(null)},Zf),{...X,phase:"leaving"}):null)},[z]),J=L==="thinking"?"thinking…":L==="executing"?"working on it":null;w.useEffect(()=>{J?q(J):D(X=>X?((X.text==="thinking…"||X.text==="working on it")&&H(),X):null)},[J]);const $=w.useCallback(X=>{var K,ee;X.button===0&&((ee=(K=X.target).setPointerCapture)==null||ee.call(K,X.pointerId),R.current={pointer:{x:X.clientX,y:X.clientY},pos:c,moved:!1},x(!0),zi()||Hi())},[c]),F=w.useCallback(X=>{const K=R.current;if(!K)return;const ee=X.clientX-K.pointer.x,ae=X.clientY-K.pointer.y;!K.moved&&Math.hypot(ee,ae)<Ff||(K.moved=!0,A&&m(null),d(er({x:K.pos.x+ee,y:K.pos.y+ae})))},[A]),V=w.useCallback(X=>{var ee,ae;const K=R.current;if((ae=(ee=X.target).releasePointerCapture)==null||ae.call(ee,X.pointerId),R.current=null,x(!1),K&&K.moved){const M=Vi(c);m(M||null)}else K&&!K.moved&&(A&&m(null),u(M=>!M))},[c,A]),se=w.useCallback(()=>{A&&_(!0)},[A]),Y=w.useCallback(()=>{_(!1)},[]),te=w.useCallback(X=>{if(X.ctrlKey||f)return;let K=X.target;for(;K&&K!==document.body;){const ee=window.getComputedStyle(K),ae=K.scrollHeight>K.clientHeight,M=ee.overflowY;if(ae&&(M==="auto"||M==="scroll")){K.scrollTop+=X.deltaY,X.preventDefault();return}K=K.parentElement}window.scrollBy({top:X.deltaY,left:X.deltaX,behavior:"auto"}),X.preventDefault()},[f]),Q=pp(c,l),be=(C==null?void 0:C.text)??null,Ce=(C==null?void 0:C.phase)??null,ce=w.useCallback(X=>{var K,ee;X.button===0&&(X.stopPropagation(),(ee=(K=X.target).setPointerCapture)==null||ee.call(K,X.pointerId),P.current={pointer:{x:X.clientX,y:X.clientY},size:l,anchorSide:Q.side,anchorVertical:Q.vertical},E(!0))},[l,Q.side,Q.vertical]),ye=w.useCallback(X=>{const K=P.current;if(!K)return;const ee=X.clientX-K.pointer.x,ae=X.clientY-K.pointer.y,M=K.anchorSide==="right"?ee:-ee,W=K.anchorVertical==="below"?ae:-ae;p(kr({w:K.size.w+M,h:K.size.h+W}))},[]),xe=w.useCallback(X=>{var K,ee;(ee=(K=X.target).releasePointerCapture)==null||ee.call(K,X.pointerId),P.current=null,E(!1)},[]),ve=dp(A,k);return n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{position:"fixed",left:c.x,top:c.y,width:ut,height:es,zIndex:2147482e3,cursor:f?"grabbing":A?"pointer":"grab",touchAction:"none",userSelect:"none",animation:T?void 0:"titan-dock-in 220ms ease-out both",transform:ve,transition:f?"none":`${Jf}, ${Xf}`},onPointerDown:$,onPointerMove:F,onPointerUp:V,onPointerCancel:V,onPointerEnter:se,onPointerLeave:Y,onWheel:te,title:g?"Click to minimize TITAN chat — drag to move":"Click to open TITAN chat — drag to move",children:n.jsx(Wf,{state:L,size:ut,quip:be,bubblePhase:Ce,somaActive:o,followCursor:!f,edgeRotate:up(A),faceFlip:hp(c),edgeHidden:!!A})}),g&&n.jsxs("div",{style:{position:"fixed",left:Q.left,top:Q.top,width:l.w,height:l.h,zIndex:2147481999,pointerEvents:"auto",borderRadius:14,border:"1px solid rgba(255,255,255,0.08)",background:"rgba(11,11,14,0.72)",backdropFilter:"blur(18px) saturate(1.08)",WebkitBackdropFilter:"blur(18px) saturate(1.08)",boxShadow:"0 18px 44px rgba(0,0,0,0.24)",animation:y||B.current||T?void 0:"titan-dock-panel-in 180ms cubic-bezier(0.2, 0.9, 0.25, 1) both",transformOrigin:`${Q.side==="right"?"left":"right"} ${Q.vertical==="below"?"top":"bottom"}`},children:[n.jsx(fl,{space:t,onClose:()=>u(!1),onMascotState:v}),n.jsx("div",{onPointerDown:ce,onPointerMove:ye,onPointerUp:xe,onPointerCancel:xe,title:"Drag to resize",style:{position:"absolute",[Q.vertical==="below"?"bottom":"top"]:0,[Q.side==="right"?"right":"left"]:0,width:18,height:18,cursor:Q.side==="right"?"nwse-resize":"nesw-resize",touchAction:"none",background:"transparent",zIndex:2},children:n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 18 18",style:{display:"block",opacity:y?1:.55},children:Q.side==="right"?n.jsxs("g",{stroke:"#6366f1",strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[n.jsx("line",{x1:"5",y1:"14",x2:"14",y2:"14"}),n.jsx("line",{x1:"9",y1:"10",x2:"14",y2:"10"}),n.jsx("line",{x1:"14",y1:"14",x2:"14",y2:"5"})]}):n.jsxs("g",{stroke:"#6366f1",strokeWidth:"1.6",strokeLinecap:"round",fill:"none",children:[n.jsx("line",{x1:"4",y1:"14",x2:"13",y2:"14"}),n.jsx("line",{x1:"4",y1:"10",x2:"9",y2:"10"}),n.jsx("line",{x1:"4",y1:"14",x2:"4",y2:"5"})]})})})]}),n.jsx("style",{children:`
942
942
  @keyframes titan-dock-in {
943
943
  from { opacity: 0; transform: translate3d(0, 4px, 0); }
944
944
  to { opacity: 1; transform: translate3d(0, 0, 0); }
@@ -953,7 +953,7 @@ ${te.code}`);if(!Q.valid){V.push({status:"error",logs:[{level:"error",text:Q.err
953
953
  transition: none !important;
954
954
  }
955
955
  }
956
- `})]})}const fp=3e4,pp=3e4;function mp(){const[t,e]=w.useState(null),s=w.useRef(null),r=w.useRef(new Set),i=w.useRef(null);if(w.useEffect(()=>{let c=!1;const d=async()=>{var p;try{const g=await ge("/api/soma/advisories?limit=5");if(!g.ok)return;const u=await g.json();if(c||!((p=u.advisories)!=null&&p.length))return;for(const f of u.advisories)if(!r.current.has(f.at)&&!(s.current&&f.at<=s.current)){if(s.current===null){s.current=u.advisories[0].at;return}s.current=f.at,e(f),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>e(null),pp);return}}catch{}};d();const l=setInterval(d,fp);return()=>{c=!0,clearInterval(l),i.current&&clearTimeout(i.current)}},[]),!t)return null;const o=()=>{r.current.add(t.at),e(null),i.current&&clearTimeout(i.current)};return n.jsx("div",{className:"titan-toast-surface",style:{position:"fixed",bottom:100,right:24,maxWidth:340,padding:"12px 14px",borderRadius:10,borderLeft:"3px solid var(--theme-accent)",fontSize:12,zIndex:60},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.8,color:"var(--theme-accent)",marginBottom:4,fontFamily:"var(--theme-font-mono)"},children:"TITAN noticed"}),n.jsx("div",{style:{lineHeight:1.45,color:"var(--theme-ink)"},children:t.rationale}),n.jsxs("div",{style:{fontSize:10,color:"var(--theme-ink-soft)",marginTop:6,textTransform:"uppercase",letterSpacing:.5,fontFamily:"var(--theme-font-mono)"},children:["suggestion: ",t.action]})]}),n.jsx("button",{onClick:o,"aria-label":"Dismiss",className:"titan-close-btn",style:{fontSize:16,lineHeight:1,marginTop:-2},children:"×"})]})})}const yl="titan-sidebar-collapsed";function gp(t){return/^\/space\/[^/]+\/?$/.test(t)}function yp(t,e=s=>typeof localStorage>"u"?null:localStorage.getItem(s)){try{const s=e(yl);if(s!==null)return s==="1"}catch{}return gp(t)}function bp(){const t=typeof localStorage<"u"?localStorage.getItem("titan-token"):null;return t?{Authorization:`Bearer ${t}`}:{}}async function ls(t,e){const s=await fetch(t,{...e,headers:{"Content-Type":"application/json",...bp(),...(e==null?void 0:e.headers)||{}}});if(!s.ok)throw new Error(`${s.status} ${s.statusText}`);return s.json()}function xp(){const t=Zi(),e=El(),{logout:s}=Nl(),[r,i]=w.useState([]),[o,c]=w.useState(null),[d,l]=w.useState([]),[p,g]=w.useState(!1),[u,f]=w.useState(!1),[x,y]=w.useState(null),[E,I]=w.useState(()=>yp(typeof window<"u"?window.location.pathname:"/")),v=w.useCallback(()=>{I(S=>{const C=!S;try{localStorage.setItem(yl,C?"1":"0")}catch{}return C})},[]),A=w.useCallback(async()=>{try{const S=await ls("/api/spaces");i(S.spaces),c(S.activeSpaceId),y(null)}catch(S){y(S.message)}},[]);w.useEffect(()=>{A(),ls("/api/spaces/presets").then(C=>l(C.presets)).catch(()=>{});const S=()=>A();return window.addEventListener("titan:spaces:refresh",S),()=>window.removeEventListener("titan:spaces:refresh",S)},[A]);const m=w.useCallback(async S=>{try{await ls(`/api/spaces/${S}/activate`,{method:"POST"}),c(S),t(`/space/${S}`)}catch(C){y(C.message)}},[t]),k=w.useCallback(async S=>{f(!0);try{const C=S.preset?d.find(j=>j.id===S.preset):void 0,D=await ls("/api/spaces",{method:"POST",body:JSON.stringify({name:S.name||(C==null?void 0:C.name)||"New Space",icon:C==null?void 0:C.icon,color:C==null?void 0:C.color,makeActive:!0})});await A(),t(`/space/${D.space.id}`),g(!1)}catch(C){y(C.message)}finally{f(!1)}},[t,d,A]),_=w.useCallback(async S=>{if(window.confirm("Archive this Space? Widgets will be preserved and you can restore it later."))try{await ls(`/api/spaces/${S}`,{method:"DELETE"}),await A()}catch(C){y(C.message)}},[A]);if(!e.pathname.startsWith("/space")&&!e.pathname.startsWith("/mission")&&e.pathname!=="/")return null;const T=e.pathname.startsWith("/mission");return E?n.jsx("aside",{className:"w-3 bg-[#0a0e1a] border-r border-[#1f2937] relative flex-shrink-0",title:"Spaces sidebar — collapsed",children:n.jsx("button",{type:"button",onClick:v,className:"absolute top-3 left-full -translate-x-1/2 z-50 w-6 h-12 rounded-r-md bg-[#1f2937] border border-[#27272a] border-l-0 text-[#a1a1aa] hover:text-white hover:bg-[#27272a] flex items-center justify-center text-sm shadow-lg",title:"Show the spaces sidebar","aria-label":"Show sidebar",children:"›"})}):n.jsxs("aside",{className:"w-60 flex flex-col relative flex-shrink-0",style:{background:"var(--theme-menu-bg-solid, #0a0e1a)",borderRight:"1px solid var(--theme-menu-border, #1f2937)",color:"var(--theme-ink, #d4d4d8)",fontFamily:"var(--theme-font-display, ui-sans-serif, system-ui)"},children:[n.jsxs("div",{className:"px-4 pt-4 pb-3 flex items-center justify-between",style:{borderBottom:"1px solid var(--theme-menu-border, #1f2937)"},children:[n.jsxs("button",{type:"button",onClick:()=>t("/space/home"),className:"flex items-center gap-2 group",title:"TITAN home",children:[n.jsx("span",{className:"w-7 h-7 rounded-md flex items-center justify-center text-[14px] font-bold leading-none",style:{background:"var(--theme-metal, #c4a35a)",color:"var(--theme-bolt, #2a1808)",boxShadow:"0 1px 2px var(--theme-shadow, rgba(0,0,0,0.3))",fontFamily:"var(--theme-font-display, serif)"},children:"T"}),n.jsx("span",{className:"text-[15px] tracking-[0.18em] font-semibold leading-none",style:{color:"var(--theme-ink, #e8e8ff)"},children:"TITAN"})]}),n.jsx("button",{type:"button",onClick:v,className:"w-6 h-6 rounded-md flex items-center justify-center text-base transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},title:"Hide sidebar","aria-label":"Hide sidebar",children:"‹"})]}),n.jsxs("nav",{className:"flex-1 overflow-y-auto py-3 px-2",children:[n.jsxs("div",{className:"mb-5",children:[n.jsx(Gi,{children:"Missions"}),n.jsx(qi,{onClick:()=>t("/mission"),active:T&&e.pathname==="/mission",icon:"✶",label:"New Mission",title:"Start a new mission or pick a template"}),n.jsx(qi,{onClick:()=>t("/mission/library"),active:e.pathname==="/mission/library",icon:"❑",label:"Library",title:"Every mission you've run"})]}),n.jsxs("div",{className:"mb-2 flex items-center justify-between px-2",children:[n.jsx(Gi,{inline:!0,children:"Workspaces"}),n.jsx("button",{type:"button",onClick:()=>g(!0),className:"w-5 h-5 rounded flex items-center justify-center text-sm leading-none transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-ink, #fff)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},title:"Create a new Workspace","aria-label":"Create a new Workspace",children:"+"})]}),x&&n.jsx("div",{className:"mx-1 my-1 px-2 py-2 text-[11px] rounded",style:{color:"var(--theme-accent, #ef4444)",background:"rgba(239,68,68,0.08)"},children:x}),r.length===0&&!x&&n.jsxs("div",{className:"px-2 py-3 text-[11px] leading-relaxed italic",style:{color:"var(--theme-ink-soft, #71717a)"},children:["No Workspaces yet. Tap + above, or ask TITAN",n.jsx("br",{}),'"make me a workspace for…"']}),r.map(S=>{const C=S.id===o;return n.jsxs("button",{type:"button",onClick:()=>m(S.id),onContextMenu:D=>{D.preventDefault(),_(S.id)},className:"w-full text-left px-2 py-1.5 rounded text-[13px] flex items-center gap-2 transition-colors",style:{background:C?"var(--theme-menu-active-bg, #1f2937)":"transparent",color:C?"var(--theme-menu-active-fg, #fff)":"var(--theme-ink, #d4d4d8)"},onMouseEnter:D=>{C||(D.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))")},onMouseLeave:D=>{C||(D.currentTarget.style.background="transparent")},title:`${S.name} · right-click to archive`,children:[S.icon&&n.jsx("span",{className:"text-base leading-none",children:S.icon}),n.jsx("span",{className:"flex-1 truncate",children:S.name}),S.widgets.length>0&&n.jsx("span",{className:"text-[10px] tabular-nums px-1.5 rounded-full",style:{color:"var(--theme-ink-soft, #71717a)",background:"var(--theme-menu-hover, rgba(244,215,145,0.10))"},children:S.widgets.length})]},S.id)})]}),n.jsxs("div",{className:"px-2 py-2 flex flex-col gap-0.5",style:{borderTop:"1px solid var(--theme-menu-border, #1f2937)"},children:[n.jsxs("a",{href:"/command-post",className:"px-2 py-1.5 rounded text-[12px] flex items-center gap-2 transition-colors no-underline",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-ink, #fff)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},children:[n.jsx("span",{"aria-hidden":!0,children:"⚙"}),n.jsx("span",{children:"Admin"})]}),n.jsxs("button",{type:"button",onClick:()=>{s(),window.location.assign("/")},className:"w-full text-left px-2 py-1.5 rounded text-[12px] flex items-center gap-2 transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-accent, #ef4444)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},title:"Sign out — mints a fresh token next login",children:[n.jsx("span",{"aria-hidden":!0,children:"⇥"}),n.jsx("span",{children:"Sign out"})]})]}),p&&n.jsx(wp,{presets:d,creating:u,onCreate:k,onClose:()=>g(!1)})]})}function wp(t){const{presets:e,creating:s,onCreate:r,onClose:i}=t,[o,c]=w.useState(""),[d,l]=w.useState(void 0);return n.jsx("div",{className:"fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4",onClick:i,children:n.jsxs("div",{className:"bg-[#0a0e1a] border border-[#1f2937] rounded-lg p-5 w-full max-w-md",onClick:p=>p.stopPropagation(),children:[n.jsx("div",{className:"text-sm font-medium text-white mb-4",children:"New Space"}),n.jsx("label",{className:"block text-[11px] text-[#a1a1aa] mb-1",children:"Starter preset (optional)"}),n.jsx("div",{className:"grid grid-cols-2 gap-2 mb-4",children:e.map(p=>n.jsxs("button",{type:"button",onClick:()=>{l(p.id),o||c(p.name)},className:`text-left px-3 py-2 rounded border ${d===p.id?"border-[#3b82f6] bg-[#0f172a]":"border-[#1f2937] hover:border-[#374151]"}`,title:p.tagline,children:[n.jsxs("div",{className:"text-sm flex items-center gap-2 text-white",children:[n.jsx("span",{children:p.icon}),n.jsx("span",{children:p.name})]}),n.jsx("div",{className:"text-[10px] text-[#71717a] mt-0.5 line-clamp-1",children:p.tagline})]},p.id))}),n.jsx("label",{className:"block text-[11px] text-[#a1a1aa] mb-1",children:"Name"}),n.jsx("input",{type:"text",value:o,onChange:p=>c(p.target.value),placeholder:"My Workspace",className:"w-full bg-[#0d1117] border border-[#1f2937] rounded px-3 py-2 text-sm text-white mb-4",autoFocus:!0}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:i,className:"px-3 py-1.5 text-sm text-[#a1a1aa] hover:text-white",children:"Cancel"}),n.jsx("button",{type:"button",onClick:()=>r({name:o.trim(),preset:d}),disabled:s||!o.trim()&&!d,className:"px-3 py-1.5 bg-[#3b82f6] hover:bg-[#2563eb] disabled:opacity-50 text-white text-sm rounded",children:s?"Creating…":"Create"})]})]})})}function Gi({children:t,inline:e=!1}){return n.jsx("div",{className:`${e?"":"px-2 mb-1.5"} text-[10px] uppercase tracking-[0.18em] font-semibold`,style:{color:"var(--theme-metal, #c4a35a)"},children:t})}function qi({active:t,icon:e,label:s,title:r,onClick:i}){return n.jsxs("button",{type:"button",onClick:i,className:"w-full text-left px-2 py-1.5 rounded text-[13px] flex items-center gap-2 transition-colors",style:{background:t?"var(--theme-menu-active-bg, #1f2937)":"transparent",color:t?"var(--theme-menu-active-fg, #fff)":"var(--theme-ink, #d4d4d8)"},onMouseEnter:o=>{t||(o.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))")},onMouseLeave:o=>{t||(o.currentTarget.style.background="transparent")},title:r,children:[n.jsx("span",{className:"w-5 text-center leading-none",style:{color:t?"var(--theme-menu-active-fg, #fff)":"var(--theme-metal, #c4a35a)"},"aria-hidden":!0,children:e}),n.jsx("span",{className:"flex-1 truncate",children:s})]})}const tr=4e3,vp=[{label:"Focused research partner",body:"You are in the research space. Prefer brief answers with citations. When the user asks a question, default to summarising authoritative sources over generating widgets. Suggest a follow-up question at the end of each response."},{label:"Hands-on builder",body:"You are in the build space. Prefer writing + iterating on widgets over explanation. Keep prose to under 2 sentences per reply. Generate widgets with `canvas.createWidget` whenever the user describes a tool they want."},{label:"Ops / monitoring",body:"You are in the ops space. Prioritise live data — API calls, log tails, health checks. Use titan.api.call and titan.fetch liberally. Surface numbers in tables or small stat widgets."},{label:"Casual / playful",body:"You are in the play space. Relaxed tone, emojis welcome, riff on user ideas, generate fun widgets. Explain trade-offs only if asked."}];function _p({space:t,open:e,onClose:s,onSaved:r}){const[i,o]=w.useState(t.agentInstructions??""),[c,d]=w.useState(!1),[l,p]=w.useState(null),g=w.useRef(null);w.useEffect(()=>{if(e){o(t.agentInstructions??""),p(null);const f=setTimeout(()=>{var x;return(x=g.current)==null?void 0:x.focus()},50);return()=>clearTimeout(f)}},[e,t.id,t.agentInstructions]),w.useEffect(()=>{if(!e)return;const f=x=>{x.key==="Escape"&&s(),x.key==="Enter"&&(x.metaKey||x.ctrlKey)&&u()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e]);const u=w.useCallback(async()=>{if(i.length>tr){p(`Instructions must be ${tr} characters or fewer.`);return}d(!0),p(null);try{const f=i.trim(),x={...t,agentInstructions:f||void 0,updatedAt:new Date().toISOString()};ke.save(x),r==null||r(f),s()}catch(f){p(f.message)}finally{d(!1)}},[i,t,r,s]);return e?n.jsx("div",{className:"fixed inset-0 z-[2147483100] flex items-center justify-center p-4",style:{background:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(4px)"},onClick:s,children:n.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-[#27272a] bg-[#0c0c10] shadow-2xl flex flex-col max-h-[85vh]",onClick:f=>f.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fs,{className:"w-4 h-4 text-[#6366f1]"}),n.jsxs("h3",{className:"font-semibold text-white text-sm",children:["Agent instructions — ",n.jsx("span",{style:{color:t.color||"#6366f1"},children:t.name})]})]}),n.jsx("button",{onClick:s,className:"p-1 rounded hover:bg-[#27272a] text-[#71717a] hover:text-white transition-colors",title:"Close (Esc)",children:n.jsx(js,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"p-5 flex-1 overflow-auto space-y-3",children:[n.jsx("p",{className:"text-[11px] text-[#a1a1aa] leading-relaxed",children:"These instructions are injected into the chat’s system prompt whenever this space is active. Use them to give the agent a persona, a rule set, or a focus area — the chat will behave differently here vs. other spaces."}),n.jsx("textarea",{ref:g,value:i,onChange:f=>o(f.target.value),placeholder:"e.g. You're in the research space — prefer concise, sourced answers over widget generation.",spellCheck:!1,className:"w-full h-48 p-3 rounded-lg border border-[#27272a] bg-[#09090c] text-[13px] text-[#e4e4e7] leading-relaxed font-mono resize-y focus:outline-none focus:border-[#6366f1]/60"}),n.jsxs("div",{className:"flex items-center justify-between text-[10px] text-[#71717a]",children:[n.jsxs("span",{children:[i.length.toLocaleString()," / ",tr.toLocaleString()," characters"]}),n.jsx("span",{children:"⌘/Ctrl + Enter to save"})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-[#71717a] mb-2",children:"Quick presets"}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:vp.map(f=>n.jsxs("button",{onClick:()=>o(f.body),className:"text-left p-3 rounded-lg border border-[#27272a] bg-[#18181b]/60 hover:border-[#6366f1]/50 hover:bg-[#18181b] transition-colors",children:[n.jsx("div",{className:"text-[11px] font-medium text-white mb-1",children:f.label}),n.jsx("div",{className:"text-[10px] text-[#a1a1aa] line-clamp-2 leading-relaxed",children:f.body})]},f.label))})]}),l&&n.jsx("div",{className:"text-[11px] text-[#ef4444] bg-[#ef4444]/10 border border-[#ef4444]/30 rounded p-2",children:l})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-[#27272a]",children:[n.jsx("button",{onClick:s,className:"px-3 py-1.5 rounded-lg text-[12px] text-[#a1a1aa] hover:text-white hover:bg-[#18181b] transition-colors",children:"Cancel"}),n.jsxs("button",{onClick:()=>{u()},disabled:c,className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-lg bg-[#6366f1] hover:bg-[#4f46e5] disabled:opacity-60 text-white text-[12px] font-medium transition-colors",children:[n.jsx(mn,{className:"w-3.5 h-3.5"}),c?"Saving…":"Save"]})]})]})}):null}const kp=12,Sp=["react","vanilla","html"];function jp({widget:t,spaceId:e,open:s,onClose:r,onSaved:i}){const[o,c]=w.useState(t.source),[d,l]=w.useState(t.format),[p,g]=w.useState(t.name),[u,f]=w.useState(!1),[x,y]=w.useState(null),[E,I]=w.useState(!1),v=w.useRef(null);w.useEffect(()=>{if(s){c(t.source),l(t.format),g(t.name),y(null),I(!1);const T=setTimeout(()=>{var S;return(S=v.current)==null?void 0:S.focus()},50);return()=>clearTimeout(T)}},[s,t.id,t.source,t.format,t.name]),w.useEffect(()=>{if(!s)return;const T=S=>{S.key==="Escape"&&r(),S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&A()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[s]);const A=w.useCallback(async()=>{f(!0),y(null);try{const T=o!==t.source||d!==t.format,S=Array.isArray(t.versions)?t.versions:[],C=T?[...S,{source:t.source,format:t.format,savedAt:t.updatedAt}].slice(-kp):S,D={name:p.trim()||t.name,source:o,format:d,versions:C};ke.updateWidget(e,t.id,D),i==null||i({...t,...D,updatedAt:Date.now()}),r()}catch(T){y(T.message)}finally{f(!1)}},[o,d,p,t,e,i,r]),m=w.useCallback(T=>{c(T.source),l(T.format),I(!1)},[]);if(!s)return null;const k=Array.isArray(t.versions)?t.versions:[],_=[...k].reverse();return n.jsx("div",{className:"fixed inset-0 z-[2147483200] flex items-center justify-center p-4",style:{background:"rgba(0, 0, 0, 0.66)",backdropFilter:"blur(4px)"},onClick:r,children:n.jsxs("div",{className:"w-full max-w-4xl rounded-2xl border border-[#27272a] bg-[#0c0c10] shadow-2xl flex flex-col",style:{height:"min(720px, 85vh)"},onClick:T=>T.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(Wl,{className:"w-4 h-4 text-[#6366f1] shrink-0"}),n.jsx("input",{value:p,onChange:T=>g(T.target.value),className:"bg-transparent text-white text-sm font-semibold outline-none border-b border-transparent focus:border-[#6366f1]/60 min-w-0 flex-1"}),n.jsx("span",{className:"text-[10px] font-mono text-[#52525b] shrink-0",children:t.id.slice(0,14)})]}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[n.jsx("button",{onClick:()=>I(T=>!T),disabled:k.length===0,className:`p-1.5 rounded text-[#a1a1aa] hover:bg-[#18181b] hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${E?"bg-[#18181b] text-white":""}`,title:k.length===0?"No history yet":`${k.length} prior version${k.length===1?"":"s"}`,children:n.jsx(Ql,{className:"w-4 h-4"})}),n.jsx("button",{onClick:r,className:"p-1.5 rounded text-[#71717a] hover:bg-[#18181b] hover:text-white transition-colors",title:"Close (Esc)",children:n.jsx(js,{className:"w-4 h-4"})})]})]}),n.jsxs("div",{className:"flex items-center gap-3 px-5 py-2 border-b border-[#27272a] text-[11px]",children:[n.jsxs("label",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-[#71717a]",children:"format"}),n.jsx("select",{value:d,onChange:T=>l(T.target.value),className:"bg-[#18181b] border border-[#27272a] rounded px-2 py-0.5 text-[#e4e4e7] focus:outline-none focus:border-[#6366f1]/60",children:Sp.map(T=>n.jsx("option",{value:T,children:T},T))})]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("span",{className:"text-[#71717a]",children:["updated ",n.jsx("span",{className:"text-[#a1a1aa]",children:new Date(t.updatedAt).toLocaleString()})]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("span",{className:"text-[#71717a]",children:[t.w," × ",t.h," grid cells"]}),n.jsx("div",{className:"ml-auto text-[10px] text-[#52525b]",children:"⌘/Ctrl + Enter to save"})]}),n.jsxs("div",{className:"flex-1 flex min-h-0",children:[n.jsx("textarea",{ref:v,value:o,onChange:T=>c(T.target.value),spellCheck:!1,className:"flex-1 p-4 bg-[#09090c] text-[12.5px] text-[#e4e4e7] leading-relaxed font-mono resize-none focus:outline-none border-r border-[#27272a]",placeholder:Ep[d]}),E&&n.jsxs("div",{className:"w-72 flex flex-col border-l border-[#27272a] bg-[#0a0a0e]",children:[n.jsxs("div",{className:"px-3 py-2 border-b border-[#27272a] text-[10px] uppercase tracking-wider text-[#71717a]",children:["History (",k.length,")"]}),n.jsxs("div",{className:"flex-1 overflow-auto",children:[_.length===0&&n.jsx("div",{className:"p-3 text-[11px] text-[#52525b]",children:"No prior versions yet — save to start tracking."}),_.map((T,S)=>n.jsxs("div",{className:"px-3 py-2 border-b border-[#18181b] hover:bg-[#18181b]/40 transition-colors",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[n.jsx("div",{className:"text-[10px] font-mono text-[#a1a1aa]",children:new Date(T.savedAt).toLocaleString()}),n.jsxs("button",{onClick:()=>m(T),className:"inline-flex items-center gap-1 text-[10px] text-[#6366f1] hover:text-[#a5b4fc] transition-colors",title:"Load this version into the editor",children:[n.jsx(io,{className:"w-3 h-3"}),"revert"]})]}),n.jsxs("div",{className:"text-[10px] text-[#71717a] font-mono",children:["format: ",T.format]}),n.jsxs("div",{className:"text-[10px] text-[#52525b] truncate mt-1",title:T.source.slice(0,280),children:[T.source.slice(0,80),T.source.length>80?"…":""]}),S===0&&n.jsx("div",{className:"text-[9px] text-[#6366f1] mt-1",children:"most recent before current"})]},T.savedAt))]})]})]}),n.jsxs("div",{className:"flex items-center justify-between gap-2 px-5 py-3 border-t border-[#27272a]",children:[n.jsx("div",{className:"text-[10px] text-[#71717a]",children:x?n.jsxs("span",{className:"text-[#ef4444]",children:["Error: ",x]}):o!==t.source||d!==t.format||p!==t.name?"Unsaved changes":"Up to date"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:r,className:"px-3 py-1.5 rounded-lg text-[12px] text-[#a1a1aa] hover:text-white hover:bg-[#18181b] transition-colors",children:"Cancel"}),n.jsxs("button",{onClick:()=>{A()},disabled:u,className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-lg bg-[#6366f1] hover:bg-[#4f46e5] disabled:opacity-60 text-white text-[12px] font-medium transition-colors",children:[n.jsx(mn,{className:"w-3.5 h-3.5"}),u?"Saving…":"Save widget"]})]})]})]})})}const Ep={react:`// Return a React component named "Widget". titan.* APIs are
956
+ `})]})}const gp=3e4,yp=3e4;function bp(){const[t,e]=w.useState(null),s=w.useRef(null),r=w.useRef(new Set),i=w.useRef(null);if(w.useEffect(()=>{let c=!1;const d=async()=>{var p;try{const g=await ge("/api/soma/advisories?limit=5");if(!g.ok)return;const u=await g.json();if(c||!((p=u.advisories)!=null&&p.length))return;for(const f of u.advisories)if(!r.current.has(f.at)&&!(s.current&&f.at<=s.current)){if(s.current===null){s.current=u.advisories[0].at;return}s.current=f.at,e(f),i.current&&clearTimeout(i.current),i.current=setTimeout(()=>e(null),yp);return}}catch{}};d();const l=setInterval(d,gp);return()=>{c=!0,clearInterval(l),i.current&&clearTimeout(i.current)}},[]),!t)return null;const o=()=>{r.current.add(t.at),e(null),i.current&&clearTimeout(i.current)};return n.jsx("div",{className:"titan-toast-surface",style:{position:"fixed",bottom:100,right:24,maxWidth:340,padding:"12px 14px",borderRadius:10,borderLeft:"3px solid var(--theme-accent)",fontSize:12,zIndex:60},children:n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.8,color:"var(--theme-accent)",marginBottom:4,fontFamily:"var(--theme-font-mono)"},children:"TITAN noticed"}),n.jsx("div",{style:{lineHeight:1.45,color:"var(--theme-ink)"},children:t.rationale}),n.jsxs("div",{style:{fontSize:10,color:"var(--theme-ink-soft)",marginTop:6,textTransform:"uppercase",letterSpacing:.5,fontFamily:"var(--theme-font-mono)"},children:["suggestion: ",t.action]})]}),n.jsx("button",{onClick:o,"aria-label":"Dismiss",className:"titan-close-btn",style:{fontSize:16,lineHeight:1,marginTop:-2},children:"×"})]})})}const bl="titan-sidebar-collapsed",xl="titan-sidebar-canvas-pin";function wl(t){return/^\/space\/[^/]+\/?$/.test(t)}function Gi(t,e=s=>typeof localStorage>"u"?null:localStorage.getItem(s)){try{if(wl(t))return e(xl)!=="1";const s=e(bl);if(s!==null)return s==="1"}catch{}return!1}function xp(t,e,s=(r,i)=>{typeof localStorage>"u"||localStorage.setItem(r,i)}){try{wl(e)?s(xl,t?"0":"1"):s(bl,t?"1":"0")}catch{}}function wp(){const t=typeof localStorage<"u"?localStorage.getItem("titan-token"):null;return t?{Authorization:`Bearer ${t}`}:{}}async function ls(t,e){const s=await fetch(t,{...e,headers:{"Content-Type":"application/json",...wp(),...(e==null?void 0:e.headers)||{}}});if(!s.ok)throw new Error(`${s.status} ${s.statusText}`);return s.json()}function vp(){const t=eo(),e=Tl(),{logout:s}=Rl(),[r,i]=w.useState([]),[o,c]=w.useState(null),[d,l]=w.useState([]),[p,g]=w.useState(!1),[u,f]=w.useState(!1),[x,y]=w.useState(null),[E,L]=w.useState(()=>Gi(typeof window<"u"?window.location.pathname:"/"));w.useEffect(()=>{L(Gi(e.pathname))},[e.pathname]);const v=w.useCallback(()=>{L(S=>{const C=!S;return xp(C,typeof window<"u"?window.location.pathname:"/"),C})},[]),A=w.useCallback(async()=>{try{const S=await ls("/api/spaces");i(S.spaces),c(S.activeSpaceId),y(null)}catch(S){y(S.message)}},[]);w.useEffect(()=>{A(),ls("/api/spaces/presets").then(C=>l(C.presets)).catch(()=>{});const S=()=>A();return window.addEventListener("titan:spaces:refresh",S),()=>window.removeEventListener("titan:spaces:refresh",S)},[A]);const m=w.useCallback(async S=>{try{await ls(`/api/spaces/${S}/activate`,{method:"POST"}),c(S),t(`/space/${S}`)}catch(C){y(C.message)}},[t]),k=w.useCallback(async S=>{f(!0);try{const C=S.preset?d.find(j=>j.id===S.preset):void 0,D=await ls("/api/spaces",{method:"POST",body:JSON.stringify({name:S.name||(C==null?void 0:C.name)||"New Space",icon:C==null?void 0:C.icon,color:C==null?void 0:C.color,makeActive:!0})});await A(),t(`/space/${D.space.id}`),g(!1)}catch(C){y(C.message)}finally{f(!1)}},[t,d,A]),_=w.useCallback(async S=>{if(window.confirm("Archive this Space? Widgets will be preserved and you can restore it later."))try{await ls(`/api/spaces/${S}`,{method:"DELETE"}),await A()}catch(C){y(C.message)}},[A]);if(!e.pathname.startsWith("/space")&&!e.pathname.startsWith("/mission")&&e.pathname!=="/")return null;const T=e.pathname.startsWith("/mission");return E?n.jsx("aside",{className:"w-3 bg-[#0a0e1a] border-r border-[#1f2937] relative flex-shrink-0",title:"Spaces sidebar — collapsed",children:n.jsx("button",{type:"button",onClick:v,className:"absolute top-3 left-full -translate-x-1/2 z-50 w-6 h-12 rounded-r-md bg-[#1f2937] border border-[#27272a] border-l-0 text-[#a1a1aa] hover:text-white hover:bg-[#27272a] flex items-center justify-center text-sm shadow-lg",title:"Show the spaces sidebar","aria-label":"Show sidebar",children:"›"})}):n.jsxs("aside",{className:"w-60 flex flex-col relative flex-shrink-0",style:{background:"var(--theme-menu-bg-solid, #0a0e1a)",borderRight:"1px solid var(--theme-menu-border, #1f2937)",color:"var(--theme-ink, #d4d4d8)",fontFamily:"var(--theme-font-display, ui-sans-serif, system-ui)"},children:[n.jsxs("div",{className:"px-4 pt-4 pb-3 flex items-center justify-between",style:{borderBottom:"1px solid var(--theme-menu-border, #1f2937)"},children:[n.jsxs("button",{type:"button",onClick:()=>t("/space/home"),className:"flex items-center gap-2 group",title:"TITAN home",children:[n.jsx("span",{className:"w-7 h-7 rounded-md flex items-center justify-center text-[14px] font-bold leading-none",style:{background:"var(--theme-metal, #c4a35a)",color:"var(--theme-bolt, #2a1808)",boxShadow:"0 1px 2px var(--theme-shadow, rgba(0,0,0,0.3))",fontFamily:"var(--theme-font-display, serif)"},children:"T"}),n.jsx("span",{className:"text-[15px] tracking-[0.18em] font-semibold leading-none",style:{color:"var(--theme-ink, #e8e8ff)"},children:"TITAN"})]}),n.jsx("button",{type:"button",onClick:v,className:"w-6 h-6 rounded-md flex items-center justify-center text-base transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},title:"Hide sidebar","aria-label":"Hide sidebar",children:"‹"})]}),n.jsxs("nav",{className:"flex-1 overflow-y-auto py-3 px-2",children:[n.jsxs("div",{className:"mb-5",children:[n.jsx(qi,{children:"Missions"}),n.jsx(Yi,{onClick:()=>t("/mission"),active:T&&e.pathname==="/mission",icon:"✶",label:"New Mission",title:"Start a new mission or pick a template"}),n.jsx(Yi,{onClick:()=>t("/mission/library"),active:e.pathname==="/mission/library",icon:"❑",label:"Library",title:"Every mission you've run"})]}),n.jsxs("div",{className:"mb-2 flex items-center justify-between px-2",children:[n.jsx(qi,{inline:!0,children:"Workspaces"}),n.jsx("button",{type:"button",onClick:()=>g(!0),className:"w-5 h-5 rounded flex items-center justify-center text-sm leading-none transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-ink, #fff)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},title:"Create a new Workspace","aria-label":"Create a new Workspace",children:"+"})]}),x&&n.jsx("div",{className:"mx-1 my-1 px-2 py-2 text-[11px] rounded",style:{color:"var(--theme-accent, #ef4444)",background:"rgba(239,68,68,0.08)"},children:x}),r.length===0&&!x&&n.jsxs("div",{className:"px-2 py-3 text-[11px] leading-relaxed italic",style:{color:"var(--theme-ink-soft, #71717a)"},children:["No Workspaces yet. Tap + above, or ask TITAN",n.jsx("br",{}),'"make me a workspace for…"']}),r.map(S=>{const C=S.id===o;return n.jsxs("button",{type:"button",onClick:()=>m(S.id),onContextMenu:D=>{D.preventDefault(),_(S.id)},className:"w-full text-left px-2 py-1.5 rounded text-[13px] flex items-center gap-2 transition-colors",style:{background:C?"var(--theme-menu-active-bg, #1f2937)":"transparent",color:C?"var(--theme-menu-active-fg, #fff)":"var(--theme-ink, #d4d4d8)"},onMouseEnter:D=>{C||(D.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))")},onMouseLeave:D=>{C||(D.currentTarget.style.background="transparent")},title:`${S.name} · right-click to archive`,children:[S.icon&&n.jsx("span",{className:"text-base leading-none",children:S.icon}),n.jsx("span",{className:"flex-1 truncate",children:S.name}),S.widgets.length>0&&n.jsx("span",{className:"text-[10px] tabular-nums px-1.5 rounded-full",style:{color:"var(--theme-ink-soft, #71717a)",background:"var(--theme-menu-hover, rgba(244,215,145,0.10))"},children:S.widgets.length})]},S.id)})]}),n.jsxs("div",{className:"px-2 py-2 flex flex-col gap-0.5",style:{borderTop:"1px solid var(--theme-menu-border, #1f2937)"},children:[n.jsxs("a",{href:"/command-post",className:"px-2 py-1.5 rounded text-[12px] flex items-center gap-2 transition-colors no-underline",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-ink, #fff)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},children:[n.jsx("span",{"aria-hidden":!0,children:"⚙"}),n.jsx("span",{children:"Admin"})]}),n.jsxs("button",{type:"button",onClick:()=>{s(),window.location.assign("/")},className:"w-full text-left px-2 py-1.5 rounded text-[12px] flex items-center gap-2 transition-colors",style:{color:"var(--theme-ink-soft, #a1a1aa)"},onMouseEnter:S=>{S.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))",S.currentTarget.style.color="var(--theme-accent, #ef4444)"},onMouseLeave:S=>{S.currentTarget.style.background="transparent",S.currentTarget.style.color="var(--theme-ink-soft, #a1a1aa)"},title:"Sign out — mints a fresh token next login",children:[n.jsx("span",{"aria-hidden":!0,children:"⇥"}),n.jsx("span",{children:"Sign out"})]})]}),p&&n.jsx(_p,{presets:d,creating:u,onCreate:k,onClose:()=>g(!1)})]})}function _p(t){const{presets:e,creating:s,onCreate:r,onClose:i}=t,[o,c]=w.useState(""),[d,l]=w.useState(void 0);return n.jsx("div",{className:"fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4",onClick:i,children:n.jsxs("div",{className:"bg-[#0a0e1a] border border-[#1f2937] rounded-lg p-5 w-full max-w-md",onClick:p=>p.stopPropagation(),children:[n.jsx("div",{className:"text-sm font-medium text-white mb-4",children:"New Space"}),n.jsx("label",{className:"block text-[11px] text-[#a1a1aa] mb-1",children:"Starter preset (optional)"}),n.jsx("div",{className:"grid grid-cols-2 gap-2 mb-4",children:e.map(p=>n.jsxs("button",{type:"button",onClick:()=>{l(p.id),o||c(p.name)},className:`text-left px-3 py-2 rounded border ${d===p.id?"border-[#3b82f6] bg-[#0f172a]":"border-[#1f2937] hover:border-[#374151]"}`,title:p.tagline,children:[n.jsxs("div",{className:"text-sm flex items-center gap-2 text-white",children:[n.jsx("span",{children:p.icon}),n.jsx("span",{children:p.name})]}),n.jsx("div",{className:"text-[10px] text-[#71717a] mt-0.5 line-clamp-1",children:p.tagline})]},p.id))}),n.jsx("label",{className:"block text-[11px] text-[#a1a1aa] mb-1",children:"Name"}),n.jsx("input",{type:"text",value:o,onChange:p=>c(p.target.value),placeholder:"My Workspace",className:"w-full bg-[#0d1117] border border-[#1f2937] rounded px-3 py-2 text-sm text-white mb-4",autoFocus:!0}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:i,className:"px-3 py-1.5 text-sm text-[#a1a1aa] hover:text-white",children:"Cancel"}),n.jsx("button",{type:"button",onClick:()=>r({name:o.trim(),preset:d}),disabled:s||!o.trim()&&!d,className:"px-3 py-1.5 bg-[#3b82f6] hover:bg-[#2563eb] disabled:opacity-50 text-white text-sm rounded",children:s?"Creating…":"Create"})]})]})})}function qi({children:t,inline:e=!1}){return n.jsx("div",{className:`${e?"":"px-2 mb-1.5"} text-[10px] uppercase tracking-[0.18em] font-semibold`,style:{color:"var(--theme-metal, #c4a35a)"},children:t})}function Yi({active:t,icon:e,label:s,title:r,onClick:i}){return n.jsxs("button",{type:"button",onClick:i,className:"w-full text-left px-2 py-1.5 rounded text-[13px] flex items-center gap-2 transition-colors",style:{background:t?"var(--theme-menu-active-bg, #1f2937)":"transparent",color:t?"var(--theme-menu-active-fg, #fff)":"var(--theme-ink, #d4d4d8)"},onMouseEnter:o=>{t||(o.currentTarget.style.background="var(--theme-menu-hover, rgba(244,215,145,0.10))")},onMouseLeave:o=>{t||(o.currentTarget.style.background="transparent")},title:r,children:[n.jsx("span",{className:"w-5 text-center leading-none",style:{color:t?"var(--theme-menu-active-fg, #fff)":"var(--theme-metal, #c4a35a)"},"aria-hidden":!0,children:e}),n.jsx("span",{className:"flex-1 truncate",children:s})]})}const tr=4e3,kp=[{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 Sp({space:t,open:e,onClose:s,onSaved:r}){const[i,o]=w.useState(t.agentInstructions??""),[c,d]=w.useState(!1),[l,p]=w.useState(null),g=w.useRef(null);w.useEffect(()=>{if(e){o(t.agentInstructions??""),p(null);const f=setTimeout(()=>{var x;return(x=g.current)==null?void 0:x.focus()},50);return()=>clearTimeout(f)}},[e,t.id,t.agentInstructions]),w.useEffect(()=>{if(!e)return;const f=x=>{x.key==="Escape"&&s(),x.key==="Enter"&&(x.metaKey||x.ctrlKey)&&u()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e]);const u=w.useCallback(async()=>{if(i.length>tr){p(`Instructions must be ${tr} characters or fewer.`);return}d(!0),p(null);try{const f=i.trim(),x={...t,agentInstructions:f||void 0,updatedAt:new Date().toISOString()};ke.save(x),r==null||r(f),s()}catch(f){p(f.message)}finally{d(!1)}},[i,t,r,s]);return e?n.jsx("div",{className:"fixed inset-0 z-[2147483100] flex items-center justify-center p-4",style:{background:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(4px)"},onClick:s,children:n.jsxs("div",{className:"w-full max-w-2xl rounded-2xl border border-[#27272a] bg-[#0c0c10] shadow-2xl flex flex-col max-h-[85vh]",onClick:f=>f.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fs,{className:"w-4 h-4 text-[#6366f1]"}),n.jsxs("h3",{className:"font-semibold text-white text-sm",children:["Agent instructions — ",n.jsx("span",{style:{color:t.color||"#6366f1"},children:t.name})]})]}),n.jsx("button",{onClick:s,className:"p-1 rounded hover:bg-[#27272a] text-[#71717a] hover:text-white transition-colors",title:"Close (Esc)",children:n.jsx(js,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"p-5 flex-1 overflow-auto space-y-3",children:[n.jsx("p",{className:"text-[11px] text-[#a1a1aa] leading-relaxed",children:"These instructions are injected into the chat’s system prompt whenever this space is active. Use them to give the agent a persona, a rule set, or a focus area — the chat will behave differently here vs. other spaces."}),n.jsx("textarea",{ref:g,value:i,onChange:f=>o(f.target.value),placeholder:"e.g. You're in the research space — prefer concise, sourced answers over widget generation.",spellCheck:!1,className:"w-full h-48 p-3 rounded-lg border border-[#27272a] bg-[#09090c] text-[13px] text-[#e4e4e7] leading-relaxed font-mono resize-y focus:outline-none focus:border-[#6366f1]/60"}),n.jsxs("div",{className:"flex items-center justify-between text-[10px] text-[#71717a]",children:[n.jsxs("span",{children:[i.length.toLocaleString()," / ",tr.toLocaleString()," characters"]}),n.jsx("span",{children:"⌘/Ctrl + Enter to save"})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-[10px] uppercase tracking-wider text-[#71717a] mb-2",children:"Quick presets"}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:kp.map(f=>n.jsxs("button",{onClick:()=>o(f.body),className:"text-left p-3 rounded-lg border border-[#27272a] bg-[#18181b]/60 hover:border-[#6366f1]/50 hover:bg-[#18181b] transition-colors",children:[n.jsx("div",{className:"text-[11px] font-medium text-white mb-1",children:f.label}),n.jsx("div",{className:"text-[10px] text-[#a1a1aa] line-clamp-2 leading-relaxed",children:f.body})]},f.label))})]}),l&&n.jsx("div",{className:"text-[11px] text-[#ef4444] bg-[#ef4444]/10 border border-[#ef4444]/30 rounded p-2",children:l})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-[#27272a]",children:[n.jsx("button",{onClick:s,className:"px-3 py-1.5 rounded-lg text-[12px] text-[#a1a1aa] hover:text-white hover:bg-[#18181b] transition-colors",children:"Cancel"}),n.jsxs("button",{onClick:()=>{u()},disabled:c,className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-lg bg-[#6366f1] hover:bg-[#4f46e5] disabled:opacity-60 text-white text-[12px] font-medium transition-colors",children:[n.jsx(mn,{className:"w-3.5 h-3.5"}),c?"Saving…":"Save"]})]})]})}):null}const jp=12,Ep=["react","vanilla","html"];function Np({widget:t,spaceId:e,open:s,onClose:r,onSaved:i}){const[o,c]=w.useState(t.source),[d,l]=w.useState(t.format),[p,g]=w.useState(t.name),[u,f]=w.useState(!1),[x,y]=w.useState(null),[E,L]=w.useState(!1),v=w.useRef(null);w.useEffect(()=>{if(s){c(t.source),l(t.format),g(t.name),y(null),L(!1);const T=setTimeout(()=>{var S;return(S=v.current)==null?void 0:S.focus()},50);return()=>clearTimeout(T)}},[s,t.id,t.source,t.format,t.name]),w.useEffect(()=>{if(!s)return;const T=S=>{S.key==="Escape"&&r(),S.key==="Enter"&&(S.metaKey||S.ctrlKey)&&A()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[s]);const A=w.useCallback(async()=>{f(!0),y(null);try{const T=o!==t.source||d!==t.format,S=Array.isArray(t.versions)?t.versions:[],C=T?[...S,{source:t.source,format:t.format,savedAt:t.updatedAt}].slice(-jp):S,D={name:p.trim()||t.name,source:o,format:d,versions:C};ke.updateWidget(e,t.id,D),i==null||i({...t,...D,updatedAt:Date.now()}),r()}catch(T){y(T.message)}finally{f(!1)}},[o,d,p,t,e,i,r]),m=w.useCallback(T=>{c(T.source),l(T.format),L(!1)},[]);if(!s)return null;const k=Array.isArray(t.versions)?t.versions:[],_=[...k].reverse();return n.jsx("div",{className:"fixed inset-0 z-[2147483200] flex items-center justify-center p-4",style:{background:"rgba(0, 0, 0, 0.66)",backdropFilter:"blur(4px)"},onClick:r,children:n.jsxs("div",{className:"w-full max-w-4xl rounded-2xl border border-[#27272a] bg-[#0c0c10] shadow-2xl flex flex-col",style:{height:"min(720px, 85vh)"},onClick:T=>T.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(Fl,{className:"w-4 h-4 text-[#6366f1] shrink-0"}),n.jsx("input",{value:p,onChange:T=>g(T.target.value),className:"bg-transparent text-white text-sm font-semibold outline-none border-b border-transparent focus:border-[#6366f1]/60 min-w-0 flex-1"}),n.jsx("span",{className:"text-[10px] font-mono text-[#52525b] shrink-0",children:t.id.slice(0,14)})]}),n.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[n.jsx("button",{onClick:()=>L(T=>!T),disabled:k.length===0,className:`p-1.5 rounded text-[#a1a1aa] hover:bg-[#18181b] hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${E?"bg-[#18181b] text-white":""}`,title:k.length===0?"No history yet":`${k.length} prior version${k.length===1?"":"s"}`,children:n.jsx(tc,{className:"w-4 h-4"})}),n.jsx("button",{onClick:r,className:"p-1.5 rounded text-[#71717a] hover:bg-[#18181b] hover:text-white transition-colors",title:"Close (Esc)",children:n.jsx(js,{className:"w-4 h-4"})})]})]}),n.jsxs("div",{className:"flex items-center gap-3 px-5 py-2 border-b border-[#27272a] text-[11px]",children:[n.jsxs("label",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-[#71717a]",children:"format"}),n.jsx("select",{value:d,onChange:T=>l(T.target.value),className:"bg-[#18181b] border border-[#27272a] rounded px-2 py-0.5 text-[#e4e4e7] focus:outline-none focus:border-[#6366f1]/60",children:Ep.map(T=>n.jsx("option",{value:T,children:T},T))})]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("span",{className:"text-[#71717a]",children:["updated ",n.jsx("span",{className:"text-[#a1a1aa]",children:new Date(t.updatedAt).toLocaleString()})]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("span",{className:"text-[#71717a]",children:[t.w," × ",t.h," grid cells"]}),n.jsx("div",{className:"ml-auto text-[10px] text-[#52525b]",children:"⌘/Ctrl + Enter to save"})]}),n.jsxs("div",{className:"flex-1 flex min-h-0",children:[n.jsx("textarea",{ref:v,value:o,onChange:T=>c(T.target.value),spellCheck:!1,className:"flex-1 p-4 bg-[#09090c] text-[12.5px] text-[#e4e4e7] leading-relaxed font-mono resize-none focus:outline-none border-r border-[#27272a]",placeholder:Cp[d]}),E&&n.jsxs("div",{className:"w-72 flex flex-col border-l border-[#27272a] bg-[#0a0a0e]",children:[n.jsxs("div",{className:"px-3 py-2 border-b border-[#27272a] text-[10px] uppercase tracking-wider text-[#71717a]",children:["History (",k.length,")"]}),n.jsxs("div",{className:"flex-1 overflow-auto",children:[_.length===0&&n.jsx("div",{className:"p-3 text-[11px] text-[#52525b]",children:"No prior versions yet — save to start tracking."}),_.map((T,S)=>n.jsxs("div",{className:"px-3 py-2 border-b border-[#18181b] hover:bg-[#18181b]/40 transition-colors",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[n.jsx("div",{className:"text-[10px] font-mono text-[#a1a1aa]",children:new Date(T.savedAt).toLocaleString()}),n.jsxs("button",{onClick:()=>m(T),className:"inline-flex items-center gap-1 text-[10px] text-[#6366f1] hover:text-[#a5b4fc] transition-colors",title:"Load this version into the editor",children:[n.jsx(oo,{className:"w-3 h-3"}),"revert"]})]}),n.jsxs("div",{className:"text-[10px] text-[#71717a] font-mono",children:["format: ",T.format]}),n.jsxs("div",{className:"text-[10px] text-[#52525b] truncate mt-1",title:T.source.slice(0,280),children:[T.source.slice(0,80),T.source.length>80?"…":""]}),S===0&&n.jsx("div",{className:"text-[9px] text-[#6366f1] mt-1",children:"most recent before current"})]},T.savedAt))]})]})]}),n.jsxs("div",{className:"flex items-center justify-between gap-2 px-5 py-3 border-t border-[#27272a]",children:[n.jsx("div",{className:"text-[10px] text-[#71717a]",children:x?n.jsxs("span",{className:"text-[#ef4444]",children:["Error: ",x]}):o!==t.source||d!==t.format||p!==t.name?"Unsaved changes":"Up to date"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:r,className:"px-3 py-1.5 rounded-lg text-[12px] text-[#a1a1aa] hover:text-white hover:bg-[#18181b] transition-colors",children:"Cancel"}),n.jsxs("button",{onClick:()=>{A()},disabled:u,className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-lg bg-[#6366f1] hover:bg-[#4f46e5] disabled:opacity-60 text-white text-[12px] font-medium transition-colors",children:[n.jsx(mn,{className:"w-3.5 h-3.5"}),u?"Saving…":"Save widget"]})]})]})]})})}const Cp={react:`// Return a React component named "Widget". titan.* APIs are
957
957
  // available for fetch/api/state. Example:
958
958
  function Widget({ titan }) {
959
959
  const [n, setN] = React.useState(0);
@@ -965,8 +965,8 @@ function Widget({ titan }) {
965
965
  const btn = container.querySelector('button');
966
966
  btn.addEventListener('click', () => btn.textContent = 'Clicked!');
967
967
  }`,html:`<!-- Raw HTML. No scripts run. -->
968
- <div style="padding:16px;color:#e4e4e7">Hello, widget!</div>`,iframe:"",system:""};function Np(t){return String(t||"").startsWith("system:")?"system":"react"}const 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 Rp({open:t,onClose:e}){const[s,r]=w.useState([]),[i,o]=w.useState([]),[c,d]=w.useState("All"),[l,p]=w.useState(""),[g,u]=w.useState(null),[f,x]=w.useState(!1),[y,E]=w.useState(null);w.useEffect(()=>{t&&(x(!0),ge("/api/widget-gallery").then(m=>m.json()).then(m=>{r(m.templates||[]),o(m.categories||[]),x(!1)}).catch(m=>{E(m.message),x(!1)}))},[t]),w.useEffect(()=>{if(!t)return;const m=k=>{k.key==="Escape"&&e()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,e]);const I=w.useMemo(()=>{const m=c==="All"?s:s.filter(_=>_.category===c),k=l.trim().toLowerCase();return k?m.filter(_=>[_.name,_.description,_.category,..._.tags||[],..._.triggers||[]].join(" ").toLowerCase().includes(k)):m},[c,l,s]);if(!t)return null;const v=async m=>{var k,_,T,S;u(m.id),E(null);try{const C=await ge(`/api/widget-gallery/${encodeURIComponent(m.id)}`);if(!C.ok)throw new Error(`Could not load template (${C.status})`);const D=await C.json(),j={templateId:m.id,templateName:D.name||m.name,source:D.source,format:Np(D.source),defaultSize:{w:((k=D.defaultSize)==null?void 0:k.w)??((_=m.defaultSize)==null?void 0:_.w)??4,h:((T=D.defaultSize)==null?void 0:T.h)??((S=m.defaultSize)==null?void 0:S.h)??4}};window.dispatchEvent(new CustomEvent("titan:gallery:run-template",{detail:j})),e()}catch(C){E(C.message)}finally{u(null)}},A=["All",...i.map(m=>m.category)];return n.jsx("div",{className:"fixed inset-0 z-[2147483150] flex items-center justify-center p-4 titan-menu-overlay",onClick:e,children:n.jsxs("div",{className:"w-full max-w-4xl titan-modal-surface flex flex-col",style:{height:"min(720px, 90vh)",borderRadius:12},onClick:m=>m.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3",style:{borderBottom:"1px solid var(--theme-menu-border)"},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Er,{className:"w-4 h-4",style:{color:"var(--theme-accent)"}}),n.jsx("h3",{className:"font-semibold text-sm",style:{color:"var(--theme-ink)",fontFamily:"var(--theme-font-display)"},children:"Widget gallery"}),n.jsx("span",{className:"text-[10px]",style:{color:"var(--theme-ink-soft)"},children:f?"Loading…":`${s.length} templates`})]}),n.jsx("button",{onClick:e,className:"titan-close-btn",title:"Close (Esc)","aria-label":"Close",children:n.jsx(js,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"flex items-center gap-1.5 px-5 py-2 border-b border-[#27272a] text-[11px] overflow-x-auto",children:A.map(m=>{var k;return n.jsxs("button",{onClick:()=>d(m),className:`px-2.5 py-1 rounded-full border transition-colors whitespace-nowrap ${c===m?"border-[#6366f1] bg-[#6366f1]/15 text-white":"border-[#27272a] bg-transparent text-[#a1a1aa] hover:border-[#3f3f46] hover:text-white"}`,children:[Tp(m),m!=="All"&&n.jsx("span",{className:"ml-1.5 text-[9px] opacity-70",children:((k=i.find(_=>_.category===m))==null?void 0:k.count)??0})]},m)})}),n.jsx("div",{className:"px-5 py-2 border-b border-[#27272a]",children:n.jsxs("label",{className:"flex items-center gap-2 rounded-lg border border-[#27272a] bg-[#18181b]/60 px-3 py-2",children:[n.jsx(oo,{className:"w-3.5 h-3.5 text-[#71717a]"}),n.jsx("input",{value:l,onChange:m=>p(m.target.value),placeholder:"Search templates...",className:"flex-1 bg-transparent text-xs text-white placeholder:text-[#71717a] outline-none"})]})}),n.jsxs("div",{className:"flex-1 overflow-auto p-4",children:[f&&n.jsx("div",{className:"flex items-center justify-center h-full text-[#a1a1aa] text-sm",children:"Loading templates…"}),y&&n.jsxs("div",{className:"flex items-center justify-center h-full text-[#f87171] text-sm",children:["Error: ",y]}),!f&&!y&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:I.map(m=>n.jsxs("button",{onClick:()=>v(m),disabled:g!==null,className:"text-left p-3 rounded-lg border border-[#27272a] bg-[#18181b]/60 hover:border-[#6366f1]/50 hover:bg-[#18181b] transition-colors group",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{background:Cp[m.category]??"#9ca3af"}}),n.jsx("span",{className:"text-[12px] font-medium text-white truncate",children:m.name})]}),n.jsx(ao,{className:"w-3 h-3 text-[#52525b] group-hover:text-[#a5b4fc] transition-colors shrink-0"})]}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] leading-relaxed line-clamp-2",children:g===m.id?"Adding to canvas...":m.description}),m.tags&&m.tags.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:m.tags.slice(0,3).map(k=>n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-[#27272a] text-[#71717a]",children:k},k))})]},m.id))}),I.length===0&&n.jsx("div",{className:"flex items-center justify-center h-40 text-[#a1a1aa] text-sm",children:"No templates in this category."})]}),n.jsxs("div",{className:"mt-4 p-3 rounded-lg border border-dashed border-[#27272a] bg-[#0a0a0e] flex items-start gap-2",children:[n.jsx(yo,{className:"w-3.5 h-3.5 text-[#71717a] mt-0.5 shrink-0"}),n.jsxs("div",{className:"text-[11px] text-[#a1a1aa] leading-relaxed",children:["Don’t see what you want? Open the chat (click the mascot) and describe your widget in plain English. TITAN can build anything that runs inside a sandboxed iframe with access to ",n.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.fetch"}),","," ",n.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.api.call"}),", and"," ",n.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.state"}),"."]})]})]})]})})}const Ap=[{type:"widget",source:"system:nav",name:"Nav Widget",w:3,h:4,icon:n.jsx(yo,{className:"w-4 h-4"})},{type:"widget",source:"system:chat",name:"Chat Widget",w:4,h:5,icon:n.jsx(lo,{className:"w-4 h-4"})},{type:"widget",source:"system:soma",name:"SOMA",w:6,h:6,icon:n.jsx(yt,{className:"w-4 h-4"})},{type:"widget",source:"system:command-post",name:"Command Post",w:8,h:6,icon:n.jsx(ro,{className:"w-4 h-4"})},{type:"widget",source:"system:intelligence",name:"Intelligence",w:6,h:5,icon:n.jsx(no,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-graph",name:"Memory Graph",w:8,h:7,icon:n.jsx(ql,{className:"w-4 h-4"})},{type:"widget",source:"system:voice",name:"Voice",w:5,h:5,icon:n.jsx(co,{className:"w-4 h-4"})},{type:"widget",source:"system:infra",name:"Infrastructure",w:6,h:4,icon:n.jsx(Rr,{className:"w-4 h-4"})},{type:"widget",source:"system:tools",name:"Tools",w:5,h:4,icon:n.jsx(jr,{className:"w-4 h-4"})},{type:"widget",source:"system:settings",name:"Settings",w:5,h:5,icon:n.jsx(Sr,{className:"w-4 h-4"})},{type:"widget",source:"system:files",name:"Files",w:4,h:6,icon:n.jsx(pn,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-wiki",name:"Memory Wiki",w:6,h:6,icon:n.jsx(fs,{className:"w-4 h-4"})},{type:"widget",source:"system:autoresearch",name:"Autoresearch",w:6,h:6,icon:n.jsx(uo,{className:"w-4 h-4"})},{type:"widget",source:"system:self-proposals",name:"Self-Proposals",w:6,h:6,icon:n.jsx(go,{className:"w-4 h-4"})},{type:"widget",source:"system:overview",name:"Overview",w:6,h:5,icon:n.jsx(eo,{className:"w-4 h-4"})},{type:"widget",source:"system:sessions",name:"Sessions",w:6,h:5,icon:n.jsx(ps,{className:"w-4 h-4"})},{type:"widget",source:"system:watch",name:"Watch",w:8,h:7,icon:n.jsx(Vt,{className:"w-4 h-4"})},{type:"widget",source:"system:backup",name:"Backup Manager",w:6,h:6,icon:n.jsx(ho,{className:"w-4 h-4"})},{type:"widget",source:"system:training",name:"Training Dashboard",w:6,h:6,icon:n.jsx(yt,{className:"w-4 h-4"})},{type:"widget",source:"system:recipes",name:"Recipe Kitchen",w:6,h:6,icon:n.jsx(fs,{className:"w-4 h-4"})},{type:"widget",source:"system:vram",name:"VRAM Monitor",w:6,h:6,icon:n.jsx(Nr,{className:"w-4 h-4"})},{type:"widget",source:"system:teams",name:"Team Hub",w:6,h:6,icon:n.jsx(Cr,{className:"w-4 h-4"})},{type:"widget",source:"system:cron",name:"Cron Scheduler",w:6,h:6,icon:n.jsx(ps,{className:"w-4 h-4"})},{type:"widget",source:"system:checkpoints",name:"Checkpoints",w:6,h:5,icon:n.jsx(mn,{className:"w-4 h-4"})},{type:"widget",source:"system:organism",name:"Organism Monitor",w:6,h:6,icon:n.jsx(Tr,{className:"w-4 h-4"})},{type:"widget",source:"system:fleet",name:"Fleet Router",w:6,h:5,icon:n.jsx(fo,{className:"w-4 h-4"})},{type:"widget",source:"system:browser",name:"Browser Tools",w:6,h:5,icon:n.jsx(to,{className:"w-4 h-4"})},{type:"widget",source:"system:eval",name:"Test Lab",w:6,h:6,icon:n.jsx(po,{className:"w-4 h-4"})}];function bl({currentSpaceId:t,onSpaceSelect:e,onAction:s,onClose:r}){const[i,o]=w.useState(""),[c,d]=w.useState(0),l=w.useRef(null),p=ke.list(),g=w.useMemo(()=>{const u=i.toLowerCase(),f=p.filter(y=>y.id!==t&&y.name.toLowerCase().includes(u)).map(y=>({type:"space",id:y.id,name:y.name,color:y.color})),x=Ap.filter(y=>y.name.toLowerCase().includes(u)).map(y=>({type:"action",action:y,name:y.name}));return[...f,...x]},[i,p,t]);return w.useEffect(()=>{var u;(u=l.current)==null||u.focus()},[]),w.useEffect(()=>{d(0)},[i]),w.useEffect(()=>{const u=f=>{if((f.metaKey||f.ctrlKey)&&f.key.toLowerCase()==="k"){f.preventDefault(),r();return}if(f.key==="Escape"){r();return}if(f.key==="ArrowDown"){f.preventDefault(),d(x=>Math.min(x+1,g.length-1));return}if(f.key==="ArrowUp"){f.preventDefault(),d(x=>Math.max(x-1,0));return}if(f.key==="Enter"){f.preventDefault();const x=g[c];if(!x)return;x.type==="space"&&e(x.id),x.type==="action"&&s(x.action)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[g,c,e,s,r]),n.jsx("div",{className:"fixed inset-0 z-[2147483200] flex items-start justify-center pt-[20vh]",onClick:r,children:n.jsxs("div",{className:"w-full max-w-lg bg-[#18181b]/98 backdrop-blur-xl border border-[#27272a]/60 rounded-2xl shadow-2xl shadow-black/60 overflow-hidden",onClick:u=>u.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#27272a]/40",children:[n.jsx(oo,{className:"w-4 h-4 text-[#3f3f46]"}),n.jsx("input",{ref:l,value:i,onChange:u=>o(u.target.value),placeholder:"Search spaces, widgets, actions...",className:"flex-1 bg-transparent text-sm text-[#e4e4e7] placeholder:text-[#3f3f46] outline-none"}),n.jsx("button",{onClick:r,className:"text-[#3f3f46] hover:text-[#71717a]",children:n.jsx(js,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"max-h-[50vh] overflow-auto py-1",children:[g.length===0&&n.jsxs("div",{className:"px-4 py-6 text-center text-xs text-[#52525b]",children:['No results for "',i,'"']}),g.map((u,f)=>n.jsxs("button",{onClick:()=>{u.type==="space"&&e(u.id),u.type==="action"&&s(u.action)},className:`w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors ${f===c?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#a1a1aa] hover:bg-[#27272a]/30"}`,children:[u.type==="space"?n.jsx("div",{className:"w-4 h-4 rounded-full",style:{background:u.color||"#52525b"}}):n.jsx("span",{className:"text-[#6366f1]/60",children:u.action.icon}),n.jsx("span",{className:"text-sm",children:u.name}),n.jsx("span",{className:"ml-auto text-[10px] text-[#3f3f46] uppercase tracking-wider",children:u.type==="space"?"Space":"Widget"})]},u.type==="space"?u.id:u.action.source))]}),n.jsxs("div",{className:"px-4 py-2 border-t border-[#27272a]/40 flex items-center gap-3 text-[10px] text-[#3f3f46]",children:[n.jsx("span",{children:"↑↓ Navigate"}),n.jsx("span",{children:"↵ Select"}),n.jsx("span",{children:"ESC Close"})]})]})})}const Lp=oe.lazy(()=>le(()=>import("./SomaView-CzZ6SCuw.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),Ae={bgBase:"var(--theme-bg-base, var(--color-bg, #09090b))",surface:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-secondary, #18181b)) 82%, transparent)",surfaceSoft:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-tertiary, #27272a)) 62%, transparent)",border:"color-mix(in srgb, var(--theme-metal-dark, var(--color-border, #3f3f46)) 66%, transparent)",ink:"var(--theme-paper-fg, var(--color-text, #fafafa))",inkSoft:"color-mix(in srgb, var(--theme-paper-fg, var(--color-text-secondary, #a1a1aa)) 72%, transparent)",paperFg:"var(--theme-paper-fg, var(--color-text-secondary, #a1a1aa))",accent:"var(--theme-accent, var(--color-accent, #6366f1))",success:"var(--color-success, #22c55e)",error:"var(--color-error, #ef4444)"},sr={background:Ae.bgBase,color:Ae.ink};function xl(){const[t,e]=w.useState(null),[s,r]=w.useState(!1),[i,o]=w.useState(null),c=w.useCallback(async()=>{var p;try{const g=await ge("/api/config");if(!g.ok)throw new Error(`HTTP ${g.status}`);const u=await g.json();e(!!((p=u==null?void 0:u.organism)!=null&&p.enabled)),o(null)}catch(g){o(g.message),e(!1)}},[]);w.useEffect(()=>{c()},[c]);const d=w.useRef(0),l=w.useCallback(async p=>{const g=++d.current;r(!0),o(null);try{const u=await ge("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:{enabled:p}})});if(g!==d.current)return;if(!u.ok)throw new Error(`HTTP ${u.status}`);e(p),window.dispatchEvent(new CustomEvent("titan:soma:changed",{detail:{enabled:p}}))}catch(u){if(g!==d.current)return;o(u.message)}finally{g===d.current&&r(!1)}},[]);return t===null?n.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs",style:{...sr,color:Ae.paperFg},children:"Loading Soma…"}):t?n.jsxs("div",{className:"w-full h-full overflow-auto flex flex-col",style:sr,children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b",style:{background:Ae.surface,borderColor:Ae.border},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full animate-pulse",style:{background:Ae.success}}),n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:Ae.success},children:"Soma active"})]}),n.jsxs("button",{onClick:()=>l(!1),disabled:s,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[10px] disabled:opacity-60 transition-colors",style:{borderColor:Ae.border,color:Ae.inkSoft,background:Ae.surfaceSoft},title:"Disable Soma",children:[n.jsx(di,{className:"w-3 h-3"}),s?"saving…":"disable"]})]}),n.jsx("div",{className:"flex-1 overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs",style:{color:Ae.paperFg},children:"Loading Soma dashboard…"}),children:n.jsx(Lp,{})})})]}):n.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-4 p-6 text-center",style:sr,children:[n.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center",style:{background:"color-mix(in srgb, var(--theme-accent, var(--color-accent, #6366f1)) 18%, transparent)",border:`1px solid ${Ae.border}`},children:n.jsx(Vt,{className:"w-7 h-7",style:{color:Ae.accent}})}),n.jsxs("div",{className:"space-y-1 max-w-md",children:[n.jsx("h3",{className:"text-lg font-semibold",style:{color:Ae.ink},children:"Soma is off"}),n.jsx("p",{className:"text-xs leading-relaxed",style:{color:Ae.inkSoft},children:"TITAN’s homeostatic drive layer. When enabled, TITAN has a sense of its own state — purpose, curiosity, hunger, safety, social, rest — and will propose work when those drives drift. Every proposal still requires your approval."})]}),n.jsxs("button",{onClick:()=>l(!0),disabled:s,className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-full disabled:opacity-60 disabled:cursor-not-allowed text-sm font-medium transition-colors",style:{background:Ae.accent,color:"var(--theme-bg-base, var(--color-bg, #09090b))"},children:[n.jsx(di,{className:"w-4 h-4"}),s?"Enabling…":"Enable Soma"]}),i&&n.jsx("p",{className:"text-xs",style:{color:Ae.error},children:i}),n.jsx("p",{className:"text-[10px]",style:{color:Ae.paperFg},children:"You can turn this off anytime from the same button."})]})}const 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)"}},Ee={surface:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-secondary, #18181b)) 90%, transparent)",surfaceSoft:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-tertiary, #27272a)) 62%, transparent)",overlay:"color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 56%, transparent)",border:"color-mix(in srgb, var(--theme-metal-dark, var(--color-border, #3f3f46)) 66%, transparent)",metal:"var(--theme-metal, var(--color-border-light, #52525b))",ink:"var(--theme-paper-fg, var(--color-text, #fafafa))",accent:"var(--theme-accent, var(--color-accent, #6366f1))",warning:"var(--color-warning, #f59e0b)"};function Dp(t,e,s){if(!s)return{emotion:"dreaming",intensity:.25,activity:"Dormant"};const r=e[0],i=Math.min(1,t/2);switch(r){case"purpose":return{emotion:"focused",intensity:.4+i*.4,activity:"Pursuing purpose"};case"curiosity":return{emotion:"excited",intensity:.4+i*.5,activity:"Exploring"};case"hunger":return{emotion:"focused",intensity:.5+i*.3,activity:"Satiating"};case"safety":return{emotion:"concerned",intensity:.5+i*.4,activity:"Securing"};case"social":return{emotion:"calm",intensity:.3+i*.3,activity:"Connecting"};case"rest":return{emotion:"dreaming",intensity:.2+i*.2,activity:"Recuperating"};default:return t>.5?{emotion:"focused",intensity:i,activity:"Processing"}:{emotion:"calm",intensity:.3,activity:"Observing"}}}function Mp(){const[t,e]=w.useState(!1),[s,r]=w.useState({emotion:"calm",intensity:.3,activity:"Observing"}),[i,o]=w.useState(!1),[c,d]=w.useState({x:280,y:80}),[l,p]=w.useState(!1),g=w.useRef({x:0,y:0}),u=w.useRef(null);w.useEffect(()=>{let v=!1;const A=async()=>{try{const k=await ge("/api/soma/state");if(!k.ok||v)return;const _=await k.json();if(v)return;r(Dp(Number((_==null?void 0:_.totalPressure)??0),Array.isArray(_==null?void 0:_.dominantDrives)?_.dominantDrives:[],!!(_!=null&&_.enabled)))}catch{}};A();const m=setInterval(A,15e3);return()=>{v=!0,clearInterval(m)}},[]),w.useEffect(()=>{const v=A=>{var m;(m=u.current)!=null&&m.contains(A.target)||o(!1)};return window.addEventListener("mousedown",v),()=>window.removeEventListener("mousedown",v)},[]);const f=v=>{v.button===0&&(g.current={x:v.clientX-c.x,y:v.clientY-c.y},p(!0))},x=v=>{l&&d({x:v.clientX-g.current.x,y:v.clientY-g.current.y})},y=()=>{p(!1)},E=Ip[s.emotion],I=s.activity==="Dormant"?Ee.metal:Ee.accent;return n.jsxs(n.Fragment,{children:[t&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center backdrop-blur-sm",style:{background:Ee.overlay},onClick:()=>e(!1),children:n.jsxs("div",{className:"border rounded-2xl shadow-2xl overflow-hidden",style:{width:"min(900px, 90vw)",height:"min(600px, 80vh)",background:Ee.surface,borderColor:Ee.border,color:Ee.ink,boxShadow:"0 24px 64px color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 72%, transparent)"},onClick:v=>v.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b",style:{borderColor:Ee.border},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(yt,{className:"w-4 h-4",style:{color:I}}),n.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",style:{color:Ee.ink},children:"SOMA Consciousness"})]}),n.jsx("button",{onClick:()=>e(!1),className:"p-1",style:{color:Ee.metal},children:n.jsx(js,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"h-[calc(100%-40px)]",children:n.jsx(xl,{})})]})}),n.jsxs("div",{ref:u,className:"fixed z-50 select-none",style:{left:c.x,top:c.y},onMouseDown:f,onMouseMove:x,onMouseUp:y,onMouseLeave:y,children:[i&&n.jsxs("div",{className:"absolute bottom-full left-0 mb-2 backdrop-blur-xl border rounded-xl shadow-2xl overflow-hidden min-w-[160px] py-1",style:{background:Ee.surface,borderColor:Ee.border,boxShadow:"0 18px 40px color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 70%, transparent)"},children:[n.jsxs("button",{onClick:()=>{e(!0),o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(yt,{className:"w-3.5 h-3.5",style:{color:I}}),"Open SOMA"]}),n.jsxs("button",{onClick:()=>{o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(Er,{className:"w-3.5 h-3.5",style:{color:Ee.warning}}),"Summarize Canvas"]}),n.jsxs("button",{onClick:()=>{o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(Cl,{className:"w-3.5 h-3.5",style:{color:Ee.accent}}),"Run Self-Check"]})]}),n.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>!l&&e(!0),onContextMenu:v=>{v.preventDefault(),o(!0)},children:[n.jsx("div",{className:"absolute inset-0 rounded-full animate-ping opacity-20",style:{background:E.pulse,animationDuration:`${3-s.intensity*2}s`}}),n.jsx("div",{className:"absolute -inset-2 rounded-full opacity-30 blur-md transition-all duration-1000",style:{background:E.glow}}),n.jsx("div",{className:"relative w-12 h-12 rounded-full flex items-center justify-center transition-all duration-500 hover:scale-110",style:{background:`radial-gradient(circle at 30% 30%, ${I}, ${Ee.metal})`,boxShadow:`0 0 ${20+s.intensity*30}px ${E.glow}, inset 0 0 10px color-mix(in srgb, var(--theme-ink, var(--color-text, #fafafa)) 12%, transparent)`},children:n.jsx(yt,{className:"w-5 h-5",style:{color:Ee.ink}})}),n.jsx("div",{className:"absolute -bottom-5 left-1/2 -translate-x-1/2 whitespace-nowrap",children:n.jsx("span",{className:"text-[9px] font-medium uppercase tracking-wider px-1.5 py-0.5 rounded border",style:{color:Ee.ink,background:Ee.surfaceSoft,borderColor:Ee.border},children:s.activity})})]})]})]})}const Op=oe.lazy(()=>le(()=>import("./CommandPostHub-Ckh7LlWG.js"),__vite__mapDeps([7,1,2,3,4,8,9,10,11,12,5,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28])));function Pp(){return n.jsx("div",{className:"w-full h-full overflow-auto p-2",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Command Post..."}),children:n.jsx(Op,{})})})}const Wp=oe.lazy(()=>le(()=>import("./IntelligenceView-CJ2r76hu.js"),__vite__mapDeps([29,1,2,4])));function Bp(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Intelligence..."}),children:n.jsx(Wp,{})})})}const Up=oe.lazy(()=>le(()=>import("./MemoryGraphPanel-DZTQIsys.js"),__vite__mapDeps([30,1,2,31,24,28,32])));function Fp(){return n.jsx("div",{className:"w-full h-full overflow-auto bg-[#09090b]",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"h-full flex items-center justify-center",children:n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-[#6366f1]/20 border-t-[#6366f1] animate-spin mx-auto mb-3"}),n.jsx("p",{className:"text-[11px] text-[#52525b]",children:"Loading memory graph..."})]})}),children:n.jsx("div",{className:"p-4",children:n.jsx(Up,{})})})})}function $p(){const[t,e]=w.useState(!1);return t?n.jsx(Bl,{onClose:()=>e(!1)}):n.jsx("div",{className:"w-full h-full flex flex-col items-center justify-center bg-[#09090b]",children:n.jsxs("button",{onClick:()=>e(!0),className:"group relative flex flex-col items-center gap-4",children:[n.jsxs("div",{className:"relative w-20 h-20 rounded-full flex items-center justify-center transition-all duration-300 group-hover:scale-110",children:[n.jsx("div",{className:"absolute inset-0 rounded-full bg-[#6366f1]/20 animate-pulse"}),n.jsx("div",{className:"absolute inset-0 rounded-full bg-gradient-to-br from-[#6366f1]/30 to-[#4f46e5]/10 border border-[#6366f1]/30"}),n.jsx(co,{className:"w-8 h-8 text-[#818cf8] relative z-10"})]}),n.jsxs("div",{className:"text-center",children:[n.jsx("p",{className:"text-sm font-medium text-[#a1a1aa]",children:"Tap to speak"}),n.jsx("p",{className:"text-[10px] text-[#52525b] mt-1",children:"F5-TTS · Voice Cloning"})]})]})})}const zp=oe.lazy(()=>le(()=>import("./InfraView-DAwJClAs.js"),__vite__mapDeps([33,1,2,4])));function Hp(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Infrastructure..."}),children:n.jsx(zp,{})})})}const Vp=oe.lazy(()=>le(()=>import("./ToolsView-C3m7TbnX.js"),__vite__mapDeps([34,1,2,4])));function Gp(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Tools..."}),children:n.jsx(Vp,{})})})}const qp=oe.lazy(()=>le(()=>import("./SettingsView-ByyjhwLz.js"),__vite__mapDeps([35,1,2,4])));function Yp(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Settings..."}),children:n.jsx(qp,{})})})}function Kp(){const[t,e]=w.useState([]),[s,r]=w.useState("/"),[i,o]=w.useState(!1),[c,d]=w.useState(null),l=async()=>{o(!0),d(null);try{const p=await ge(`/api/files?path=${encodeURIComponent(s)}`);if(p.ok){const g=await p.json();e(g.files||[])}else e([]),d(`Couldn't load files (HTTP ${p.status})`)}catch(p){e([]),d(`Couldn't reach /api/files — ${p.message}`)}finally{o(!1)}};return w.useEffect(()=>{l()},[s]),n.jsxs("div",{className:"w-full h-full flex flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-[#27272a]/40",children:[n.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-[#71717a]",children:[n.jsx("span",{className:"text-[#6366f1]",children:"~"}),n.jsx(Ul,{className:"w-3 h-3"}),n.jsx("span",{children:s})]}),n.jsx("button",{onClick:l,className:"p-1 text-[#3f3f46] hover:text-[#71717a]",children:n.jsx(gn,{className:`w-3 h-3 ${i?"animate-spin":""}`})})]}),n.jsxs("div",{className:"flex-1 overflow-auto",children:[c&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#ef4444]/80",children:c}),!c&&!i&&t.length===0&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#52525b]",children:"No files"}),t.map(p=>n.jsxs("button",{onClick:()=>p.type==="directory"&&r(p.path),className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-[#27272a]/20 transition-colors",children:[p.type==="directory"?n.jsx(Fl,{className:"w-3.5 h-3.5 text-[#f59e0b]"}):n.jsx(pn,{className:"w-3.5 h-3.5 text-[#6366f1]"}),n.jsx("span",{className:"text-[12px] text-[#a1a1aa]",children:p.name})]},p.path))]})]})}const Jp=oe.lazy(()=>le(()=>import("./SettingsPanel-CmIAAw_T.js"),__vite__mapDeps([36,1,2,3,4,37,14,5,38,39,24,40,41,42,43])));function Xp(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Jp,{})})})}const Qp=oe.lazy(()=>le(()=>import("./SecurityPanel-DRZu6PRV.js"),__vite__mapDeps([44,1,2,37,14])));function Zp(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Qp,{})})})}const em=oe.lazy(()=>le(()=>import("./AuditPanel-6hTX-30T.js"),__vite__mapDeps([45,1,2,46,24,47])));function tm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(em,{})})})}const Yi={researcher:"#60a5fa",engineer:"#f87171",manager:"#a78bfa",ceo:"#fbbf24",general:"#9ca3af"},sm={Recommended:"bg-[#10b981]/15 text-[#10b981] border-[#10b981]/30",Reasoning:"bg-[#8b5cf6]/15 text-[#8b5cf6] border-[#8b5cf6]/30",Fast:"bg-[#0ea5e9]/15 text-[#0ea5e9] border-[#0ea5e9]/30",Light:"bg-[#f59e0b]/15 text-[#f59e0b] border-[#f59e0b]/30","Long Context":"bg-[#6366f1]/15 text-[#6366f1] border-[#6366f1]/30","High Output":"bg-[#ec4899]/15 text-[#ec4899] border-[#ec4899]/30","Needs Key":"bg-[#ef4444]/15 text-[#ef4444] border-[#ef4444]/30"};function nm(){const[t,e]=w.useState(null),[s,r]=w.useState({}),[i,o]=w.useState({}),[c,d]=w.useState(null),[l,p]=w.useState({}),[g,u]=w.useState(!0),f=w.useCallback(async()=>{d(null);try{const[E,I]=await Promise.all([ge("/api/specialists"),ge("/api/models")]);if(!E.ok)throw new Error(`Specialists request failed: ${E.status}`);if(!I.ok)throw new Error(`Models request failed: ${I.status}`);const v=await E.json(),A=await I.json();e(v),r(A);const m={};await Promise.all(v.map(async k=>{try{const _=await ge(`/api/specialists/${encodeURIComponent(k.id)}/recommendations`);if(_.ok){const T=await _.json();T.recommendations&&(m[k.id]=T.recommendations)}}catch{}})),o(m)}catch(E){d(E.message)}finally{u(!1)}},[]);w.useEffect(()=>{f()},[f]);const x=w.useCallback(E=>{const I=i[E];if(I&&I.length)return I.map(A=>A.id);const v=new Set;if(s&&typeof s=="object")for(const A of Object.keys(s)){const m=s[A];if(Array.isArray(m))for(const k of m)typeof k=="string"?v.add(k):k&&typeof k=="object"&&"id"in k&&typeof k.id=="string"&&v.add(k.id)}if(Array.isArray(t))for(const A of t)A!=null&&A.activeModel&&v.add(A.activeModel),A!=null&&A.defaultModel&&v.add(A.defaultModel);return Array.from(v).sort((A,m)=>A.localeCompare(m))},[i,s,t]),y=w.useCallback(async(E,I)=>{p(v=>({...v,[E]:"saving"}));try{const v=await ge(`/api/specialists/${encodeURIComponent(E)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:I})});if(!v.ok){const m=await v.text().catch(()=>"");throw new Error(`PATCH failed (${v.status}): ${m||v.statusText}`)}const A=await v.json();e(m=>(m==null?void 0:m.map(k=>k.id===E?{...k,activeModel:A.activeModel??k.defaultModel,overridden:(A.activeModel??k.defaultModel)!==k.defaultModel}:k))??null),p(m=>({...m,[E]:"saved"})),setTimeout(()=>{p(m=>{if(m[E]!=="saved")return m;const k={...m};return delete k[E],k})},1500)}catch(v){p(A=>({...A,[E]:"error"})),d(`${E}: ${v.message}`)}},[]);return g&&!t?n.jsx("div",{className:"h-full w-full flex items-center justify-center text-xs text-[#52525b]",children:"Loading specialists…"}):n.jsxs("div",{className:"w-full h-full flex flex-col bg-[#0a0a0f] text-[#e4e4e7] text-sm",children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-[#27272a]/60",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Cr,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("h3",{className:"font-semibold",children:"Specialist Models"}),n.jsxs("span",{className:"text-[10px] text-[#52525b]",children:[(t==null?void 0:t.length)??0," sub-agents"]})]}),n.jsxs("button",{onClick:()=>{u(!0),f()},className:"flex items-center gap-1 px-2 py-1 rounded text-[11px] text-[#71717a] hover:text-[#e4e4e7] hover:bg-[#27272a]/60 transition-colors",title:"Refresh from server",children:[n.jsx(gn,{className:`w-3 h-3 ${g?"animate-spin":""}`}),"Refresh"]})]}),c&&n.jsxs("div",{className:"mx-4 mt-3 flex items-start gap-2 px-3 py-2 rounded bg-[#7f1d1d]/20 border border-[#7f1d1d]/40 text-[11px] text-[#fca5a5]",children:[n.jsx(fn,{className:"w-3 h-3 mt-0.5 shrink-0"}),n.jsx("span",{className:"font-mono",children:c})]}),n.jsxs("div",{className:"flex-1 overflow-auto px-4 py-3 space-y-3",children:[(t==null?void 0:t.length)===0&&n.jsx("div",{className:"text-xs text-[#52525b] italic",children:"No specialists registered."}),t==null?void 0:t.map(E=>n.jsx(rm,{row:E,models:x(E.id),recommendations:i[E.id]??[],state:l[E.id]??"idle",onChange:I=>y(E.id,I),onReset:()=>y(E.id,null)},E.id))]}),n.jsxs("div",{className:"px-4 py-2 border-t border-[#27272a]/60 text-[10px] text-[#52525b]",children:["Overrides write to ",n.jsx("span",{className:"font-mono text-[#71717a]",children:"config.specialists.overrides"}),". Top-scored models are recommended per specialist role."]})]})}function rm({row:t,models:e,recommendations:s,state:r,onChange:i,onReset:o}){var u;const c=Yi[t.role]??Yi.general,d=s.find(f=>f.id===t.activeModel),l=s[0]??null,[p,g]=w.useState(!1);return n.jsxs("div",{className:"rounded-lg border border-[#27272a]/60 bg-[#18181b]/70 hover:border-[#3f3f46]/80 transition-colors",children:[n.jsxs("div",{className:"px-3 py-2 flex items-center gap-3",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-[180px]",children:[n.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:c},title:t.role}),n.jsxs("div",{className:"flex flex-col min-w-0",children:[n.jsx("div",{className:"text-sm font-medium truncate",children:t.name}),n.jsx("div",{className:"text-[10px] text-[#52525b] truncate",children:t.title})]})]}),n.jsxs("div",{className:"flex-1 flex items-center gap-2 min-w-0",children:[n.jsx("select",{value:t.activeModel,onChange:f=>i(f.target.value),disabled:r==="saving",className:"flex-1 min-w-0 px-2 py-1 rounded bg-[#0a0a0f] border border-[#27272a] text-xs font-mono focus:outline-none focus:border-[#6366f1] disabled:opacity-50",title:`default: ${t.defaultModel}`,children:e.map(f=>{const x=s.find(I=>I.id===f),y=(x==null?void 0:x.badges)??[],E=y.length?`${f} [${y.join(", ")}]`:f;return n.jsx("option",{value:f,children:E},f)})}),d&&d.badges.length>0&&n.jsx("div",{className:"hidden sm:flex items-center gap-1 shrink-0",children:d.badges.slice(0,3).map(f=>n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${sm[f]??"bg-[#27272a] text-[#a1a1aa] border-[#27272a]"}`,children:f},f))}),t.overridden&&n.jsxs("button",{onClick:o,disabled:r==="saving",className:"flex items-center gap-1 px-2 py-1 rounded text-[10px] text-[#fbbf24] border border-[#fbbf24]/30 hover:bg-[#fbbf24]/10 transition-colors disabled:opacity-50",title:`Reset to default: ${t.defaultModel}`,children:[n.jsx(io,{className:"w-3 h-3"}),"Reset"]}),n.jsx("button",{onClick:()=>g(f=>!f),className:"flex items-center justify-center w-6 h-6 rounded hover:bg-[#27272a]/60 text-[#52525b] hover:text-[#a1a1aa] transition-colors",title:"Show recommendation details",children:n.jsx(ci,{className:"w-3.5 h-3.5"})}),n.jsxs("div",{className:"w-5 h-5 flex items-center justify-center shrink-0",children:[r==="saving"&&n.jsx(gn,{className:"w-3.5 h-3.5 animate-spin text-[#6366f1]"}),r==="saved"&&n.jsx(ui,{className:"w-3.5 h-3.5 text-[#10b981]"}),r==="error"&&n.jsx(fn,{className:"w-3.5 h-3.5 text-[#ef4444]"})]})]})]}),p&&n.jsxs("div",{className:"px-3 pb-3 space-y-1.5",children:[d&&n.jsxs("div",{className:"flex items-start gap-2 text-[11px] text-[#a1a1aa]",children:[n.jsx(ci,{className:"w-3 h-3 mt-0.5 shrink-0 text-[#6366f1]"}),n.jsx("span",{children:d.rationale})]}),l&&l.id!==t.activeModel&&n.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[#10b981]",children:[n.jsx(ui,{className:"w-3 h-3 shrink-0"}),n.jsxs("span",{children:["Recommended upgrade: ",n.jsx("span",{className:"font-mono",children:l.id})," (score ",l.score,"/100)",l.badges.length>0&&n.jsxs("span",{className:"ml-1 text-[#71717a]",children:["[",l.badges.join(", "),"]"]})]})]}),d&&n.jsxs("div",{className:"grid grid-cols-3 gap-2 text-[10px] text-[#52525b]",children:[n.jsxs("div",{children:["Capability: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[d.breakdown.capabilityScore,"/40"]})]}),n.jsxs("div",{children:["Fit: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[d.breakdown.specialistFit,"/40"]})]}),n.jsxs("div",{children:["Availability: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[d.breakdown.availability,"/20"]})]})]})]}),n.jsxs("div",{className:"px-3 pb-2 flex items-center gap-2 text-[10px] text-[#52525b]",children:[n.jsxs("span",{children:["id: ",n.jsx("span",{className:"font-mono text-[#71717a]",children:t.id})]}),n.jsx("span",{children:"•"}),n.jsxs("span",{children:["role: ",n.jsx("span",{className:"font-mono",style:{color:c},children:t.role})]}),((u=t.templateMatches)==null?void 0:u.length)>0&&n.jsxs(n.Fragment,{children:[n.jsx("span",{children:"•"}),n.jsxs("span",{className:"truncate",children:["templates: ",n.jsx("span",{className:"font-mono text-[#71717a]",children:t.templateMatches.join(", ")})]})]})]})]})}function im(){const[t,e]=w.useState(null),[s,r]=w.useState(null),[i,o]=w.useState(null),[c,d]=w.useState(!1),[l,p]=w.useState(null),[g,u]=w.useState(null),f=w.useCallback(async()=>{p(null);try{const[I,v,A]=await Promise.all([ge("/api/telemetry/consent").then(m=>m.ok?m.json():Promise.reject(new Error(`consent ${m.status}`))),ge("/api/analytics/profile").then(m=>m.ok?m.json():null),ge("/api/telemetry/status").then(m=>m.ok?m.json():null)]);e(I),r(v),A!=null&&A.remote&&o(A.remote)}catch(I){p(I.message)}},[]);w.useEffect(()=>{const I=setInterval(()=>{ge("/api/telemetry/status").then(v=>v.ok?v.json():null).then(v=>{v!=null&&v.remote&&o(v.remote)}).catch(()=>{})},15e3);return()=>clearInterval(I)},[]),w.useEffect(()=>{f()},[f]);const x=w.useCallback(async I=>{d(!0),p(null);try{const v=await ge("/api/telemetry/consent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!v.ok)throw new Error(`save failed: ${v.status}`);const A=await v.json();e(m=>m?{...m,...A,consentedAt:A.enabled?new Date().toISOString():void 0}:null),u(Date.now()),setTimeout(()=>u(null),2e3)}catch(v){p(v.message)}finally{d(!1)}},[]),y=!!(t!=null&&t.enabled),E=!!(t!=null&&t.crashReports);return n.jsxs("div",{className:"w-full h-full overflow-auto bg-[#0a0a0f] text-[#e4e4e7] text-sm p-4",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[y?n.jsx($l,{className:"w-5 h-5 text-[#10b981]"}):n.jsx(Tr,{className:"w-5 h-5 text-[#71717a]"}),n.jsx("h3",{className:"font-semibold text-base",children:"Privacy & Telemetry"}),n.jsx("span",{className:`ml-2 text-[10px] px-2 py-0.5 rounded-full border ${y?"border-[#10b981]/40 bg-[#10b981]/10 text-[#10b981]":"border-[#3f3f46] bg-[#18181b] text-[#71717a]"}`,children:y?"ENABLED":"OFF"}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[g&&n.jsxs("span",{className:"text-[11px] text-[#10b981] flex items-center gap-1",children:[n.jsx(Tl,{className:"w-3 h-3"})," Saved"]}),l&&n.jsxs("span",{className:"text-[11px] text-[#ef4444] flex items-center gap-1",children:[n.jsx(Rl,{className:"w-3 h-3"})," ",l]}),n.jsxs("button",{onClick:()=>{f()},className:"flex items-center gap-1 px-2 py-1 rounded text-[11px] text-[#71717a] hover:text-[#e4e4e7] hover:bg-[#27272a]/60 transition-colors",children:[n.jsx(gn,{className:"w-3 h-3"})," Refresh"]})]})]}),n.jsx("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/70",children:n.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:y,disabled:c,onChange:I=>x({enabled:I.target.checked,crashReports:E}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"font-medium",children:"Send anonymous usage stats"}),n.jsx("div",{className:"text-xs text-[#a1a1aa] mt-1 leading-relaxed",children:"OS, Node version, CPU/GPU model + VRAM, RAM, TITAN version, and install method. A heartbeat every 5 minutes so we see uptime + concurrent-session counts. Never sends: prompts, file contents, credentials, IP address, or conversations."}),(t==null?void 0:t.consentedAt)&&n.jsxs("div",{className:"text-[10px] text-[#71717a] mt-2",children:["Consented ",n.jsx("span",{className:"font-mono",children:new Date(t.consentedAt).toLocaleString()}),t.consentedVersion&&n.jsxs(n.Fragment,{children:[" on TITAN v",n.jsx("span",{className:"font-mono",children:t.consentedVersion})]})]})]})]})}),n.jsx("div",{className:`mb-4 p-4 rounded-lg border transition-opacity ${y?"border-[#27272a]/60 bg-[#18181b]/70":"border-[#27272a]/30 bg-[#18181b]/30 opacity-60"}`,children:n.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:E,disabled:c||!y,onChange:I=>x({enabled:y,crashReports:I.target.checked}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("div",{className:"font-medium",children:"Send crash reports"}),n.jsxs("div",{className:"text-xs text-[#a1a1aa] mt-1 leading-relaxed",children:["When TITAN throws an uncaught exception or unhandled promise rejection, send the error class, message, and stack trace. ",n.jsxs("span",{className:"text-[#fbbf24]",children:["Your $HOME path is replaced with the string ",n.jsx("span",{className:"font-mono",children:'"$HOME"'})," before sending."]})]})]})]})}),n.jsxs("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/40",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(fn,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("div",{className:"text-sm font-medium",children:"What would be sent right now"})]}),s?n.jsxs("dl",{className:"grid grid-cols-[160px_1fr] gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-[#71717a]",children:"installId"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.installId.slice(0,32),"…"]}),n.jsx("dt",{className:"text-[#71717a]",children:"os / arch"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.os," / ",s.arch," (",s.osRelease,")"]}),n.jsx("dt",{className:"text-[#71717a]",children:"cpu"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.cpuModel," · ",s.cpuCores,"c"]}),n.jsx("dt",{className:"text-[#71717a]",children:"ram"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[(s.ramTotalMB/1024).toFixed(1)," GB"]}),n.jsx("dt",{className:"text-[#71717a]",children:"gpu"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.gpuVendor,"/",s.gpuName," · ",(s.gpuVramMB/1024).toFixed(1)," GB VRAM"]}),n.jsx("dt",{className:"text-[#71717a]",children:"disk"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.diskTotalGB," GB"]}),n.jsx("dt",{className:"text-[#71717a]",children:"version / node"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.version," · ",s.nodeVersion]}),n.jsx("dt",{className:"text-[#71717a]",children:"install method"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7]",children:s.installMethod})]}):n.jsx("div",{className:"text-xs text-[#71717a]",children:"Loading profile preview…"})]}),n.jsxs("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/50",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(ao,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("div",{className:"text-sm font-medium",children:"Delivery status"}),(i==null?void 0:i.lastSuccessAt)&&!i.lastError&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#10b981]/40 bg-[#10b981]/10 text-[#10b981]",children:"FLOWING"}),(i==null?void 0:i.lastError)&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#ef4444]/40 bg-[#ef4444]/10 text-[#ef4444]",children:"ERROR"}),!(i!=null&&i.configured)&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#71717a]/40 bg-[#71717a]/10 text-[#71717a]",children:"NO REMOTE"})]}),i?n.jsxs("dl",{className:"grid grid-cols-[160px_1fr] gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-[#71717a]",children:"remote URL"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7] break-all",children:i.remoteUrl||"—"}),n.jsx("dt",{className:"text-[#71717a]",children:"sent / failed"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[n.jsx("span",{className:"text-[#10b981]",children:i.sentCount})," / ",n.jsx("span",{className:i.failedCount>0?"text-[#ef4444]":"text-[#71717a]",children:i.failedCount}),i.lastEventType&&n.jsxs("span",{className:"text-[#71717a]",children:[" · last event: ",n.jsx("span",{className:"text-[#a1a1aa]",children:i.lastEventType})]})]}),n.jsx("dt",{className:"text-[#71717a]",children:"last attempt"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7] flex items-center gap-1",children:[n.jsx(ps,{className:"w-3 h-3 text-[#71717a]"}),i.lastAttemptAt?new Date(i.lastAttemptAt).toLocaleString():"—"]}),n.jsx("dt",{className:"text-[#71717a]",children:"last success"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7]",children:i.lastSuccessAt?new Date(i.lastSuccessAt).toLocaleString():"—"}),i.lastError&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-[#ef4444]",children:"last error"}),n.jsx("dd",{className:"font-mono text-[#fca5a5] break-all",children:i.lastError})]})]}):n.jsx("div",{className:"text-xs text-[#71717a]",children:"Checking collector reachability…"})]}),n.jsxs("div",{className:"mb-4 p-3 rounded-lg border border-[#27272a]/60 bg-[#0a0a0f]",children:[n.jsx("div",{className:"text-[10px] text-[#71717a] uppercase tracking-wider mb-1",children:"Collector"}),n.jsx("div",{className:"font-mono text-[11px] text-[#a1a1aa] break-all",children:(t==null?void 0:t.remoteUrl)||"—"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[n.jsxs("a",{href:"https://github.com/Djtony707/TITAN/blob/main/PRIVACY.md",target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-[#6366f1] hover:underline",children:[n.jsx(hi,{className:"w-3 h-3"})," Read the full PRIVACY.md"]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("a",{href:"https://github.com/Djtony707/TITAN/blob/main/src/analytics/collector.ts",target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-[#6366f1] hover:underline",children:[n.jsx(hi,{className:"w-3 h-3"})," See the collector source"]})]})]})}const om=oe.lazy(()=>le(()=>import("./AutopilotPanel-BBhP6EEw.js"),__vite__mapDeps([48,1,2,37,14])));function am(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(om,{})})})}const lm=oe.lazy(()=>le(()=>import("./WorkflowsPanel-BZQu93gE.js"),__vite__mapDeps([49,1,2,37,14,3,4,10,11,12,24,27,42,16,28,20,50,51])));function cm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(lm,{})})})}const dm=oe.lazy(()=>le(()=>import("./LearningPanel-Ka17sHxK.js"),__vite__mapDeps([52,1,2,37,14,24,51,53,54,55,27,22,56,31,23,43,12,57,32,26,21,39,58,20,59,60,61,62,63,64,11,65,66,15,40])));function um(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(dm,{})})})}const hm=oe.lazy(()=>le(()=>import("./SelfImprovePanel-CgJG9v1W.js"),__vite__mapDeps([67,1,2,24,38,20,68,54,15,14,42,23,60,28])));function fm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(hm,{})})})}const pm=oe.lazy(()=>le(()=>import("./PersonasPanel-VfvknF9L.js"),__vite__mapDeps([69,1,2])));function mm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(pm,{})})})}const gm=oe.lazy(()=>le(()=>import("./PersonaProfilesPanel-hmUdUabW.js"),__vite__mapDeps([70,1,2,37,14,24,11,16,63,20])));function ym(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(gm,{})})})}const bm=oe.lazy(()=>le(()=>import("./DreamPanel-BJO5hRUh.js"),__vite__mapDeps([71,1,2,37,14,24])));function xm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(bm,{})})})}const wm=oe.lazy(()=>le(()=>import("./HomelabPanel-C658fL2z.js"),__vite__mapDeps([72,1,2,37,14,73,74,4,24,20,21,56,19,31,38,40,17])));function vm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(wm,{})})})}const _m=oe.lazy(()=>le(()=>import("./NvidiaPanel-53CiSPrh.js"),__vite__mapDeps([75,1,2,24,43,38,66,32])));function km(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(_m,{})})})}const Sm=oe.lazy(()=>le(()=>import("./FilesPanel-Cimj2Z8k.js"),__vite__mapDeps([76,1,2,27,24,14,77,20,12,28,43,41,11,22,55,56,31,23,51,57,32,26,21,39,58,59,60,61,62,63,64,65,66,15,40])));function jm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Sm,{})})})}const Em=oe.lazy(()=>le(()=>import("./LogsPanel-BiELvlMC.js"),__vite__mapDeps([78,1,2,24])));function Nm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Em,{})})})}const Cm=oe.lazy(()=>le(()=>import("./TelemetryPanel-C3JTWWQO.js"),__vite__mapDeps([79,1,2,73,20,18,19,56])));function Tm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Cm,{})})})}const Rm=oe.lazy(()=>le(()=>import("./SkillsPanel-BINP41r2.js"),__vite__mapDeps([80,1,2,37,14,32,28,41])));function Am(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Rm,{})})})}const Lm=oe.lazy(()=>le(()=>import("./McpPanel-BW2r8V3m.js"),__vite__mapDeps([81,1,2,82,24,27,56,61,28])));function Im(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Lm,{})})})}const Dm=oe.lazy(()=>le(()=>import("./IntegrationsPanel-Xy3HlXti.js"),__vite__mapDeps([83,1,2,82,38,43,14])));function Mm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Dm,{})})})}const Om=oe.lazy(()=>le(()=>import("./ChannelsPanel-e1nT5QcW.js"),__vite__mapDeps([84,1,2,37,14,24,38,43])));function Pm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Om,{})})})}const Wm=oe.lazy(()=>le(()=>import("./MeshPanel-Ch_uGo4a.js"),__vite__mapDeps([85,1,2,86,24,65])));function Bm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Wm,{})})})}const Um=oe.lazy(()=>le(()=>import("./MemoryWikiPanel-BSbG8c80.js"),__vite__mapDeps([87,1,2,37,14,77,20,32,51])));function Fm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Um,{})})})}const $m=oe.lazy(()=>le(()=>import("./AutoresearchPanel-CmSoFu9c.js"),__vite__mapDeps([88,1,2,58,42,16,24,68,54,20,14])));function zm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx($m,{})})})}const Hm=oe.lazy(()=>le(()=>import("./SelfProposalsPanel-BenuzEGo.js"),__vite__mapDeps([89,1,2,37,14,20,55,27,22,56,31,23,51,43,12,57,32,26,21,39,58,59,60,61,62,63,24,64,11,65,66,15,40])));function Vm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Hm,{})})})}const Gm=oe.lazy(()=>le(()=>import("./OverviewPanel-CmRVwkE7.js"),__vite__mapDeps([90,1,2,73,37,14,74,4,20,21,56,91])));function qm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Gm,{})})})}const Ym=oe.lazy(()=>le(()=>import("./SessionsPanel-CFdsWt2W.js"),__vite__mapDeps([92,1,2,37,14,3,4,86,10,11,12,32,28])));function Km(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Ym,{})})})}const Jm=oe.lazy(()=>le(()=>import("./WatchView-Cflz1FfL.js"),__vite__mapDeps([93,1,2,9])));function Xm(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Jm,{})})})}const Qm=oe.lazy(()=>le(()=>import("./BackupPanel-BMqXOM64.js"),__vite__mapDeps([94,1,2,37,14,27,24,59,38])));function Zm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Qm,{})})})}const eg=oe.lazy(()=>le(()=>import("./TrainingPanel-BMunX3EV.js"),__vite__mapDeps([95,1,2,37,14,24,41])));function tg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(eg,{})})})}const sg=oe.lazy(()=>le(()=>import("./RecipesPanel-B7NygJvl.js"),__vite__mapDeps([96,1,2,37,14,24,51,42,28])));function ng(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(sg,{})})})}const rg=oe.lazy(()=>le(()=>import("./VramPanel-C4nG82nu.js"),__vite__mapDeps([97,1,2,37,14,24])));function ig(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(rg,{})})})}const og=oe.lazy(()=>le(()=>import("./TeamsPanel-CwVNzD77.js"),__vite__mapDeps([98,1,2,37,14,24,28])));function ag(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(og,{})})})}const lg=oe.lazy(()=>le(()=>import("./CronPanel-BMneWRHA.js"),__vite__mapDeps([99,1,2,37,14,24,20,50,28])));function cg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(lg,{})})})}const dg=oe.lazy(()=>le(()=>import("./CheckpointsPanel-BixKyU53.js"),__vite__mapDeps([100,1,2,37,14,24,43,28])));function ug(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(dg,{})})})}const hg=oe.lazy(()=>le(()=>import("./OrganismPanel-BRbiiY5k.js"),__vite__mapDeps([101,1,2,37,14,24,38])));function fg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(hg,{})})})}const pg=oe.lazy(()=>le(()=>import("./FleetPanel-zzprw7Ro.js"),__vite__mapDeps([102,1,2,37,14,24,60])));function mg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(pg,{})})})}const gg=oe.lazy(()=>le(()=>import("./BrowserPanel-DqpJBtZO.js"),__vite__mapDeps([103,1,2,37,14])));function yg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(gg,{})})})}const bg=oe.lazy(()=>le(()=>import("./EvalPanel-j3fHE-k4.js"),__vite__mapDeps([104,1,2,37,14,24,42])));function xg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(bg,{})})})}function wg(t){const e=Date.now()-new Date(t).getTime();if(!Number.isFinite(e)||e<0)return t;const s=Math.floor(e/1e3);if(s<60)return`${s}s ago`;const r=Math.floor(s/60);if(r<60)return`${r}m ago`;const i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function vg(t){const e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e>=0?t.slice(e+1):t}function _g(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(""),[c,d]=w.useState(null),[l,p]=w.useState(""),[g,u]=w.useState(!1),[f,x]=w.useState(null),[y,E]=w.useState(null),[I,v]=w.useState(null),A=w.useCallback(async()=>{r(!0),x(null);try{const C=await ge("/api/time-travel/checkpoints?limit=100");if(!C.ok)throw new Error(`${C.status} ${C.statusText}`);const D=await C.json();e(D.checkpoints||[])}catch(C){x(C.message||"Failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{A()},[A]);const m=w.useCallback((C,D)=>{v({kind:C,message:D}),setTimeout(()=>v(null),4e3)},[]),k=w.useCallback(async C=>{d(C),p(""),u(!0);try{const D=await ge(`/api/time-travel/diff/${encodeURIComponent(C)}`);if(!D.ok)throw new Error(`${D.status} ${D.statusText}`);const j=await D.json();p(j.diff||"(no diff returned)")}catch(D){p(`Failed to load diff: ${D.message}`)}finally{u(!1)}},[]),_=w.useCallback(C=>{E(C)},[]),T=w.useCallback(async()=>{if(!y)return;const C=y;E(null);try{const D=await ge(`/api/time-travel/restore/${encodeURIComponent(C)}`,{method:"POST"});if(!D.ok)throw new Error(`${D.status} ${D.statusText}`);const j=await D.json();j.ok?(m("ok",j.message||`Restored to ${C.slice(0,8)}.`),A()):m("err",j.message||"Restore failed.")}catch(D){m("err",D.message||"Restore failed.")}},[y,A,m]),S=w.useMemo(()=>{const C=i.trim().toLowerCase();return C?t.filter(D=>D.filePath.toLowerCase().includes(C)||D.toolName.toLowerCase().includes(C)||D.id.toLowerCase().includes(C)):t},[t,i]);return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",fontSize:12,background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Time Travel"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," file checkpoints · newest first"]})]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("input",{type:"text",value:i,onChange:C=>o(C.target.value),placeholder:"Filter by file or tool…",style:{background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:6,color:"#fff",fontSize:11,padding:"4px 8px",outline:"none",width:180}}),n.jsx("button",{onClick:A,disabled:s,title:"Refresh checkpoint list",style:{background:"rgba(99,102,241,0.15)",border:"1px solid rgba(99,102,241,0.35)",borderRadius:6,color:"#c7d2fe",fontSize:11,padding:"4px 10px",cursor:s?"wait":"pointer"},children:s?"…":"Refresh"})]})]}),I&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,background:I.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${I.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:I.kind==="ok"?"#86efac":"#fca5a5",fontSize:11},children:I.message}),f&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.3)",color:"#fca5a5",fontSize:11},children:f}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[n.jsx("div",{style:{flex:1,overflow:"auto",borderRight:"1px solid rgba(255,255,255,0.06)"},children:s&&t.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)"},children:"Loading checkpoints…"}):S.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)"},children:i?"No matches for that filter.":"No file checkpoints yet. They're created automatically whenever TITAN writes or edits a file."}):S.map(C=>n.jsxs("div",{onClick:()=>k(C.id),style:{padding:"8px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",cursor:"pointer",background:c===C.id?"rgba(99,102,241,0.08)":"transparent",borderLeft:c===C.id?"2px solid #818cf8":"2px solid transparent"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[n.jsx("span",{style:{fontSize:11,fontFamily:"ui-monospace, monospace",color:"#a5b4fc"},children:C.commitHash.slice(0,8)}),n.jsx("span",{style:{fontSize:10,color:"rgba(255,255,255,0.5)"},children:wg(C.timestamp)})]}),n.jsx("div",{style:{fontSize:12,color:"#e2e8f5",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:C.filePath,children:vg(C.filePath)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:4},children:[n.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:["before ",n.jsx("code",{style:{color:"#fbbf24"},children:C.toolName})]}),n.jsx("button",{onClick:D=>{D.stopPropagation(),_(C.id)},title:"Restore this file to the state it was in at this checkpoint",style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"rgba(34,197,94,0.12)",border:"1px solid rgba(34,197,94,0.3)",color:"#86efac",cursor:"pointer"},children:"Restore"})]})]},C.id))}),n.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:c?g?n.jsx("div",{style:{color:"rgba(255,255,255,0.4)"},children:"Loading diff…"}):n.jsx("pre",{style:{margin:0,fontFamily:'ui-monospace, "SF Mono", Menlo, monospace',fontSize:11,lineHeight:1.5,color:"#e2e8f5",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:(l||"").split(`
969
- `).map((C,D)=>{let j="rgba(255,255,255,0.7)";return C.startsWith("+")&&!C.startsWith("+++")?j="#86efac":C.startsWith("-")&&!C.startsWith("---")?j="#fca5a5":C.startsWith("@@")?j="#a5b4fc":(C.startsWith("diff")||C.startsWith("index")||C.startsWith("+++")||C.startsWith("---"))&&(j="rgba(255,255,255,0.45)"),n.jsx("div",{style:{color:j},children:C||" "},D)})}):n.jsx("div",{style:{color:"rgba(255,255,255,0.4)"},children:"Select a checkpoint on the left to see its diff vs the current file."})})]}),y&&n.jsx("div",{onClick:()=>E(null),style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10},children:n.jsxs("div",{onClick:C=>C.stopPropagation(),style:{background:"#0d0f1d",border:"1px solid rgba(255,255,255,0.1)",borderRadius:10,padding:18,maxWidth:380,color:"#e2e8f5"},children:[n.jsx("div",{style:{fontSize:14,fontWeight:600,marginBottom:8},children:"Restore this checkpoint?"}),n.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.7)",marginBottom:12},children:["The file will be overwritten with its state at ",n.jsx("code",{children:y.slice(0,8)}),". A NEW checkpoint of the current state is taken first, so you can always come back."]}),n.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[n.jsx("button",{onClick:()=>E(null),style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.1)",color:"#e2e8f5",borderRadius:6,padding:"6px 12px",fontSize:12,cursor:"pointer"},children:"Cancel"}),n.jsx("button",{onClick:T,style:{background:"rgba(34,197,94,0.18)",border:"1px solid rgba(34,197,94,0.4)",color:"#86efac",borderRadius:6,padding:"6px 12px",fontSize:12,cursor:"pointer"},children:"Restore"})]})]})})]})}const Ki=5e3,Ji={planning:"#a5b4fc",delegating:"#60a5fa",observing:"#22d3ee",iterating:"#f59e0b",verifying:"#a78bfa",reporting:"#34d399",blocked:"#facc15",escalated:"#fb7185",done:"#34d399",failed:"#ef4444",cancelled:"#737373"};function kg(t){if(!Number.isFinite(t)||t<0)return"—";const e=Math.floor(t/1e3);if(e<60)return`${e}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),i=s%60;return`${r}h ${i}m`}function Sg(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function jg(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(null),[c,d]=w.useState(!1),[l,p]=w.useState(""),[g,u]=w.useState(2),[f,x]=w.useState(!1),[y,E]=w.useState(null),I=w.useCallback(async()=>{try{const _=await ge("/api/missions/active");if(!_.ok)throw new Error(`${_.status} ${_.statusText}`);const T=await _.json();e(T.missions||[]),o(null)}catch(_){o(_.message||"failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{I();const _=setInterval(I,Ki);return()=>clearInterval(_)},[I]);const v=w.useCallback((_,T)=>{E({kind:_,message:T}),setTimeout(()=>E(null),5e3)},[]),A=w.useCallback(async()=>{var T;const _=l.trim();if(_.length<10){v("err","Describe the mission (>=10 chars).");return}x(!0);try{const S=await ge("/api/mission/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:_,budgetUsd:g})});if(!S.ok)throw new Error(`${S.status} ${S.statusText}`);const C=await S.json();v("ok",C.message||`Mission "${((T=C.goal)==null?void 0:T.title)??"?"}" launched.`),p(""),d(!1),I()}catch(S){v("err",S.message||"launch failed")}finally{x(!1)}},[l,g,I,v]),m=w.useCallback(async _=>{try{const T=await ge(`/api/mission/${encodeURIComponent(_)}/cancel`,{method:"POST"});if(!T.ok)throw new Error(`${T.status} ${T.statusText}`);v("ok","Mission marked for cancellation."),I()}catch(T){v("err",T.message||"cancel failed")}},[I,v]),k=w.useMemo(()=>{const _={delegating:0,observing:1,iterating:2,verifying:3,planning:4,reporting:5,blocked:6,escalated:7};return[...t].sort((T,S)=>(_[T.phase]??99)-(_[S.phase]??99))},[t]);return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Mission Driver"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," active · polling every ",Ki/1e3,"s"]})]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("button",{onClick:()=>d(_=>!_),title:"Launch a new autonomous mission",style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid rgba(99,102,241,0.4)",background:c?"rgba(99,102,241,0.25)":"rgba(99,102,241,0.12)",color:"#c7d2fe",cursor:"pointer"},children:c?"× Close":"+ New mission"}),n.jsx("button",{onClick:I,title:"Refresh",style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid rgba(255,255,255,0.1)",background:"rgba(255,255,255,0.04)",color:"#e2e8f5",cursor:"pointer"},children:"↻"})]})]}),y&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,fontSize:11,background:y.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${y.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:y.kind==="ok"?"#86efac":"#fca5a5"},children:y.message}),c&&n.jsxs("div",{style:{padding:12,borderBottom:"1px solid rgba(255,255,255,0.06)",background:"rgba(99,102,241,0.04)"},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.6,color:"#a5b4fc",marginBottom:6},children:"Describe the mission"}),n.jsx("textarea",{value:l,onChange:_=>p(_.target.value),placeholder:"e.g. 'Research the top 5 AI agent frameworks for 2026, summarize their differentiation in a markdown report, and save to ~/Documents/agent-research.md'",rows:3,style:{width:"100%",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:12,padding:"6px 10px",resize:"vertical",fontFamily:"inherit",boxSizing:"border-box"}}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:8,gap:8},children:[n.jsxs("label",{style:{fontSize:11,color:"rgba(255,255,255,0.6)"},children:["Budget cap: $",n.jsx("input",{type:"number",value:g,onChange:_=>u(Math.max(.05,Math.min(50,Number(_.target.value)||2))),step:"0.5",min:"0.05",max:"50",style:{width:60,marginLeft:4,background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:4,color:"#fff",fontSize:11,padding:"2px 6px"}})]}),n.jsx("button",{onClick:A,disabled:f||l.trim().length<10,style:{fontSize:12,padding:"6px 14px",borderRadius:6,border:"none",background:f?"rgba(255,255,255,0.05)":"rgba(34,197,94,0.18)",color:"#86efac",cursor:f?"wait":"pointer",fontWeight:600},children:f?"Decomposing…":"🚀 Launch"})]})]}),n.jsxs("div",{style:{flex:1,overflow:"auto",padding:8},children:[i&&n.jsx("div",{style:{padding:10,color:"#fca5a5",fontSize:11},children:i}),s&&t.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)",fontSize:12},children:"Loading missions…"}):k.length===0?n.jsxs("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:["No active missions.",n.jsx("br",{}),n.jsx("span",{style:{fontSize:11,color:"rgba(255,255,255,0.35)"},children:'Click "+ New mission" to launch one.'})]}):k.map(_=>{const T=Ji[_.phase]??"#94a3b8",S=_.subtasks.total>0?Math.round(_.subtasks.completed/_.subtasks.total*100):0;return n.jsxs("div",{style:{padding:"10px 12px",marginBottom:6,borderRadius:8,background:"rgba(255,255,255,0.025)",border:`1px solid ${_.phase==="blocked"?"rgba(250,204,21,0.4)":"rgba(255,255,255,0.06)"}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[n.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#fafafa",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:_.title,children:_.title}),n.jsx("button",{onClick:()=>m(_.goalId),title:"Cancel this mission",style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.3)",color:"#fca5a5",cursor:"pointer",marginLeft:6},children:"Cancel"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:"rgba(255,255,255,0.7)"},children:[n.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 6px",borderRadius:4,background:`${T}22`,border:`1px solid ${T}55`,color:T,textTransform:"uppercase",letterSpacing:.5,fontWeight:600,fontSize:9},children:_.phase}),n.jsxs("span",{children:[_.subtasks.completed,"/",_.subtasks.total," subtasks (",S,"%)"]}),n.jsx("span",{children:"·"}),n.jsx("span",{children:Sg(_.budget.costUsd)}),n.jsx("span",{children:"·"}),n.jsx("span",{children:kg(Date.now()-new Date(_.startedAt).getTime())})]}),_.blockedReason&&n.jsxs("div",{style:{marginTop:6,padding:"6px 8px",borderRadius:4,background:"rgba(250,204,21,0.08)",border:"1px solid rgba(250,204,21,0.25)",fontSize:11,color:"#fde68a"},children:[n.jsx("strong",{children:"Blocked:"})," ",_.blockedReason.question??"(no reason)"]}),_.lastHistory.length>0&&n.jsx("div",{style:{marginTop:6,fontSize:10,color:"rgba(255,255,255,0.45)",display:"flex",flexDirection:"column",gap:1},children:_.lastHistory.slice(-3).map((C,D)=>n.jsxs("div",{style:{display:"flex",gap:6,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n.jsx("span",{style:{color:Ji[C.phase]??"rgba(255,255,255,0.6)",minWidth:70,fontFamily:"ui-monospace, monospace",fontSize:9},children:C.phase}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C.note??""})]},D))})]},_.goalId)})]})]})}const Eg=6e4,Ng=[{label:"6h",hours:6},{label:"24h",hours:24},{label:"7d",hours:168}];function Cg(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function Tg(t){return t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(1)}k`:`${(t/1e6).toFixed(2)}M`}function Rg(){const[t,e]=w.useState(24),[s,r]=w.useState(null),[i,o]=w.useState(!0),[c,d]=w.useState(null),l=w.useCallback(async()=>{o(!0);try{const p=await ge(`/api/missions/digest?hours=${t}`);if(!p.ok)throw new Error(`${p.status} ${p.statusText}`);const g=await p.json();r(g),d(null)}catch(p){d(p.message||"failed")}finally{o(!1)}},[t]);return w.useEffect(()=>{l();const p=setInterval(l,Eg);return()=>clearInterval(p)},[l]),n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Daily digest"}),n.jsx("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:"what TITAN did while you were away"})]}),n.jsx("div",{style:{display:"flex",gap:4},children:Ng.map(p=>n.jsx("button",{onClick:()=>e(p.hours),style:{fontSize:10,padding:"3px 8px",borderRadius:4,border:"1px solid rgba(255,255,255,0.1)",background:t===p.hours?"rgba(99,102,241,0.25)":"rgba(255,255,255,0.03)",color:t===p.hours?"#c7d2fe":"rgba(255,255,255,0.65)",cursor:"pointer"},children:p.label},p.label))})]}),s&&n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:8},children:[n.jsx(Ws,{label:"Done",value:s.stats.completed,color:"#34d399"}),n.jsx(Ws,{label:"Failed",value:s.stats.failed,color:s.stats.failed>0?"#fca5a5":"rgba(255,255,255,0.5)"}),n.jsx(Ws,{label:"Active",value:s.stats.active,color:"#60a5fa"}),n.jsx(Ws,{label:"Blocked",value:s.stats.blocked,color:s.stats.blocked>0?"#facc15":"rgba(255,255,255,0.5)"})]}),s&&(s.stats.totalCostUsd>0||s.stats.totalTokens>0)&&n.jsxs("div",{style:{padding:"6px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:10,color:"rgba(255,255,255,0.55)",display:"flex",justifyContent:"space-between"},children:[n.jsxs("span",{children:["Spend: ",n.jsx("strong",{style:{color:"#e2e8f5"},children:Cg(s.stats.totalCostUsd)})]}),n.jsxs("span",{children:["Tokens: ",n.jsx("strong",{style:{color:"#e2e8f5"},children:Tg(s.stats.totalTokens)})]})]}),n.jsxs("div",{style:{flex:1,overflow:"auto",padding:14},children:[i&&!s&&n.jsx("div",{style:{color:"rgba(255,255,255,0.4)",fontSize:11},children:"Loading…"}),c&&n.jsx("div",{style:{color:"#fca5a5",fontSize:11},children:c}),s&&n.jsxs(n.Fragment,{children:[n.jsx("pre",{style:{margin:0,fontFamily:'ui-monospace, "SF Mono", Menlo, monospace',fontSize:11,lineHeight:1.55,color:"#e2e8f5",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s.summaryText||"(no activity in this window)"}),s.recentLessons.length>0&&n.jsxs("div",{style:{marginTop:16,paddingTop:12,borderTop:"1px solid rgba(255,255,255,0.06)"},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.6,color:"#a5b4fc",marginBottom:6},children:"Lessons learned (Reflexion)"}),s.recentLessons.map((p,g)=>n.jsxs("div",{style:{fontSize:11,color:"rgba(255,255,255,0.8)",padding:"4px 0",borderBottom:"1px dashed rgba(255,255,255,0.04)"},children:["• ",p]},g))]})]})]})]})}function Ws({label:t,value:e,color:s}){return n.jsxs("div",{style:{textAlign:"center",padding:"6px 4px",borderRadius:6,background:"rgba(255,255,255,0.02)"},children:[n.jsx("div",{style:{fontSize:18,fontWeight:700,color:s,lineHeight:1},children:e}),n.jsx("div",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textTransform:"uppercase",letterSpacing:.5,marginTop:4},children:t})]})}const Bs={pending:"#737373",running:"#60a5fa",done:"#34d399",failed:"#ef4444",skipped:"#a78bfa"},Xi=6e3,_t=180,nr=64,Qi=96,Us=24;function Ag(t){const e=new Map,s=new Map(t.map(i=>[i.id,i])),r=(i,o)=>{if(e.has(i))return e.get(i);if(o.has(i))return 0;const c=s.get(i);if(!c)return 0;o.add(i);const d=(c.dependsOn??[]).filter(p=>s.has(p)),l=d.length===0?0:Math.max(...d.map(p=>r(p,o)))+1;return o.delete(i),e.set(i,l),l};for(const i of t)r(i.id,new Set);return e}function Lg(){const[t,e]=w.useState([]),[s,r]=w.useState(null),[i,o]=w.useState(null),[c,d]=w.useState(null),[l,p]=w.useState(null),g=w.useCallback(async()=>{try{const v=await ge("/api/missions/active");if(!v.ok)throw new Error(`${v.status} ${v.statusText}`);const m=(await v.json()).missions||[];e(m),!s&&m.length>0&&r(m[0].goalId)}catch(v){d(v.message||"failed")}},[s]),u=w.useCallback(async v=>{try{const A=await ge(`/api/mission/${encodeURIComponent(v)}`);if(!A.ok)throw new Error(`${A.status} ${A.statusText}`);const m=await A.json();o(m),d(null)}catch(A){d(A.message||"failed to load mission"),o(null)}},[]);w.useEffect(()=>{g();const v=setInterval(g,Xi);return()=>clearInterval(v)},[g]),w.useEffect(()=>{if(!s){o(null);return}u(s);const v=setInterval(()=>u(s),Xi);return()=>clearInterval(v)},[s,u]);const{layout:f,edges:x,viewBox:y}=w.useMemo(()=>{if(!(i!=null&&i.goal.subtasks))return{layout:[],edges:[],viewBox:"0 0 600 200"};const v=i.goal.subtasks,A=Ag(v),m=new Map;for(const R of v){const P=A.get(R.id)??0;m.has(P)||m.set(P,[]),m.get(P).push(R)}const k=Array.from(m.keys()).sort((R,P)=>R-P),_=Math.max(...Array.from(m.values()).map(R=>R.length),1),T=Math.max(640,_*(_t+Us)+Us),S=k.length*Qi+nr+40,C=new Map,D=[];for(const R of k){const P=m.get(R),B=P.length*_t+(P.length-1)*Us,z=(T-B)/2,q=R*Qi+20;for(let H=0;H<P.length;H++){const J=z+H*(_t+Us);C.set(P[H].id,{x:J,y:q}),D.push({...P[H],x:J,y:q})}}const j=[];for(const R of v){const P=C.get(R.id);if(P)for(const B of R.dependsOn??[]){const z=C.get(B);z&&j.push({from:B,to:R.id,x1:z.x+_t/2,y1:z.y+nr,x2:P.x+_t/2,y2:P.y})}}return{layout:D,edges:j,viewBox:`0 0 ${T} ${S}`}},[i]),E=w.useMemo(()=>new Map(((i==null?void 0:i.goal.subtasks)??[]).map(v=>[v.id,v])),[i]),I=l?E.get(l):null;return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",gap:10},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Mission graph"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," active mission(s) · subtask DAG"]})]}),t.length>0&&n.jsx("select",{value:s??"",onChange:v=>r(v.target.value||null),style:{background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,padding:"4px 8px",maxWidth:240},children:t.map(v=>n.jsxs("option",{value:v.goalId,children:[v.title," [",v.phase,"]"]},v.goalId))})]}),c&&n.jsx("div",{style:{padding:10,color:"#fca5a5",fontSize:11},children:c}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[n.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:i?f.length===0?n.jsx("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:"This mission has no subtasks yet."}):n.jsxs("svg",{viewBox:y,style:{width:"100%",height:"auto"},role:"img","aria-label":"Mission subtask DAG",children:[n.jsx("defs",{children:n.jsx("marker",{id:"mg-arrow",viewBox:"0 0 10 10",refX:"10",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:n.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(255,255,255,0.35)"})})}),x.map((v,A)=>n.jsx("line",{x1:v.x1,y1:v.y1,x2:v.x2,y2:v.y2,stroke:"rgba(255,255,255,0.25)",strokeWidth:"1.4",markerEnd:"url(#mg-arrow)"},`e-${A}`)),f.map(v=>{var _;const A=((_=i.driver)==null?void 0:_.currentSubtaskId)===v.id,m=Bs[v.status],k=l===v.id;return n.jsxs("g",{transform:`translate(${v.x}, ${v.y})`,onClick:()=>p(v.id),style:{cursor:"pointer"},children:[n.jsx("rect",{width:_t,height:nr,rx:"8",fill:A?`${m}22`:"rgba(255,255,255,0.04)",stroke:k||A?m:`${m}55`,strokeWidth:A||k?2:1}),n.jsx("circle",{cx:14,cy:14,r:"5",fill:m,children:v.status==="running"&&n.jsx("animate",{attributeName:"r",values:"4;6;4",dur:"1.2s",repeatCount:"indefinite"})}),n.jsx("text",{x:28,y:18,fontSize:"11",fontWeight:"600",fill:"#fafafa",children:v.title.length>22?v.title.slice(0,21)+"…":v.title}),n.jsxs("text",{x:28,y:34,fontSize:"9",fill:"rgba(255,255,255,0.55)",letterSpacing:"0.5",style:{textTransform:"uppercase"},children:[v.status,v.retries>0?` · ${v.retries} retr${v.retries===1?"y":"ies"}`:""]}),n.jsxs("text",{x:14,y:52,fontSize:"9",fill:"rgba(255,255,255,0.45)",children:[(v.description||"").slice(0,30),(v.description||"").length>30?"…":""]}),A&&n.jsx("text",{x:_t-8,y:14,fontSize:"8",fill:m,textAnchor:"end",fontWeight:"700",children:"NOW"})]},v.id)})]}):n.jsx("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:t.length===0?"No active missions. Launch one via the Mission Driver widget.":"Select a mission to view its graph."})}),I&&n.jsxs("div",{style:{width:260,borderLeft:"1px solid rgba(255,255,255,0.06)",padding:14,overflow:"auto",fontSize:11},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:8},children:[n.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#fafafa",flex:1},children:I.title}),n.jsx("button",{onClick:()=>p(null),style:{background:"transparent",border:"none",color:"rgba(255,255,255,0.5)",cursor:"pointer",fontSize:14,padding:0,marginLeft:6},children:"×"})]}),n.jsxs("div",{style:{marginBottom:8},children:[n.jsx("span",{style:{padding:"2px 8px",borderRadius:4,fontSize:9,fontWeight:600,textTransform:"uppercase",letterSpacing:.5,background:`${Bs[I.status]}22`,border:`1px solid ${Bs[I.status]}55`,color:Bs[I.status]},children:I.status}),I.retries>0&&n.jsxs("span",{style:{marginLeft:6,color:"rgba(255,255,255,0.5)"},children:[I.retries," retries"]})]}),n.jsx("div",{style:{color:"rgba(255,255,255,0.85)",lineHeight:1.5,marginBottom:10},children:I.description}),I.dependsOn.length>0&&n.jsxs("div",{style:{color:"rgba(255,255,255,0.55)",fontSize:10,marginBottom:6},children:[n.jsx("strong",{children:"Depends on:"})," ",I.dependsOn.map(v=>{var A;return((A=E.get(v))==null?void 0:A.title)||v}).join(", ")]}),I.completedAt&&n.jsxs("div",{style:{color:"rgba(255,255,255,0.45)",fontSize:10},children:["Completed: ",new Date(I.completedAt).toLocaleString()]})]})]}),i&&n.jsxs("div",{style:{padding:"6px 14px",borderTop:"1px solid rgba(255,255,255,0.06)",display:"flex",justifyContent:"space-between",fontSize:10,color:"rgba(255,255,255,0.55)"},children:[n.jsxs("span",{children:[i.goal.subtasks.length," subtasks · ",i.goal.progress,"% progress"]}),i.driver&&n.jsxs("span",{children:[i.driver.phase," · $",i.driver.budget.costUsd.toFixed(2)," spent"]})]})]})}function Ig(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(null),c=async()=>{try{const d=await fetch("/api/agents");if(!d.ok)throw new Error(`HTTP ${d.status}`);const l=await d.json();e(Array.isArray(l)?l:l.agents||[]),o(null)}catch(d){o(d.message)}finally{r(!1)}};return w.useEffect(()=>{c();const d=setInterval(c,1e4);return()=>clearInterval(d)},[]),s?n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(so,{className:"w-4 h-4 text-[#6366f1] animate-spin"})}):i?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsxs("div",{className:"text-center",children:[n.jsx(fn,{className:"w-4 h-4 text-red-400 mx-auto mb-1"}),n.jsx("span",{className:"text-[10px] text-red-400",children:i})]})}):t.length===0?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsx("span",{className:"text-[10px] text-[#52525b]",children:"No active agents"})}):n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsx("div",{className:"space-y-2",children:t.map(d=>n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx(mo,{className:`w-3.5 h-3.5 ${d.status==="busy"?"text-[#f59e0b]":d.status==="error"?"text-red-400":"text-[#6366f1]"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-[11px] text-[#a1a1aa] truncate",children:d.name}),n.jsxs("div",{className:"text-[10px] text-[#52525b] truncate",children:[d.role,d.model?` · ${d.model}`:""]})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${d.status==="busy"?"bg-[#f59e0b]/10 text-[#f59e0b]":d.status==="error"?"bg-red-400/10 text-red-400":"bg-[#6366f1]/10 text-[#818cf8]"}`,children:d.status})]},d.id))})})}function Dg(){const[t,e]=w.useState(null),[s,r]=w.useState(!0),i=async()=>{try{const[c,d]=await Promise.allSettled([fetch("/api/health").then(g=>g.ok?g.json():null),fetch("/ollama/api/tags").then(g=>g.ok)]),l=c.status==="fulfilled"&&c.value,p=d.status==="fulfilled"&&d.value;e({gateway:l,ollama:p,version:(l==null?void 0:l.version)||"unknown",uptime:(l==null?void 0:l.uptime)||0})}catch{e({gateway:!1,ollama:!1,version:"unknown",uptime:0})}finally{r(!1)}};if(w.useEffect(()=>{i();const c=setInterval(i,3e4);return()=>clearInterval(c)},[]),s)return n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(so,{className:"w-4 h-4 text-[#6366f1] animate-spin"})});const o=c=>{const d=Math.floor(c/3600),l=Math.floor(c%3600/60);return`${d}h ${l}m`};return n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[t!=null&&t.gateway?n.jsx(Al,{className:"w-3.5 h-3.5 text-emerald-400"}):n.jsx(zl,{className:"w-3.5 h-3.5 text-red-400"}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa]",children:"TITAN Gateway"})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${t!=null&&t.gateway?"bg-emerald-400/10 text-emerald-400":"bg-red-400/10 text-red-400"}`,children:t!=null&&t.gateway?"Online":"Offline"})]}),n.jsxs("div",{className:"flex items-center justify-between px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Vt,{className:`w-3.5 h-3.5 ${t!=null&&t.ollama?"text-emerald-400":"text-red-400"}`}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa]",children:"Ollama"})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${t!=null&&t.ollama?"bg-emerald-400/10 text-emerald-400":"bg-red-400/10 text-red-400"}`,children:t!=null&&t.ollama?"Online":"Offline"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx("div",{className:"text-[9px] text-[#52525b] uppercase tracking-wider",children:"Version"}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] font-mono mt-0.5",children:t==null?void 0:t.version})]}),n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx("div",{className:"text-[9px] text-[#52525b] uppercase tracking-wider",children:"Uptime"}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] font-mono mt-0.5",children:o((t==null?void 0:t.uptime)||0)})]})]})]})})}function Fs({label:t,value:e,icon:s,color:r,unknown:i}){const o=Math.max(0,Math.min(100,Math.round(e)));return n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[s,n.jsx("span",{className:"text-[10px] text-[#52525b] uppercase tracking-wider",children:t})]}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa] font-mono",children:i?"—":`${o}%`})]}),n.jsx("div",{className:"h-1.5 rounded-full bg-[#27272a] overflow-hidden",children:n.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:i?"0%":`${o}%`,backgroundColor:r}})})]})}function Mg(){const[t,e]=w.useState({cpu:0,memory:0,disk:0,load:0,loaded:!1,error:null,diskAvailable:!0});w.useEffect(()=>{let r=!1;async function i(){try{const c=await ge("/api/stats");if(!c.ok){const y=`HTTP ${c.status}`;r||e(E=>({...E,loaded:!0,error:y}));return}const d=await c.json();if(r)return;const l=d.host;if(!l){e(y=>({...y,loaded:!0,error:"no host metrics"}));return}const p=typeof l.cpuPercent=="number"?l.cpuPercent:0,g=typeof l.memPercent=="number"?l.memPercent:0,u=typeof l.diskPercent=="number"?l.diskPercent:0,f=l.cores||1,x=typeof l.loadAvg1=="number"?Math.min(100,l.loadAvg1/f*100):0;e({cpu:p,memory:g,disk:u,load:x,loaded:!0,error:null,diskAvailable:!l.diskError})}catch(c){r||e(d=>({...d,loaded:!0,error:c.message}))}}i();const o=setInterval(i,3e3);return()=>{r=!0,clearInterval(o)}},[]);const s=!t.loaded||!!t.error;return n.jsxs("div",{className:"w-full h-full p-3 overflow-auto",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx(Fs,{label:"CPU",value:t.cpu,icon:n.jsx(Nr,{className:"w-3 h-3 text-[#6366f1]"}),color:"#6366f1",unknown:s}),n.jsx(Fs,{label:"Memory",value:t.memory,icon:n.jsx(Ll,{className:"w-3 h-3 text-[#a78bfa]"}),color:"#a78bfa",unknown:s}),n.jsx(Fs,{label:"Disk",value:t.disk,icon:n.jsx(Il,{className:"w-3 h-3 text-[#10b981]"}),color:"#10b981",unknown:s||!t.diskAvailable}),n.jsx(Fs,{label:"Load",value:t.load,icon:n.jsx(Vt,{className:"w-3 h-3 text-[#f59e0b]"}),color:"#f59e0b",unknown:s})]}),t.error&&n.jsx("div",{className:"mt-2 text-[10px] text-[#ef4444]/80",children:t.error})]})}const Og=[{label:"Nav",source:"system:nav",w:3,h:4,icon:n.jsx(Vl,{className:"w-3.5 h-3.5"})},{label:"Agents",source:"system:agents",w:3,h:4,icon:n.jsx(mo,{className:"w-3.5 h-3.5"})},{label:"Health",source:"system:health",w:3,h:3,icon:n.jsx(Vt,{className:"w-3.5 h-3.5"})},{label:"Stats",source:"system:stats",w:3,h:4,icon:n.jsx(Kl,{className:"w-3.5 h-3.5"})},{label:"Chat",source:"system:chat",w:4,h:5,icon:n.jsx(lo,{className:"w-3.5 h-3.5"})},{label:"Files",source:"system:files",w:4,h:6,icon:n.jsx(pn,{className:"w-3.5 h-3.5"})},{label:"Skills",source:"system:tools",w:5,h:4,icon:n.jsx(Er,{className:"w-3.5 h-3.5"})},{label:"Soma",source:"system:soma",w:6,h:6,icon:n.jsx(Dl,{className:"w-3.5 h-3.5"})},{label:"Intel",source:"system:intelligence",w:6,h:5,icon:n.jsx(yt,{className:"w-3.5 h-3.5"})},{label:"Infra",source:"system:infra",w:6,h:4,icon:n.jsx(Rr,{className:"w-3.5 h-3.5"})},{label:"Tools",source:"system:tools",w:5,h:4,icon:n.jsx(jr,{className:"w-3.5 h-3.5"})},{label:"Settings",source:"system:settings",w:4,h:6,icon:n.jsx(Sr,{className:"w-3.5 h-3.5"})},{label:"Wiki",source:"system:memory-wiki",w:5,h:5,icon:n.jsx(fs,{className:"w-3.5 h-3.5"})},{label:"Research",source:"system:autoresearch",w:5,h:5,icon:n.jsx(uo,{className:"w-3.5 h-3.5"})},{label:"Proposals",source:"system:self-proposals",w:5,h:5,icon:n.jsx(go,{className:"w-3.5 h-3.5"})},{label:"Overview",source:"system:overview",w:5,h:4,icon:n.jsx(eo,{className:"w-3.5 h-3.5"})},{label:"Sessions",source:"system:sessions",w:5,h:4,icon:n.jsx(ps,{className:"w-3.5 h-3.5"})},{label:"Watch",source:"system:watch",w:6,h:5,icon:n.jsx(Vt,{className:"w-3.5 h-3.5"})},{label:"Backup",source:"system:backup",w:5,h:5,icon:n.jsx(ho,{className:"w-3.5 h-3.5"})},{label:"Training",source:"system:training",w:5,h:5,icon:n.jsx(yt,{className:"w-3.5 h-3.5"})},{label:"Recipes",source:"system:recipes",w:5,h:5,icon:n.jsx(fs,{className:"w-3.5 h-3.5"})},{label:"VRAM",source:"system:vram",w:5,h:5,icon:n.jsx(Nr,{className:"w-3.5 h-3.5"})},{label:"Teams",source:"system:teams",w:5,h:5,icon:n.jsx(Cr,{className:"w-3.5 h-3.5"})},{label:"Cron",source:"system:cron",w:5,h:5,icon:n.jsx(ps,{className:"w-3.5 h-3.5"})},{label:"Checkpoints",source:"system:checkpoints",w:5,h:5,icon:n.jsx(mn,{className:"w-3.5 h-3.5"})},{label:"Organism",source:"system:organism",w:5,h:5,icon:n.jsx(Tr,{className:"w-3.5 h-3.5"})},{label:"Fleet",source:"system:fleet",w:5,h:5,icon:n.jsx(fo,{className:"w-3.5 h-3.5"})},{label:"Browser",source:"system:browser",w:5,h:5,icon:n.jsx(to,{className:"w-3.5 h-3.5"})},{label:"Eval",source:"system:eval",w:5,h:5,icon:n.jsx(po,{className:"w-3.5 h-3.5"})}];function Pg(){const t=(e,s,r)=>{window.dispatchEvent(new CustomEvent("titan:widget:add",{detail:{source:e,w:s,h:r}}))};return n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:Og.map(e=>n.jsxs("button",{onClick:()=>t(e.source,e.w,e.h),className:"flex items-center gap-2 px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a] text-[#71717a] hover:text-[#a1a1aa] hover:border-[#3f3f46] hover:bg-[#27272a]/30 transition-all text-left",children:[n.jsx("span",{className:"text-[#6366f1]",children:e.icon}),n.jsx("span",{className:"text-[10px] font-medium",children:e.label})]},e.source))})})}class Wg extends oe.Component{componentDidCatch(e){this.props.onError(e.message)}render(){return this.props.children}}function Bg({name:t,children:e}){const[s,r]=oe.useState(null);return s?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsxs("span",{className:"text-xs text-red-400",children:[t,": ",s]})}):n.jsx(Wg,{onError:r,children:e})}const Ug=oe.lazy(()=>le(()=>import("./legacy-CMWeVEm-.js"),__vite__mapDeps([105,1,2,4])).then(t=>({default:t.Responsive}))),Fg={"system:nav":ll,"system:chat":hl,"system:cmd":bl,"system:soma":xl,"system:command-post":Pp,"system:intelligence":Bp,"system:memory-graph":Fp,"system:voice":$p,"system:infra":Hp,"system:tools":Gp,"system:settings":Yp,"system:files":Kp,"system:settings-general":Xp,"system:settings-security":Zp,"system:settings-audit":tm,"system:settings-specialists":nm,"system:settings-privacy":im,"system:intelligence-autopilot":am,"system:intelligence-workflows":cm,"system:intelligence-learning":um,"system:intelligence-self-improve":fm,"system:intelligence-personas":mm,"system:intelligence-persona-profiles":ym,"system:intelligence-dream":xm,"system:infra-homelab":vm,"system:infra-gpu":km,"system:infra-files":jm,"system:infra-logs":Nm,"system:infra-telemetry":Tm,"system:tools-skills":Am,"system:tools-mcp":Im,"system:tools-integrations":Mm,"system:tools-channels":Pm,"system:tools-mesh":Bm,"system:agents":Ig,"system:health":Dg,"system:stats":Mg,"system:quick-links":Pg,"system:memory-wiki":Fm,"system:autoresearch":zm,"system:self-proposals":Vm,"system:overview":qm,"system:sessions":Km,"system:watch":Xm,"system:backup":Zm,"system:training":tg,"system:recipes":ng,"system:vram":ig,"system:teams":ag,"system:cron":cg,"system:checkpoints":ug,"system:organism":fg,"system:fleet":mg,"system:browser":yg,"system:eval":xg,"system:time-travel":_g,"system:mission-driver":jg,"system:daily-digest":Rg,"system:mission-graph":Lg},$g={lg:12,md:10,sm:6,xs:4,xxs:2},zg=60,Hg={lg:1200,md:996,sm:768,xs:480,xxs:0},Vg=[12,12],Gg=["se","sw","ne","nw","e","w","n","s"],wl=oe.forwardRef(({widget:t,space:e,onRemove:s,style:r,className:i,onMouseDown:o,onMouseUp:c,onTouchStart:d,onTouchEnd:l,children:p},g)=>{const u=w.useCallback(()=>s(t.id),[t.id,s]);return n.jsxs("div",{ref:g,style:r,className:i,onMouseDown:o,onMouseUp:c,onTouchStart:d,onTouchEnd:l,children:[n.jsx(Kg,{widget:t,space:e,onRemove:u}),p]})});wl.displayName="MemoWidgetItem";const qg=oe.memo(wl);function Yg({widget:t,space:e,onRemove:s}){const r=w.useRef(null),i=w.useRef(null),o=w.useRef(e),[c,d]=w.useState(null),[l,p]=w.useState(!0);if(w.useEffect(()=>{o.current=e},[e]),w.useEffect(()=>{if(t.format==="system"||!r.current)return;if(!t.source||t.source.trim()===""){d("Empty widget — no source code"),p(!1);return}p(!0),d(null),i.current=new al(r.current,{onLog:u=>console.log(`[Widget ${t.id}]`,u)}),i.current.setMessageHandler(u=>{var x,y,E,I;const f=o.current;if(u.type==="canvas"&&((x=u.payload)==null?void 0:x.action)==="createWidget"){const v=u.payload.def;if(!v)return{ok:!1,error:"createWidget requires a `def` object"};const A=Number.isFinite(v.w)?v.w:4,m=Number.isFinite(v.h)?v.h:4,k=Number.isFinite(v.x)&&Number.isFinite(v.y)?{x:v.x,y:v.y}:Gs(f.widgets||[],A,m);try{const _=ke.addWidget(f.id,{name:v.name||"Agent Widget",format:v.format||"react",source:v.source||"",x:k.x,y:k.y,w:A,h:m});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0,widgetId:_.id}}catch(_){return{ok:!1,error:_.message}}}if(u.type==="canvas"&&((y=u.payload)==null?void 0:y.action)==="updateWidget"){const{id:v,patch:A}=u.payload;return v?(ke.updateWidget(f.id,v,A||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0,id:v}):{ok:!1,error:"updateWidget requires an `id`"}}if(u.type==="canvas"&&((E=u.payload)==null?void 0:E.action)==="listWidgets")return{ok:!0,widgets:f.widgets||[]};if(u.type==="canvas"&&((I=u.payload)==null?void 0:I.action)==="removeWidget"){const v=u.payload.id;return v?(ke.removeWidget(f.id,v),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}});const g=setTimeout(()=>{p(!1),d("Sandbox timeout: widget took longer than 30s to render. The widget source may have an infinite loop or an unhandled exception. Open DevTools (F12) → Console to see the iframe-side error.")},3e4);return i.current.render(t.format,t.source).then(()=>{clearTimeout(g),p(!1)}).catch(u=>{clearTimeout(g),p(!1),d(String(u))}),()=>{var u;clearTimeout(g),(u=i.current)==null||u.destroy()}},[t.format,t.source,t.id]),t.format==="system"){const g=Fg[t.source];return g?n.jsxs("div",{className:"w-full h-full rounded-xl overflow-hidden flex flex-col group transition-colors shadow-md",style:{background:"var(--color-desk-widget-bg)",border:"1px solid var(--color-desk-border)",boxShadow:"0 4px 12px var(--theme-shadow, rgba(60,40,15,0.15))"},children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b panel-drag-handle cursor-move",style:{borderColor:"var(--color-desk-border-light)",background:"var(--theme-leather, rgba(58,37,24,0.05))"},children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--color-desk-accent)"},children:t.name}),n.jsx("button",{onClick:s,className:"opacity-0 group-hover:opacity-100 text-xs px-1 transition-opacity",style:{color:"var(--color-desk-text-muted)"},children:"×"})]}),n.jsx("div",{className:"flex-1 overflow-auto relative",children:n.jsx(Bg,{name:t.name,children:n.jsx(g,{space:e,widget:t,onRemove:s})})})]}):n.jsxs("div",{className:"w-full h-full flex items-center justify-center text-xs text-red-400",children:["Unknown system widget: ",t.source]})}return n.jsxs("div",{className:"w-full h-full rounded-xl overflow-hidden flex flex-col shadow-md",style:{background:"var(--color-desk-widget-bg)",border:"1px solid var(--color-desk-border)",boxShadow:"0 4px 12px var(--theme-shadow, rgba(60,40,15,0.15))"},children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b panel-drag-handle cursor-move",style:{borderColor:"var(--color-desk-border-light)",background:"var(--theme-leather, rgba(58,37,24,0.05))"},children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--color-desk-accent)"},children:t.name}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("button",{onClick:g=>{g.stopPropagation(),window.dispatchEvent(new CustomEvent("titan:widget:edit",{detail:{spaceId:e.id,widgetId:t.id}}))},onMouseDown:g=>g.stopPropagation(),className:"px-1",style:{color:"var(--color-desk-text-muted)"},title:"Edit widget",children:n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 2 4 4-14 14H4v-4L18 2z"})})}),n.jsx("button",{onClick:s,className:"text-xs px-1",style:{color:"var(--color-desk-text-muted)"},children:"×"})]})]}),n.jsx("div",{className:"flex-1 relative",children:c?n.jsx("div",{className:"p-3 text-xs text-red-400 font-mono whitespace-pre-wrap",children:c}):n.jsxs(n.Fragment,{children:[n.jsx("iframe",{ref:r,className:"w-full h-full border-0",sandbox:"allow-scripts",title:t.name}),l&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-xs",style:{background:"var(--theme-paper, rgba(253,246,227,0.85))",color:"var(--color-desk-text-muted)",fontFamily:"var(--theme-font-display, 'Georgia', serif)"},children:n.jsx("span",{className:"animate-pulse",children:"Loading widget…"})})]})})]})}const Kg=oe.memo(Yg);function Jg(){const{spaceId:t}=Ml(),e=Zi(),[s,r]=w.useState(null),[i]=w.useState(!0),[o,c]=w.useState(!1),[d,l]=w.useState(null),[p,g]=w.useState(!1),[u,f]=w.useState(!1),[x,y]=w.useState(!1),[E,I]=w.useState(1200),v=w.useRef(null),A=w.useRef(null),{info:m,triggerUpdate:k,waitForReload:_}=wf(),[T,S]=w.useState(!1);w.useEffect(()=>{const $=t||"home",F=ke.get($);F?r(F):e("/space/home",{replace:!0})},[t,e]),w.useEffect(()=>{const $=()=>{const se=A.current;if(!se)return null;const Y=new ResizeObserver(te=>{for(const Q of te)I(Q.contentRect.width)});return Y.observe(se),I(se.getBoundingClientRect().width||1200),Y};let F=$();const V=setInterval(()=>{F||(F=$()),F&&clearInterval(V)},200);return()=>{F==null||F.disconnect(),clearInterval(V)}},[s==null?void 0:s.id]),w.useEffect(()=>{const $=F=>{(F.metaKey||F.ctrlKey)&&F.key==="k"&&(F.preventDefault(),f(V=>!V)),(F.metaKey||F.ctrlKey)&&F.key==="j"&&(F.preventDefault(),window.dispatchEvent(new CustomEvent("titan:chat:toggle")))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[]),vf([{key:"?",action:()=>y(!0),description:"Show keyboard shortcuts help"},{key:"g",shift:!0,action:()=>e("/space/command"),description:"Go to Command Post space"},{key:"h",shift:!0,action:()=>e("/space/home"),description:"Go to Home space"},{key:"s",shift:!0,action:()=>e("/space/settings"),description:"Go to Settings space"},{key:"i",shift:!0,action:()=>e("/space/intelligence"),description:"Go to Intelligence space"}]);const C=w.useCallback(()=>{},[]),D=w.useRef(null),j=w.useRef(null),R=w.useCallback($=>{s&&(j.current=$,D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{const F=j.current;!F||!s||(ke.updateLayout(s.id,F.map(V=>({i:V.i,x:V.x,y:V.y,w:V.w,h:V.h}))),j.current=null,D.current=null)},50))},[s]),P=w.useCallback($=>{var se;if(!s)return;const F=(se=s.widgets)==null?void 0:se.find(Y=>Y.id===$);Dn("canvas_panel_removed",{widgetId:$,format:F==null?void 0:F.format,source:F==null?void 0:F.source}),ke.removeWidget(s.id,$);const V=Array.isArray(s.widgets)?s.widgets:[];r({...s,widgets:V.filter(Y=>Y.id!==$)})},[s]),B=w.useCallback($=>{if(!s)return;const F=ke.addWidget(s.id,$),V=Array.isArray(s.widgets)?s.widgets:[];return r({...s,widgets:[...V,F]}),Dn($.format==="system"?"canvas_system_panel_created":"canvas_panel_created",{source:$.source,name:$.name,format:$.format}),F},[s]),z=w.useCallback(($,F)=>{if(!s||!Array.isArray(s.widgets)||s.widgets.length===0)return{x:0,y:0};const V=12,se=new Set;for(const Y of s.widgets)for(let te=0;te<Y.w;te++)for(let Q=0;Q<Y.h;Q++)se.add(`${Y.x+te},${Y.y+Q}`);for(let Y=0;Y<200;Y++)for(let te=0;te<=V-$;te++){let Q=!0;for(let be=0;be<$;be++){for(let Ce=0;Ce<F;Ce++)if(se.has(`${te+be},${Y+Ce}`)){Q=!1;break}if(!Q)break}if(Q)return{x:te,y:Y}}return{x:0,y:0}},[s]),q=w.useCallback(($,F,V=4,se=4)=>{const Y=z(V,se);B({name:F,format:"system",source:$,x:Y.x,y:Y.y,w:V,h:se})},[B,z]);w.useEffect(()=>{const $=F=>{const V=F.detail;if(console.log("[TitanCanvas] titan:space:refresh received:",V),!!s&&(V==null?void 0:V.spaceId)===s.id){const se=ke.get(s.id);se&&(console.log("[TitanCanvas] Refreshing space, widget count:",se.widgets.length),r(se))}};return window.addEventListener("titan:space:refresh",$),()=>window.removeEventListener("titan:space:refresh",$)},[s]),w.useEffect(()=>{const $=F=>{const V=F.detail;if(s&&V!=null&&V.source){const se=Number.isFinite(V.w)?V.w:4,Y=Number.isFinite(V.h)?V.h:4,te=typeof V.name=="string"&&V.name.trim()?V.name.trim():String(V.source).replace("system:","").replace(/-/g," "),Q=V.format==="react"||V.format==="vanilla"||V.format==="html"||V.format==="system"?V.format:String(V.source).startsWith("system:")?"system":"react",be=z(se,Y);B({name:te,format:Q,source:String(V.source),x:be.x,y:be.y,w:se,h:Y})}};return window.addEventListener("titan:widget:add",$),()=>window.removeEventListener("titan:widget:add",$)},[s,B,z]),w.useEffect(()=>{const $=F=>{const V=F.detail;s&&(V==null?void 0:V.spaceId)===s.id&&typeof(V==null?void 0:V.widgetId)=="string"&&l(V.widgetId)};return window.addEventListener("titan:widget:edit",$),()=>window.removeEventListener("titan:widget:edit",$)},[s]),w.useEffect(()=>s?ke.observe(s.id,F=>{console.log("[TitanCanvas] CRDT observer fired, widgets:",F.length),r(V=>V&&{...V,widgets:F})}):void 0,[s==null?void 0:s.id]);const H=w.useMemo(()=>{const $=s==null?void 0:s.widgets;return Array.isArray($)?$.filter(Boolean):[]},[s]),J=w.useMemo(()=>H.map(($,F)=>({i:$.id,x:Number.isFinite($.x)?$.x:F%3*4,y:Number.isFinite($.y)?$.y:Math.floor(F/3)*4,w:Number.isFinite($.w)?$.w:4,h:Number.isFinite($.h)?$.h:4,minW:2,minH:2,maxW:12,maxH:40})),[H]);return s?n.jsxs("div",{className:"h-full w-full flex",children:[n.jsx(xp,{}),n.jsxs("div",{ref:v,className:"flex-1 relative overflow-auto",children:[n.jsx("style",{children:`
968
+ <div style="padding:16px;color:#e4e4e7">Hello, widget!</div>`,iframe:"",system:""};function Tp(t){return String(t||"").startsWith("system:")?"system":"react"}const Rp={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 Ap(t){return t.split(/[-_/]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function Lp({open:t,onClose:e}){const[s,r]=w.useState([]),[i,o]=w.useState([]),[c,d]=w.useState("All"),[l,p]=w.useState(""),[g,u]=w.useState(null),[f,x]=w.useState(!1),[y,E]=w.useState(null);w.useEffect(()=>{t&&(x(!0),ge("/api/widget-gallery").then(m=>m.json()).then(m=>{r(m.templates||[]),o(m.categories||[]),x(!1)}).catch(m=>{E(m.message),x(!1)}))},[t]),w.useEffect(()=>{if(!t)return;const m=k=>{k.key==="Escape"&&e()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,e]);const L=w.useMemo(()=>{const m=c==="All"?s:s.filter(_=>_.category===c),k=l.trim().toLowerCase();return k?m.filter(_=>[_.name,_.description,_.category,..._.tags||[],..._.triggers||[]].join(" ").toLowerCase().includes(k)):m},[c,l,s]);if(!t)return null;const v=async m=>{var k,_,T,S;u(m.id),E(null);try{const C=await ge(`/api/widget-gallery/${encodeURIComponent(m.id)}`);if(!C.ok)throw new Error(`Could not load template (${C.status})`);const D=await C.json(),j={templateId:m.id,templateName:D.name||m.name,source:D.source,format:Tp(D.source),defaultSize:{w:((k=D.defaultSize)==null?void 0:k.w)??((_=m.defaultSize)==null?void 0:_.w)??4,h:((T=D.defaultSize)==null?void 0:T.h)??((S=m.defaultSize)==null?void 0:S.h)??4}};window.dispatchEvent(new CustomEvent("titan:gallery:run-template",{detail:j})),e()}catch(C){E(C.message)}finally{u(null)}},A=["All",...i.map(m=>m.category)];return n.jsx("div",{className:"fixed inset-0 z-[2147483150] flex items-center justify-center p-4 titan-menu-overlay",onClick:e,children:n.jsxs("div",{className:"w-full max-w-4xl titan-modal-surface flex flex-col",style:{height:"min(720px, 90vh)",borderRadius:12},onClick:m=>m.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3",style:{borderBottom:"1px solid var(--theme-menu-border)"},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Er,{className:"w-4 h-4",style:{color:"var(--theme-accent)"}}),n.jsx("h3",{className:"font-semibold text-sm",style:{color:"var(--theme-ink)",fontFamily:"var(--theme-font-display)"},children:"Widget gallery"}),n.jsx("span",{className:"text-[10px]",style:{color:"var(--theme-ink-soft)"},children:f?"Loading…":`${s.length} templates`})]}),n.jsx("button",{onClick:e,className:"titan-close-btn",title:"Close (Esc)","aria-label":"Close",children:n.jsx(js,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"flex items-center gap-1.5 px-5 py-2 border-b border-[#27272a] text-[11px] overflow-x-auto",children:A.map(m=>{var k;return n.jsxs("button",{onClick:()=>d(m),className:`px-2.5 py-1 rounded-full border transition-colors whitespace-nowrap ${c===m?"border-[#6366f1] bg-[#6366f1]/15 text-white":"border-[#27272a] bg-transparent text-[#a1a1aa] hover:border-[#3f3f46] hover:text-white"}`,children:[Ap(m),m!=="All"&&n.jsx("span",{className:"ml-1.5 text-[9px] opacity-70",children:((k=i.find(_=>_.category===m))==null?void 0:k.count)??0})]},m)})}),n.jsx("div",{className:"px-5 py-2 border-b border-[#27272a]",children:n.jsxs("label",{className:"flex items-center gap-2 rounded-lg border border-[#27272a] bg-[#18181b]/60 px-3 py-2",children:[n.jsx(ao,{className:"w-3.5 h-3.5 text-[#71717a]"}),n.jsx("input",{value:l,onChange:m=>p(m.target.value),placeholder:"Search templates...",className:"flex-1 bg-transparent text-xs text-white placeholder:text-[#71717a] outline-none"})]})}),n.jsxs("div",{className:"flex-1 overflow-auto p-4",children:[f&&n.jsx("div",{className:"flex items-center justify-center h-full text-[#a1a1aa] text-sm",children:"Loading templates…"}),y&&n.jsxs("div",{className:"flex items-center justify-center h-full text-[#f87171] text-sm",children:["Error: ",y]}),!f&&!y&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:L.map(m=>n.jsxs("button",{onClick:()=>v(m),disabled:g!==null,className:"text-left p-3 rounded-lg border border-[#27272a] bg-[#18181b]/60 hover:border-[#6366f1]/50 hover:bg-[#18181b] transition-colors group",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{background:Rp[m.category]??"#9ca3af"}}),n.jsx("span",{className:"text-[12px] font-medium text-white truncate",children:m.name})]}),n.jsx(lo,{className:"w-3 h-3 text-[#52525b] group-hover:text-[#a5b4fc] transition-colors shrink-0"})]}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] leading-relaxed line-clamp-2",children:g===m.id?"Adding to canvas...":m.description}),m.tags&&m.tags.length>0&&n.jsx("div",{className:"flex flex-wrap gap-1 mt-1.5",children:m.tags.slice(0,3).map(k=>n.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-[#27272a] text-[#71717a]",children:k},k))})]},m.id))}),L.length===0&&n.jsx("div",{className:"flex items-center justify-center h-40 text-[#a1a1aa] text-sm",children:"No templates in this category."})]}),n.jsxs("div",{className:"mt-4 p-3 rounded-lg border border-dashed border-[#27272a] bg-[#0a0a0e] flex items-start gap-2",children:[n.jsx(bo,{className:"w-3.5 h-3.5 text-[#71717a] mt-0.5 shrink-0"}),n.jsxs("div",{className:"text-[11px] text-[#a1a1aa] leading-relaxed",children:["Don’t see what you want? Open the chat (click the mascot) and describe your widget in plain English. TITAN can build anything that runs inside a sandboxed iframe with access to ",n.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.fetch"}),","," ",n.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.api.call"}),", and"," ",n.jsx("span",{className:"font-mono text-[#d4d4d8]",children:"titan.state"}),"."]})]})]})]})})}const Ip=[{type:"widget",source:"system:nav",name:"Nav Widget",w:3,h:4,icon:n.jsx(bo,{className:"w-4 h-4"})},{type:"widget",source:"system:chat",name:"Chat Widget",w:4,h:5,icon:n.jsx(co,{className:"w-4 h-4"})},{type:"widget",source:"system:soma",name:"SOMA",w:6,h:6,icon:n.jsx(yt,{className:"w-4 h-4"})},{type:"widget",source:"system:command-post",name:"Command Post",w:8,h:6,icon:n.jsx(io,{className:"w-4 h-4"})},{type:"widget",source:"system:intelligence",name:"Intelligence",w:6,h:5,icon:n.jsx(ro,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-graph",name:"Memory Graph",w:8,h:7,icon:n.jsx(Jl,{className:"w-4 h-4"})},{type:"widget",source:"system:voice",name:"Voice",w:5,h:5,icon:n.jsx(uo,{className:"w-4 h-4"})},{type:"widget",source:"system:infra",name:"Infrastructure",w:6,h:4,icon:n.jsx(Rr,{className:"w-4 h-4"})},{type:"widget",source:"system:tools",name:"Tools",w:5,h:4,icon:n.jsx(jr,{className:"w-4 h-4"})},{type:"widget",source:"system:settings",name:"Settings",w:5,h:5,icon:n.jsx(Sr,{className:"w-4 h-4"})},{type:"widget",source:"system:files",name:"Files",w:4,h:6,icon:n.jsx(pn,{className:"w-4 h-4"})},{type:"widget",source:"system:memory-wiki",name:"Memory Wiki",w:6,h:6,icon:n.jsx(fs,{className:"w-4 h-4"})},{type:"widget",source:"system:autoresearch",name:"Autoresearch",w:6,h:6,icon:n.jsx(ho,{className:"w-4 h-4"})},{type:"widget",source:"system:self-proposals",name:"Self-Proposals",w:6,h:6,icon:n.jsx(yo,{className:"w-4 h-4"})},{type:"widget",source:"system:overview",name:"Overview",w:6,h:5,icon:n.jsx(to,{className:"w-4 h-4"})},{type:"widget",source:"system:sessions",name:"Sessions",w:6,h:5,icon:n.jsx(ps,{className:"w-4 h-4"})},{type:"widget",source:"system:watch",name:"Watch",w:8,h:7,icon:n.jsx(Vt,{className:"w-4 h-4"})},{type:"widget",source:"system:backup",name:"Backup Manager",w:6,h:6,icon:n.jsx(fo,{className:"w-4 h-4"})},{type:"widget",source:"system:training",name:"Training Dashboard",w:6,h:6,icon:n.jsx(yt,{className:"w-4 h-4"})},{type:"widget",source:"system:recipes",name:"Recipe Kitchen",w:6,h:6,icon:n.jsx(fs,{className:"w-4 h-4"})},{type:"widget",source:"system:vram",name:"VRAM Monitor",w:6,h:6,icon:n.jsx(Nr,{className:"w-4 h-4"})},{type:"widget",source:"system:teams",name:"Team Hub",w:6,h:6,icon:n.jsx(Cr,{className:"w-4 h-4"})},{type:"widget",source:"system:cron",name:"Cron Scheduler",w:6,h:6,icon:n.jsx(ps,{className:"w-4 h-4"})},{type:"widget",source:"system:checkpoints",name:"Checkpoints",w:6,h:5,icon:n.jsx(mn,{className:"w-4 h-4"})},{type:"widget",source:"system:organism",name:"Organism Monitor",w:6,h:6,icon:n.jsx(Tr,{className:"w-4 h-4"})},{type:"widget",source:"system:fleet",name:"Fleet Router",w:6,h:5,icon:n.jsx(po,{className:"w-4 h-4"})},{type:"widget",source:"system:browser",name:"Browser Tools",w:6,h:5,icon:n.jsx(so,{className:"w-4 h-4"})},{type:"widget",source:"system:eval",name:"Test Lab",w:6,h:6,icon:n.jsx(mo,{className:"w-4 h-4"})}];function vl({currentSpaceId:t,onSpaceSelect:e,onAction:s,onClose:r}){const[i,o]=w.useState(""),[c,d]=w.useState(0),l=w.useRef(null),p=ke.list(),g=w.useMemo(()=>{const u=i.toLowerCase(),f=p.filter(y=>y.id!==t&&y.name.toLowerCase().includes(u)).map(y=>({type:"space",id:y.id,name:y.name,color:y.color})),x=Ip.filter(y=>y.name.toLowerCase().includes(u)).map(y=>({type:"action",action:y,name:y.name}));return[...f,...x]},[i,p,t]);return w.useEffect(()=>{var u;(u=l.current)==null||u.focus()},[]),w.useEffect(()=>{d(0)},[i]),w.useEffect(()=>{const u=f=>{if((f.metaKey||f.ctrlKey)&&f.key.toLowerCase()==="k"){f.preventDefault(),r();return}if(f.key==="Escape"){r();return}if(f.key==="ArrowDown"){f.preventDefault(),d(x=>Math.min(x+1,g.length-1));return}if(f.key==="ArrowUp"){f.preventDefault(),d(x=>Math.max(x-1,0));return}if(f.key==="Enter"){f.preventDefault();const x=g[c];if(!x)return;x.type==="space"&&e(x.id),x.type==="action"&&s(x.action)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[g,c,e,s,r]),n.jsx("div",{className:"fixed inset-0 z-[2147483200] flex items-start justify-center pt-[20vh]",onClick:r,children:n.jsxs("div",{className:"w-full max-w-lg bg-[#18181b]/98 backdrop-blur-xl border border-[#27272a]/60 rounded-2xl shadow-2xl shadow-black/60 overflow-hidden",onClick:u=>u.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-[#27272a]/40",children:[n.jsx(ao,{className:"w-4 h-4 text-[#3f3f46]"}),n.jsx("input",{ref:l,value:i,onChange:u=>o(u.target.value),placeholder:"Search spaces, widgets, actions...",className:"flex-1 bg-transparent text-sm text-[#e4e4e7] placeholder:text-[#3f3f46] outline-none"}),n.jsx("button",{onClick:r,className:"text-[#3f3f46] hover:text-[#71717a]",children:n.jsx(js,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"max-h-[50vh] overflow-auto py-1",children:[g.length===0&&n.jsxs("div",{className:"px-4 py-6 text-center text-xs text-[#52525b]",children:['No results for "',i,'"']}),g.map((u,f)=>n.jsxs("button",{onClick:()=>{u.type==="space"&&e(u.id),u.type==="action"&&s(u.action)},className:`w-full flex items-center gap-3 px-4 py-2.5 text-left transition-colors ${f===c?"bg-[#6366f1]/10 text-[#818cf8]":"text-[#a1a1aa] hover:bg-[#27272a]/30"}`,children:[u.type==="space"?n.jsx("div",{className:"w-4 h-4 rounded-full",style:{background:u.color||"#52525b"}}):n.jsx("span",{className:"text-[#6366f1]/60",children:u.action.icon}),n.jsx("span",{className:"text-sm",children:u.name}),n.jsx("span",{className:"ml-auto text-[10px] text-[#3f3f46] uppercase tracking-wider",children:u.type==="space"?"Space":"Widget"})]},u.type==="space"?u.id:u.action.source))]}),n.jsxs("div",{className:"px-4 py-2 border-t border-[#27272a]/40 flex items-center gap-3 text-[10px] text-[#3f3f46]",children:[n.jsx("span",{children:"↑↓ Navigate"}),n.jsx("span",{children:"↵ Select"}),n.jsx("span",{children:"ESC Close"})]})]})})}const Dp=oe.lazy(()=>le(()=>import("./SomaView-CvHD2r-j.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),Ae={bgBase:"var(--theme-bg-base, var(--color-bg, #09090b))",surface:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-secondary, #18181b)) 82%, transparent)",surfaceSoft:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-tertiary, #27272a)) 62%, transparent)",border:"color-mix(in srgb, var(--theme-metal-dark, var(--color-border, #3f3f46)) 66%, transparent)",ink:"var(--theme-paper-fg, var(--color-text, #fafafa))",inkSoft:"color-mix(in srgb, var(--theme-paper-fg, var(--color-text-secondary, #a1a1aa)) 72%, transparent)",paperFg:"var(--theme-paper-fg, var(--color-text-secondary, #a1a1aa))",accent:"var(--theme-accent, var(--color-accent, #6366f1))",success:"var(--color-success, #22c55e)",error:"var(--color-error, #ef4444)"},sr={background:Ae.bgBase,color:Ae.ink};function _l(){const[t,e]=w.useState(null),[s,r]=w.useState(!1),[i,o]=w.useState(null),c=w.useCallback(async()=>{var p;try{const g=await ge("/api/config");if(!g.ok)throw new Error(`HTTP ${g.status}`);const u=await g.json();e(!!((p=u==null?void 0:u.organism)!=null&&p.enabled)),o(null)}catch(g){o(g.message),e(!1)}},[]);w.useEffect(()=>{c()},[c]);const d=w.useRef(0),l=w.useCallback(async p=>{const g=++d.current;r(!0),o(null);try{const u=await ge("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({organism:{enabled:p}})});if(g!==d.current)return;if(!u.ok)throw new Error(`HTTP ${u.status}`);e(p),window.dispatchEvent(new CustomEvent("titan:soma:changed",{detail:{enabled:p}}))}catch(u){if(g!==d.current)return;o(u.message)}finally{g===d.current&&r(!1)}},[]);return t===null?n.jsx("div",{className:"w-full h-full flex items-center justify-center text-xs",style:{...sr,color:Ae.paperFg},children:"Loading Soma…"}):t?n.jsxs("div",{className:"w-full h-full overflow-auto flex flex-col",style:sr,children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b",style:{background:Ae.surface,borderColor:Ae.border},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full animate-pulse",style:{background:Ae.success}}),n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:Ae.success},children:"Soma active"})]}),n.jsxs("button",{onClick:()=>l(!1),disabled:s,className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[10px] disabled:opacity-60 transition-colors",style:{borderColor:Ae.border,color:Ae.inkSoft,background:Ae.surfaceSoft},title:"Disable Soma",children:[n.jsx(di,{className:"w-3 h-3"}),s?"saving…":"disable"]})]}),n.jsx("div",{className:"flex-1 overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs",style:{color:Ae.paperFg},children:"Loading Soma dashboard…"}),children:n.jsx(Dp,{})})})]}):n.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center gap-4 p-6 text-center",style:sr,children:[n.jsx("div",{className:"w-14 h-14 rounded-full flex items-center justify-center",style:{background:"color-mix(in srgb, var(--theme-accent, var(--color-accent, #6366f1)) 18%, transparent)",border:`1px solid ${Ae.border}`},children:n.jsx(Vt,{className:"w-7 h-7",style:{color:Ae.accent}})}),n.jsxs("div",{className:"space-y-1 max-w-md",children:[n.jsx("h3",{className:"text-lg font-semibold",style:{color:Ae.ink},children:"Soma is off"}),n.jsx("p",{className:"text-xs leading-relaxed",style:{color:Ae.inkSoft},children:"TITAN’s homeostatic drive layer. When enabled, TITAN has a sense of its own state — purpose, curiosity, hunger, safety, social, rest — and will propose work when those drives drift. Every proposal still requires your approval."})]}),n.jsxs("button",{onClick:()=>l(!0),disabled:s,className:"inline-flex items-center gap-2 px-5 py-2.5 rounded-full disabled:opacity-60 disabled:cursor-not-allowed text-sm font-medium transition-colors",style:{background:Ae.accent,color:"var(--theme-bg-base, var(--color-bg, #09090b))"},children:[n.jsx(di,{className:"w-4 h-4"}),s?"Enabling…":"Enable Soma"]}),i&&n.jsx("p",{className:"text-xs",style:{color:Ae.error},children:i}),n.jsx("p",{className:"text-[10px]",style:{color:Ae.paperFg},children:"You can turn this off anytime from the same button."})]})}const Mp={calm:{primary:"#6366f1",glow:"rgba(99,102,241,0.4)",pulse:"rgba(99,102,241,0.15)"},focused:{primary:"#10b981",glow:"rgba(16,185,129,0.4)",pulse:"rgba(16,185,129,0.15)"},excited:{primary:"#f59e0b",glow:"rgba(245,158,11,0.4)",pulse:"rgba(245,158,11,0.15)"},concerned:{primary:"#ef4444",glow:"rgba(239,68,68,0.4)",pulse:"rgba(239,68,68,0.15)"},dreaming:{primary:"#8b5cf6",glow:"rgba(139,92,246,0.4)",pulse:"rgba(139,92,246,0.15)"}},Ee={surface:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-secondary, #18181b)) 90%, transparent)",surfaceSoft:"color-mix(in srgb, var(--theme-bg-grain, var(--color-bg-tertiary, #27272a)) 62%, transparent)",overlay:"color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 56%, transparent)",border:"color-mix(in srgb, var(--theme-metal-dark, var(--color-border, #3f3f46)) 66%, transparent)",metal:"var(--theme-metal, var(--color-border-light, #52525b))",ink:"var(--theme-paper-fg, var(--color-text, #fafafa))",accent:"var(--theme-accent, var(--color-accent, #6366f1))",warning:"var(--color-warning, #f59e0b)"};function Op(t,e,s){if(!s)return{emotion:"dreaming",intensity:.25,activity:"Dormant"};const r=e[0],i=Math.min(1,t/2);switch(r){case"purpose":return{emotion:"focused",intensity:.4+i*.4,activity:"Pursuing purpose"};case"curiosity":return{emotion:"excited",intensity:.4+i*.5,activity:"Exploring"};case"hunger":return{emotion:"focused",intensity:.5+i*.3,activity:"Satiating"};case"safety":return{emotion:"concerned",intensity:.5+i*.4,activity:"Securing"};case"social":return{emotion:"calm",intensity:.3+i*.3,activity:"Connecting"};case"rest":return{emotion:"dreaming",intensity:.2+i*.2,activity:"Recuperating"};default:return t>.5?{emotion:"focused",intensity:i,activity:"Processing"}:{emotion:"calm",intensity:.3,activity:"Observing"}}}function Pp(){const[t,e]=w.useState(!1),[s,r]=w.useState({emotion:"calm",intensity:.3,activity:"Observing"}),[i,o]=w.useState(!1),[c,d]=w.useState({x:280,y:80}),[l,p]=w.useState(!1),g=w.useRef({x:0,y:0}),u=w.useRef(null);w.useEffect(()=>{let v=!1;const A=async()=>{try{const k=await ge("/api/soma/state");if(!k.ok||v)return;const _=await k.json();if(v)return;r(Op(Number((_==null?void 0:_.totalPressure)??0),Array.isArray(_==null?void 0:_.dominantDrives)?_.dominantDrives:[],!!(_!=null&&_.enabled)))}catch{}};A();const m=setInterval(A,15e3);return()=>{v=!0,clearInterval(m)}},[]),w.useEffect(()=>{const v=A=>{var m;(m=u.current)!=null&&m.contains(A.target)||o(!1)};return window.addEventListener("mousedown",v),()=>window.removeEventListener("mousedown",v)},[]);const f=v=>{v.button===0&&(g.current={x:v.clientX-c.x,y:v.clientY-c.y},p(!0))},x=v=>{l&&d({x:v.clientX-g.current.x,y:v.clientY-g.current.y})},y=()=>{p(!1)},E=Mp[s.emotion],L=s.activity==="Dormant"?Ee.metal:Ee.accent;return n.jsxs(n.Fragment,{children:[t&&n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center backdrop-blur-sm",style:{background:Ee.overlay},onClick:()=>e(!1),children:n.jsxs("div",{className:"border rounded-2xl shadow-2xl overflow-hidden",style:{width:"min(900px, 90vw)",height:"min(600px, 80vh)",background:Ee.surface,borderColor:Ee.border,color:Ee.ink,boxShadow:"0 24px 64px color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 72%, transparent)"},onClick:v=>v.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b",style:{borderColor:Ee.border},children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(yt,{className:"w-4 h-4",style:{color:L}}),n.jsx("span",{className:"text-[11px] font-bold uppercase tracking-wider",style:{color:Ee.ink},children:"SOMA Consciousness"})]}),n.jsx("button",{onClick:()=>e(!1),className:"p-1",style:{color:Ee.metal},children:n.jsx(js,{className:"w-4 h-4"})})]}),n.jsx("div",{className:"h-[calc(100%-40px)]",children:n.jsx(_l,{})})]})}),n.jsxs("div",{ref:u,className:"fixed z-50 select-none",style:{left:c.x,top:c.y},onMouseDown:f,onMouseMove:x,onMouseUp:y,onMouseLeave:y,children:[i&&n.jsxs("div",{className:"absolute bottom-full left-0 mb-2 backdrop-blur-xl border rounded-xl shadow-2xl overflow-hidden min-w-[160px] py-1",style:{background:Ee.surface,borderColor:Ee.border,boxShadow:"0 18px 40px color-mix(in srgb, var(--theme-bg-base, var(--color-bg, #09090b)) 70%, transparent)"},children:[n.jsxs("button",{onClick:()=>{e(!0),o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(yt,{className:"w-3.5 h-3.5",style:{color:L}}),"Open SOMA"]}),n.jsxs("button",{onClick:()=>{o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(Er,{className:"w-3.5 h-3.5",style:{color:Ee.warning}}),"Summarize Canvas"]}),n.jsxs("button",{onClick:()=>{o(!1)},className:"w-full flex items-center gap-2 px-3 py-2 text-left text-[11px] transition-colors",style:{color:Ee.ink,background:"transparent"},children:[n.jsx(Al,{className:"w-3.5 h-3.5",style:{color:Ee.accent}}),"Run Self-Check"]})]}),n.jsxs("div",{className:"relative cursor-pointer group",onClick:()=>!l&&e(!0),onContextMenu:v=>{v.preventDefault(),o(!0)},children:[n.jsx("div",{className:"absolute inset-0 rounded-full animate-ping opacity-20",style:{background:E.pulse,animationDuration:`${3-s.intensity*2}s`}}),n.jsx("div",{className:"absolute -inset-2 rounded-full opacity-30 blur-md transition-all duration-1000",style:{background:E.glow}}),n.jsx("div",{className:"relative w-12 h-12 rounded-full flex items-center justify-center transition-all duration-500 hover:scale-110",style:{background:`radial-gradient(circle at 30% 30%, ${L}, ${Ee.metal})`,boxShadow:`0 0 ${20+s.intensity*30}px ${E.glow}, inset 0 0 10px color-mix(in srgb, var(--theme-ink, var(--color-text, #fafafa)) 12%, transparent)`},children:n.jsx(yt,{className:"w-5 h-5",style:{color:Ee.ink}})}),n.jsx("div",{className:"absolute -bottom-5 left-1/2 -translate-x-1/2 whitespace-nowrap",children:n.jsx("span",{className:"text-[9px] font-medium uppercase tracking-wider px-1.5 py-0.5 rounded border",style:{color:Ee.ink,background:Ee.surfaceSoft,borderColor:Ee.border},children:s.activity})})]})]})]})}const Wp=oe.lazy(()=>le(()=>import("./CommandPostHub-Jd5_PAh3.js"),__vite__mapDeps([7,1,2,3,4,8,9,10,11,12,5,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28])));function Bp(){return n.jsx("div",{className:"w-full h-full overflow-auto p-2",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Command Post..."}),children:n.jsx(Wp,{})})})}const Up=oe.lazy(()=>le(()=>import("./IntelligenceView-DqwlFo91.js"),__vite__mapDeps([29,1,2,4])));function Fp(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Intelligence..."}),children:n.jsx(Up,{})})})}const $p=oe.lazy(()=>le(()=>import("./MemoryGraphPanel-BBxgK2Lo.js"),__vite__mapDeps([30,1,2,31,24,28,32])));function zp(){return n.jsx("div",{className:"w-full h-full overflow-auto bg-[#09090b]",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"h-full flex items-center justify-center",children:n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"w-8 h-8 rounded-full border-2 border-[#6366f1]/20 border-t-[#6366f1] animate-spin mx-auto mb-3"}),n.jsx("p",{className:"text-[11px] text-[#52525b]",children:"Loading memory graph..."})]})}),children:n.jsx("div",{className:"p-4",children:n.jsx($p,{})})})})}function Hp(){const[t,e]=w.useState(!1);return t?n.jsx($l,{onClose:()=>e(!1)}):n.jsx("div",{className:"w-full h-full flex flex-col items-center justify-center bg-[#09090b]",children:n.jsxs("button",{onClick:()=>e(!0),className:"group relative flex flex-col items-center gap-4",children:[n.jsxs("div",{className:"relative w-20 h-20 rounded-full flex items-center justify-center transition-all duration-300 group-hover:scale-110",children:[n.jsx("div",{className:"absolute inset-0 rounded-full bg-[#6366f1]/20 animate-pulse"}),n.jsx("div",{className:"absolute inset-0 rounded-full bg-gradient-to-br from-[#6366f1]/30 to-[#4f46e5]/10 border border-[#6366f1]/30"}),n.jsx(uo,{className:"w-8 h-8 text-[#818cf8] relative z-10"})]}),n.jsxs("div",{className:"text-center",children:[n.jsx("p",{className:"text-sm font-medium text-[#a1a1aa]",children:"Tap to speak"}),n.jsx("p",{className:"text-[10px] text-[#52525b] mt-1",children:"F5-TTS · Voice Cloning"})]})]})})}const Vp=oe.lazy(()=>le(()=>import("./InfraView-CYH3ieie.js"),__vite__mapDeps([33,1,2,4])));function Gp(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Infrastructure..."}),children:n.jsx(Vp,{})})})}const qp=oe.lazy(()=>le(()=>import("./ToolsView-UCDMsvb1.js"),__vite__mapDeps([34,1,2,4])));function Yp(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Tools..."}),children:n.jsx(qp,{})})})}const Kp=oe.lazy(()=>le(()=>import("./SettingsView-ZTklN8Q3.js"),__vite__mapDeps([35,1,2,4])));function Jp(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"p-4 text-xs text-[#52525b]",children:"Loading Settings..."}),children:n.jsx(Kp,{})})})}function Xp(){const[t,e]=w.useState([]),[s,r]=w.useState("/"),[i,o]=w.useState(!1),[c,d]=w.useState(null),l=async()=>{o(!0),d(null);try{const p=await ge(`/api/files?path=${encodeURIComponent(s)}`);if(p.ok){const g=await p.json();e(g.files||[])}else e([]),d(`Couldn't load files (HTTP ${p.status})`)}catch(p){e([]),d(`Couldn't reach /api/files — ${p.message}`)}finally{o(!1)}};return w.useEffect(()=>{l()},[s]),n.jsxs("div",{className:"w-full h-full flex flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-[#27272a]/40",children:[n.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-[#71717a]",children:[n.jsx("span",{className:"text-[#6366f1]",children:"~"}),n.jsx(zl,{className:"w-3 h-3"}),n.jsx("span",{children:s})]}),n.jsx("button",{onClick:l,className:"p-1 text-[#3f3f46] hover:text-[#71717a]",children:n.jsx(gn,{className:`w-3 h-3 ${i?"animate-spin":""}`})})]}),n.jsxs("div",{className:"flex-1 overflow-auto",children:[c&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#ef4444]/80",children:c}),!c&&!i&&t.length===0&&n.jsx("div",{className:"px-3 py-2 text-[11px] text-[#52525b]",children:"No files"}),t.map(p=>n.jsxs("button",{onClick:()=>p.type==="directory"&&r(p.path),className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-[#27272a]/20 transition-colors",children:[p.type==="directory"?n.jsx(Hl,{className:"w-3.5 h-3.5 text-[#f59e0b]"}):n.jsx(pn,{className:"w-3.5 h-3.5 text-[#6366f1]"}),n.jsx("span",{className:"text-[12px] text-[#a1a1aa]",children:p.name})]},p.path))]})]})}const Qp=oe.lazy(()=>le(()=>import("./SettingsPanel-C1FbNM3W.js"),__vite__mapDeps([36,1,2,3,4,37,14,5,38,39,24,40,41,42,43])));function Zp(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Qp,{})})})}const em=oe.lazy(()=>le(()=>import("./SecurityPanel-BQ3-aMmO.js"),__vite__mapDeps([44,1,2,37,14])));function tm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(em,{})})})}const sm=oe.lazy(()=>le(()=>import("./AuditPanel-C7rrUHBM.js"),__vite__mapDeps([45,1,2,46,24,47])));function nm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(sm,{})})})}const Ki={researcher:"#60a5fa",engineer:"#f87171",manager:"#a78bfa",ceo:"#fbbf24",general:"#9ca3af"},rm={Recommended:"bg-[#10b981]/15 text-[#10b981] border-[#10b981]/30",Reasoning:"bg-[#8b5cf6]/15 text-[#8b5cf6] border-[#8b5cf6]/30",Fast:"bg-[#0ea5e9]/15 text-[#0ea5e9] border-[#0ea5e9]/30",Light:"bg-[#f59e0b]/15 text-[#f59e0b] border-[#f59e0b]/30","Long Context":"bg-[#6366f1]/15 text-[#6366f1] border-[#6366f1]/30","High Output":"bg-[#ec4899]/15 text-[#ec4899] border-[#ec4899]/30","Needs Key":"bg-[#ef4444]/15 text-[#ef4444] border-[#ef4444]/30"};function im(){const[t,e]=w.useState(null),[s,r]=w.useState({}),[i,o]=w.useState({}),[c,d]=w.useState(null),[l,p]=w.useState({}),[g,u]=w.useState(!0),f=w.useCallback(async()=>{d(null);try{const[E,L]=await Promise.all([ge("/api/specialists"),ge("/api/models")]);if(!E.ok)throw new Error(`Specialists request failed: ${E.status}`);if(!L.ok)throw new Error(`Models request failed: ${L.status}`);const v=await E.json(),A=await L.json();e(v),r(A);const m={};await Promise.all(v.map(async k=>{try{const _=await ge(`/api/specialists/${encodeURIComponent(k.id)}/recommendations`);if(_.ok){const T=await _.json();T.recommendations&&(m[k.id]=T.recommendations)}}catch{}})),o(m)}catch(E){d(E.message)}finally{u(!1)}},[]);w.useEffect(()=>{f()},[f]);const x=w.useCallback(E=>{const L=i[E];if(L&&L.length)return L.map(A=>A.id);const v=new Set;if(s&&typeof s=="object")for(const A of Object.keys(s)){const m=s[A];if(Array.isArray(m))for(const k of m)typeof k=="string"?v.add(k):k&&typeof k=="object"&&"id"in k&&typeof k.id=="string"&&v.add(k.id)}if(Array.isArray(t))for(const A of t)A!=null&&A.activeModel&&v.add(A.activeModel),A!=null&&A.defaultModel&&v.add(A.defaultModel);return Array.from(v).sort((A,m)=>A.localeCompare(m))},[i,s,t]),y=w.useCallback(async(E,L)=>{p(v=>({...v,[E]:"saving"}));try{const v=await ge(`/api/specialists/${encodeURIComponent(E)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:L})});if(!v.ok){const m=await v.text().catch(()=>"");throw new Error(`PATCH failed (${v.status}): ${m||v.statusText}`)}const A=await v.json();e(m=>(m==null?void 0:m.map(k=>k.id===E?{...k,activeModel:A.activeModel??k.defaultModel,overridden:(A.activeModel??k.defaultModel)!==k.defaultModel}:k))??null),p(m=>({...m,[E]:"saved"})),setTimeout(()=>{p(m=>{if(m[E]!=="saved")return m;const k={...m};return delete k[E],k})},1500)}catch(v){p(A=>({...A,[E]:"error"})),d(`${E}: ${v.message}`)}},[]);return g&&!t?n.jsx("div",{className:"h-full w-full flex items-center justify-center text-xs text-[#52525b]",children:"Loading specialists…"}):n.jsxs("div",{className:"w-full h-full flex flex-col bg-[#0a0a0f] text-[#e4e4e7] text-sm",children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-[#27272a]/60",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Cr,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("h3",{className:"font-semibold",children:"Specialist Models"}),n.jsxs("span",{className:"text-[10px] text-[#52525b]",children:[(t==null?void 0:t.length)??0," sub-agents"]})]}),n.jsxs("button",{onClick:()=>{u(!0),f()},className:"flex items-center gap-1 px-2 py-1 rounded text-[11px] text-[#71717a] hover:text-[#e4e4e7] hover:bg-[#27272a]/60 transition-colors",title:"Refresh from server",children:[n.jsx(gn,{className:`w-3 h-3 ${g?"animate-spin":""}`}),"Refresh"]})]}),c&&n.jsxs("div",{className:"mx-4 mt-3 flex items-start gap-2 px-3 py-2 rounded bg-[#7f1d1d]/20 border border-[#7f1d1d]/40 text-[11px] text-[#fca5a5]",children:[n.jsx(fn,{className:"w-3 h-3 mt-0.5 shrink-0"}),n.jsx("span",{className:"font-mono",children:c})]}),n.jsxs("div",{className:"flex-1 overflow-auto px-4 py-3 space-y-3",children:[(t==null?void 0:t.length)===0&&n.jsx("div",{className:"text-xs text-[#52525b] italic",children:"No specialists registered."}),t==null?void 0:t.map(E=>n.jsx(om,{row:E,models:x(E.id),recommendations:i[E.id]??[],state:l[E.id]??"idle",onChange:L=>y(E.id,L),onReset:()=>y(E.id,null)},E.id))]}),n.jsxs("div",{className:"px-4 py-2 border-t border-[#27272a]/60 text-[10px] text-[#52525b]",children:["Overrides write to ",n.jsx("span",{className:"font-mono text-[#71717a]",children:"config.specialists.overrides"}),". Top-scored models are recommended per specialist role."]})]})}function om({row:t,models:e,recommendations:s,state:r,onChange:i,onReset:o}){var u;const c=Ki[t.role]??Ki.general,d=s.find(f=>f.id===t.activeModel),l=s[0]??null,[p,g]=w.useState(!1);return n.jsxs("div",{className:"rounded-lg border border-[#27272a]/60 bg-[#18181b]/70 hover:border-[#3f3f46]/80 transition-colors",children:[n.jsxs("div",{className:"px-3 py-2 flex items-center gap-3",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-[180px]",children:[n.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:c},title:t.role}),n.jsxs("div",{className:"flex flex-col min-w-0",children:[n.jsx("div",{className:"text-sm font-medium truncate",children:t.name}),n.jsx("div",{className:"text-[10px] text-[#52525b] truncate",children:t.title})]})]}),n.jsxs("div",{className:"flex-1 flex items-center gap-2 min-w-0",children:[n.jsx("select",{value:t.activeModel,onChange:f=>i(f.target.value),disabled:r==="saving",className:"flex-1 min-w-0 px-2 py-1 rounded bg-[#0a0a0f] border border-[#27272a] text-xs font-mono focus:outline-none focus:border-[#6366f1] disabled:opacity-50",title:`default: ${t.defaultModel}`,children:e.map(f=>{const x=s.find(L=>L.id===f),y=(x==null?void 0:x.badges)??[],E=y.length?`${f} [${y.join(", ")}]`:f;return n.jsx("option",{value:f,children:E},f)})}),d&&d.badges.length>0&&n.jsx("div",{className:"hidden sm:flex items-center gap-1 shrink-0",children:d.badges.slice(0,3).map(f=>n.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${rm[f]??"bg-[#27272a] text-[#a1a1aa] border-[#27272a]"}`,children:f},f))}),t.overridden&&n.jsxs("button",{onClick:o,disabled:r==="saving",className:"flex items-center gap-1 px-2 py-1 rounded text-[10px] text-[#fbbf24] border border-[#fbbf24]/30 hover:bg-[#fbbf24]/10 transition-colors disabled:opacity-50",title:`Reset to default: ${t.defaultModel}`,children:[n.jsx(oo,{className:"w-3 h-3"}),"Reset"]}),n.jsx("button",{onClick:()=>g(f=>!f),className:"flex items-center justify-center w-6 h-6 rounded hover:bg-[#27272a]/60 text-[#52525b] hover:text-[#a1a1aa] transition-colors",title:"Show recommendation details",children:n.jsx(ci,{className:"w-3.5 h-3.5"})}),n.jsxs("div",{className:"w-5 h-5 flex items-center justify-center shrink-0",children:[r==="saving"&&n.jsx(gn,{className:"w-3.5 h-3.5 animate-spin text-[#6366f1]"}),r==="saved"&&n.jsx(ui,{className:"w-3.5 h-3.5 text-[#10b981]"}),r==="error"&&n.jsx(fn,{className:"w-3.5 h-3.5 text-[#ef4444]"})]})]})]}),p&&n.jsxs("div",{className:"px-3 pb-3 space-y-1.5",children:[d&&n.jsxs("div",{className:"flex items-start gap-2 text-[11px] text-[#a1a1aa]",children:[n.jsx(ci,{className:"w-3 h-3 mt-0.5 shrink-0 text-[#6366f1]"}),n.jsx("span",{children:d.rationale})]}),l&&l.id!==t.activeModel&&n.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-[#10b981]",children:[n.jsx(ui,{className:"w-3 h-3 shrink-0"}),n.jsxs("span",{children:["Recommended upgrade: ",n.jsx("span",{className:"font-mono",children:l.id})," (score ",l.score,"/100)",l.badges.length>0&&n.jsxs("span",{className:"ml-1 text-[#71717a]",children:["[",l.badges.join(", "),"]"]})]})]}),d&&n.jsxs("div",{className:"grid grid-cols-3 gap-2 text-[10px] text-[#52525b]",children:[n.jsxs("div",{children:["Capability: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[d.breakdown.capabilityScore,"/40"]})]}),n.jsxs("div",{children:["Fit: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[d.breakdown.specialistFit,"/40"]})]}),n.jsxs("div",{children:["Availability: ",n.jsxs("span",{className:"text-[#a1a1aa]",children:[d.breakdown.availability,"/20"]})]})]})]}),n.jsxs("div",{className:"px-3 pb-2 flex items-center gap-2 text-[10px] text-[#52525b]",children:[n.jsxs("span",{children:["id: ",n.jsx("span",{className:"font-mono text-[#71717a]",children:t.id})]}),n.jsx("span",{children:"•"}),n.jsxs("span",{children:["role: ",n.jsx("span",{className:"font-mono",style:{color:c},children:t.role})]}),((u=t.templateMatches)==null?void 0:u.length)>0&&n.jsxs(n.Fragment,{children:[n.jsx("span",{children:"•"}),n.jsxs("span",{className:"truncate",children:["templates: ",n.jsx("span",{className:"font-mono text-[#71717a]",children:t.templateMatches.join(", ")})]})]})]})]})}function am(){const[t,e]=w.useState(null),[s,r]=w.useState(null),[i,o]=w.useState(null),[c,d]=w.useState(!1),[l,p]=w.useState(null),[g,u]=w.useState(null),f=w.useCallback(async()=>{p(null);try{const[L,v,A]=await Promise.all([ge("/api/telemetry/consent").then(m=>m.ok?m.json():Promise.reject(new Error(`consent ${m.status}`))),ge("/api/analytics/profile").then(m=>m.ok?m.json():null),ge("/api/telemetry/status").then(m=>m.ok?m.json():null)]);e(L),r(v),A!=null&&A.remote&&o(A.remote)}catch(L){p(L.message)}},[]);w.useEffect(()=>{const L=setInterval(()=>{ge("/api/telemetry/status").then(v=>v.ok?v.json():null).then(v=>{v!=null&&v.remote&&o(v.remote)}).catch(()=>{})},15e3);return()=>clearInterval(L)},[]),w.useEffect(()=>{f()},[f]);const x=w.useCallback(async L=>{d(!0),p(null);try{const v=await ge("/api/telemetry/consent",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!v.ok)throw new Error(`save failed: ${v.status}`);const A=await v.json();e(m=>m?{...m,...A,consentedAt:A.enabled?new Date().toISOString():void 0}:null),u(Date.now()),setTimeout(()=>u(null),2e3)}catch(v){p(v.message)}finally{d(!1)}},[]),y=!!(t!=null&&t.enabled),E=!!(t!=null&&t.crashReports);return n.jsxs("div",{className:"w-full h-full overflow-auto bg-[#0a0a0f] text-[#e4e4e7] text-sm p-4",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[y?n.jsx(Vl,{className:"w-5 h-5 text-[#10b981]"}):n.jsx(Tr,{className:"w-5 h-5 text-[#71717a]"}),n.jsx("h3",{className:"font-semibold text-base",children:"Privacy & Telemetry"}),n.jsx("span",{className:`ml-2 text-[10px] px-2 py-0.5 rounded-full border ${y?"border-[#10b981]/40 bg-[#10b981]/10 text-[#10b981]":"border-[#3f3f46] bg-[#18181b] text-[#71717a]"}`,children:y?"ENABLED":"OFF"}),n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[g&&n.jsxs("span",{className:"text-[11px] text-[#10b981] flex items-center gap-1",children:[n.jsx(Ll,{className:"w-3 h-3"})," Saved"]}),l&&n.jsxs("span",{className:"text-[11px] text-[#ef4444] flex items-center gap-1",children:[n.jsx(Il,{className:"w-3 h-3"})," ",l]}),n.jsxs("button",{onClick:()=>{f()},className:"flex items-center gap-1 px-2 py-1 rounded text-[11px] text-[#71717a] hover:text-[#e4e4e7] hover:bg-[#27272a]/60 transition-colors",children:[n.jsx(gn,{className:"w-3 h-3"})," Refresh"]})]})]}),n.jsx("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/70",children:n.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:y,disabled:c,onChange:L=>x({enabled:L.target.checked,crashReports:E}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"font-medium",children:"Send anonymous usage stats"}),n.jsx("div",{className:"text-xs text-[#a1a1aa] mt-1 leading-relaxed",children:"OS, Node version, CPU/GPU model + VRAM, RAM, TITAN version, and install method. A heartbeat every 5 minutes so we see uptime + concurrent-session counts. Never sends: prompts, file contents, credentials, IP address, or conversations."}),(t==null?void 0:t.consentedAt)&&n.jsxs("div",{className:"text-[10px] text-[#71717a] mt-2",children:["Consented ",n.jsx("span",{className:"font-mono",children:new Date(t.consentedAt).toLocaleString()}),t.consentedVersion&&n.jsxs(n.Fragment,{children:[" on TITAN v",n.jsx("span",{className:"font-mono",children:t.consentedVersion})]})]})]})]})}),n.jsx("div",{className:`mb-4 p-4 rounded-lg border transition-opacity ${y?"border-[#27272a]/60 bg-[#18181b]/70":"border-[#27272a]/30 bg-[#18181b]/30 opacity-60"}`,children:n.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:E,disabled:c||!y,onChange:L=>x({enabled:y,crashReports:L.target.checked}),className:"mt-1 w-4 h-4 accent-[#6366f1] disabled:opacity-50"}),n.jsxs("div",{className:"flex-1",children:[n.jsx("div",{className:"font-medium",children:"Send crash reports"}),n.jsxs("div",{className:"text-xs text-[#a1a1aa] mt-1 leading-relaxed",children:["When TITAN throws an uncaught exception or unhandled promise rejection, send the error class, message, and stack trace. ",n.jsxs("span",{className:"text-[#fbbf24]",children:["Your $HOME path is replaced with the string ",n.jsx("span",{className:"font-mono",children:'"$HOME"'})," before sending."]})]})]})]})}),n.jsxs("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/40",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(fn,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("div",{className:"text-sm font-medium",children:"What would be sent right now"})]}),s?n.jsxs("dl",{className:"grid grid-cols-[160px_1fr] gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-[#71717a]",children:"installId"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.installId.slice(0,32),"…"]}),n.jsx("dt",{className:"text-[#71717a]",children:"os / arch"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.os," / ",s.arch," (",s.osRelease,")"]}),n.jsx("dt",{className:"text-[#71717a]",children:"cpu"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.cpuModel," · ",s.cpuCores,"c"]}),n.jsx("dt",{className:"text-[#71717a]",children:"ram"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[(s.ramTotalMB/1024).toFixed(1)," GB"]}),n.jsx("dt",{className:"text-[#71717a]",children:"gpu"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.gpuVendor,"/",s.gpuName," · ",(s.gpuVramMB/1024).toFixed(1)," GB VRAM"]}),n.jsx("dt",{className:"text-[#71717a]",children:"disk"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.diskTotalGB," GB"]}),n.jsx("dt",{className:"text-[#71717a]",children:"version / node"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[s.version," · ",s.nodeVersion]}),n.jsx("dt",{className:"text-[#71717a]",children:"install method"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7]",children:s.installMethod})]}):n.jsx("div",{className:"text-xs text-[#71717a]",children:"Loading profile preview…"})]}),n.jsxs("div",{className:"mb-4 p-4 rounded-lg border border-[#27272a]/60 bg-[#18181b]/50",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(lo,{className:"w-4 h-4 text-[#6366f1]"}),n.jsx("div",{className:"text-sm font-medium",children:"Delivery status"}),(i==null?void 0:i.lastSuccessAt)&&!i.lastError&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#10b981]/40 bg-[#10b981]/10 text-[#10b981]",children:"FLOWING"}),(i==null?void 0:i.lastError)&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#ef4444]/40 bg-[#ef4444]/10 text-[#ef4444]",children:"ERROR"}),!(i!=null&&i.configured)&&n.jsx("span",{className:"ml-auto text-[10px] px-2 py-0.5 rounded-full border border-[#71717a]/40 bg-[#71717a]/10 text-[#71717a]",children:"NO REMOTE"})]}),i?n.jsxs("dl",{className:"grid grid-cols-[160px_1fr] gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-[#71717a]",children:"remote URL"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7] break-all",children:i.remoteUrl||"—"}),n.jsx("dt",{className:"text-[#71717a]",children:"sent / failed"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7]",children:[n.jsx("span",{className:"text-[#10b981]",children:i.sentCount})," / ",n.jsx("span",{className:i.failedCount>0?"text-[#ef4444]":"text-[#71717a]",children:i.failedCount}),i.lastEventType&&n.jsxs("span",{className:"text-[#71717a]",children:[" · last event: ",n.jsx("span",{className:"text-[#a1a1aa]",children:i.lastEventType})]})]}),n.jsx("dt",{className:"text-[#71717a]",children:"last attempt"}),n.jsxs("dd",{className:"font-mono text-[#e4e4e7] flex items-center gap-1",children:[n.jsx(ps,{className:"w-3 h-3 text-[#71717a]"}),i.lastAttemptAt?new Date(i.lastAttemptAt).toLocaleString():"—"]}),n.jsx("dt",{className:"text-[#71717a]",children:"last success"}),n.jsx("dd",{className:"font-mono text-[#e4e4e7]",children:i.lastSuccessAt?new Date(i.lastSuccessAt).toLocaleString():"—"}),i.lastError&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-[#ef4444]",children:"last error"}),n.jsx("dd",{className:"font-mono text-[#fca5a5] break-all",children:i.lastError})]})]}):n.jsx("div",{className:"text-xs text-[#71717a]",children:"Checking collector reachability…"})]}),n.jsxs("div",{className:"mb-4 p-3 rounded-lg border border-[#27272a]/60 bg-[#0a0a0f]",children:[n.jsx("div",{className:"text-[10px] text-[#71717a] uppercase tracking-wider mb-1",children:"Collector"}),n.jsx("div",{className:"font-mono text-[11px] text-[#a1a1aa] break-all",children:(t==null?void 0:t.remoteUrl)||"—"})]}),n.jsxs("div",{className:"flex items-center gap-3 text-[11px]",children:[n.jsxs("a",{href:"https://github.com/Djtony707/TITAN/blob/main/PRIVACY.md",target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-[#6366f1] hover:underline",children:[n.jsx(hi,{className:"w-3 h-3"})," Read the full PRIVACY.md"]}),n.jsx("span",{className:"text-[#52525b]",children:"·"}),n.jsxs("a",{href:"https://github.com/Djtony707/TITAN/blob/main/src/analytics/collector.ts",target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 text-[#6366f1] hover:underline",children:[n.jsx(hi,{className:"w-3 h-3"})," See the collector source"]})]})]})}const lm=oe.lazy(()=>le(()=>import("./AutopilotPanel-CjrYEF2s.js"),__vite__mapDeps([48,1,2,37,14])));function cm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(lm,{})})})}const dm=oe.lazy(()=>le(()=>import("./WorkflowsPanel-BYtLGQVm.js"),__vite__mapDeps([49,1,2,37,14,3,4,10,11,12,24,27,42,16,28,20,50,51])));function um(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(dm,{})})})}const hm=oe.lazy(()=>le(()=>import("./LearningPanel-DHQSZZGb.js"),__vite__mapDeps([52,1,2,37,14,24,51,53,54,55,27,22,56,31,23,43,12,57,32,26,21,39,58,20,59,60,61,62,63,64,11,65,66,15,40])));function fm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(hm,{})})})}const pm=oe.lazy(()=>le(()=>import("./SelfImprovePanel-C-ylXP-k.js"),__vite__mapDeps([67,1,2,24,38,20,68,54,15,14,42,23,60,28])));function mm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(pm,{})})})}const gm=oe.lazy(()=>le(()=>import("./PersonasPanel-CxDpp_3j.js"),__vite__mapDeps([69,1,2])));function ym(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(gm,{})})})}const bm=oe.lazy(()=>le(()=>import("./PersonaProfilesPanel-qAgZyu1B.js"),__vite__mapDeps([70,1,2,37,14,24,11,16,63,20])));function xm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(bm,{})})})}const wm=oe.lazy(()=>le(()=>import("./DreamPanel-B5M--_sB.js"),__vite__mapDeps([71,1,2,37,14,24])));function vm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(wm,{})})})}const _m=oe.lazy(()=>le(()=>import("./HomelabPanel-CxkWfeeN.js"),__vite__mapDeps([72,1,2,37,14,73,74,4,24,20,21,56,19,31,38,40,17])));function km(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(_m,{})})})}const Sm=oe.lazy(()=>le(()=>import("./NvidiaPanel-CiB9Nlbq.js"),__vite__mapDeps([75,1,2,24,43,38,66,32])));function jm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Sm,{})})})}const Em=oe.lazy(()=>le(()=>import("./FilesPanel-B5RpGquX.js"),__vite__mapDeps([76,1,2,27,24,14,77,20,12,28,43,41,11,22,55,56,31,23,51,57,32,26,21,39,58,59,60,61,62,63,64,65,66,15,40])));function Nm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Em,{})})})}const Cm=oe.lazy(()=>le(()=>import("./LogsPanel-XfC4fyQ6.js"),__vite__mapDeps([78,1,2,24])));function Tm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Cm,{})})})}const Rm=oe.lazy(()=>le(()=>import("./TelemetryPanel-BEEWcoNE.js"),__vite__mapDeps([79,1,2,73,20,18,19,56])));function Am(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Rm,{})})})}const Lm=oe.lazy(()=>le(()=>import("./SkillsPanel-eyCYqSuP.js"),__vite__mapDeps([80,1,2,37,14,32,28,41])));function Im(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Lm,{})})})}const Dm=oe.lazy(()=>le(()=>import("./McpPanel-CBN7xizL.js"),__vite__mapDeps([81,1,2,82,24,27,56,61,28])));function Mm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Dm,{})})})}const Om=oe.lazy(()=>le(()=>import("./IntegrationsPanel-CPZclot5.js"),__vite__mapDeps([83,1,2,82,38,43,14])));function Pm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Om,{})})})}const Wm=oe.lazy(()=>le(()=>import("./ChannelsPanel-CeIEB9Es.js"),__vite__mapDeps([84,1,2,37,14,24,38,43])));function Bm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Wm,{})})})}const Um=oe.lazy(()=>le(()=>import("./MeshPanel-GFPkWStS.js"),__vite__mapDeps([85,1,2,86,24,65])));function Fm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Um,{})})})}const $m=oe.lazy(()=>le(()=>import("./MemoryWikiPanel-BNv9ycwr.js"),__vite__mapDeps([87,1,2,37,14,77,20,32,51])));function zm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx($m,{})})})}const Hm=oe.lazy(()=>le(()=>import("./AutoresearchPanel-CBdGRAdZ.js"),__vite__mapDeps([88,1,2,58,42,16,24,68,54,20,14])));function Vm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Hm,{})})})}const Gm=oe.lazy(()=>le(()=>import("./SelfProposalsPanel-d5W-0A3P.js"),__vite__mapDeps([89,1,2,37,14,20,55,27,22,56,31,23,51,43,12,57,32,26,21,39,58,59,60,61,62,63,24,64,11,65,66,15,40])));function qm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Gm,{})})})}const Ym=oe.lazy(()=>le(()=>import("./OverviewPanel-DF7eBJCF.js"),__vite__mapDeps([90,1,2,73,37,14,74,4,20,21,56,91])));function Km(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Ym,{})})})}const Jm=oe.lazy(()=>le(()=>import("./SessionsPanel-DzbNc8iW.js"),__vite__mapDeps([92,1,2,37,14,3,4,86,10,11,12,32,28])));function Xm(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Jm,{})})})}const Qm=oe.lazy(()=>le(()=>import("./WatchView-DDNt13KH.js"),__vite__mapDeps([93,1,2,9])));function Zm(){return n.jsx("div",{className:"w-full h-full overflow-auto",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(Qm,{})})})}const eg=oe.lazy(()=>le(()=>import("./BackupPanel-BhU-utCn.js"),__vite__mapDeps([94,1,2,37,14,27,24,59,38])));function tg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(eg,{})})})}const sg=oe.lazy(()=>le(()=>import("./TrainingPanel-CmJXLn4n.js"),__vite__mapDeps([95,1,2,37,14,24,41])));function ng(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(sg,{})})})}const rg=oe.lazy(()=>le(()=>import("./RecipesPanel-DqMMQnyc.js"),__vite__mapDeps([96,1,2,37,14,24,51,42,28])));function ig(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(rg,{})})})}const og=oe.lazy(()=>le(()=>import("./VramPanel-h6zjNx-6.js"),__vite__mapDeps([97,1,2,37,14,24])));function ag(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(og,{})})})}const lg=oe.lazy(()=>le(()=>import("./TeamsPanel-fa--osWi.js"),__vite__mapDeps([98,1,2,37,14,24,28])));function cg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(lg,{})})})}const dg=oe.lazy(()=>le(()=>import("./CronPanel-COkBBcTV.js"),__vite__mapDeps([99,1,2,37,14,24,20,50,28])));function ug(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(dg,{})})})}const hg=oe.lazy(()=>le(()=>import("./CheckpointsPanel-BkqqvLDL.js"),__vite__mapDeps([100,1,2,37,14,24,43,28])));function fg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(hg,{})})})}const pg=oe.lazy(()=>le(()=>import("./OrganismPanel-d6mPFcBq.js"),__vite__mapDeps([101,1,2,37,14,24,38])));function mg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(pg,{})})})}const gg=oe.lazy(()=>le(()=>import("./FleetPanel-1g-MrF81.js"),__vite__mapDeps([102,1,2,37,14,24,60])));function yg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(gg,{})})})}const bg=oe.lazy(()=>le(()=>import("./BrowserPanel-Dr-B5Kva.js"),__vite__mapDeps([103,1,2,37,14])));function xg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(bg,{})})})}const wg=oe.lazy(()=>le(()=>import("./EvalPanel-CY1kmmoG.js"),__vite__mapDeps([104,1,2,37,14,24,42])));function vg(){return n.jsx("div",{className:"w-full h-full overflow-auto p-4",children:n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"text-xs text-[#52525b]",children:"Loading..."}),children:n.jsx(wg,{})})})}function _g(t){const e=Date.now()-new Date(t).getTime();if(!Number.isFinite(e)||e<0)return t;const s=Math.floor(e/1e3);if(s<60)return`${s}s ago`;const r=Math.floor(s/60);if(r<60)return`${r}m ago`;const i=Math.floor(r/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function kg(t){const e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e>=0?t.slice(e+1):t}function Sg(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(""),[c,d]=w.useState(null),[l,p]=w.useState(""),[g,u]=w.useState(!1),[f,x]=w.useState(null),[y,E]=w.useState(null),[L,v]=w.useState(null),A=w.useCallback(async()=>{r(!0),x(null);try{const C=await ge("/api/time-travel/checkpoints?limit=100");if(!C.ok)throw new Error(`${C.status} ${C.statusText}`);const D=await C.json();e(D.checkpoints||[])}catch(C){x(C.message||"Failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{A()},[A]);const m=w.useCallback((C,D)=>{v({kind:C,message:D}),setTimeout(()=>v(null),4e3)},[]),k=w.useCallback(async C=>{d(C),p(""),u(!0);try{const D=await ge(`/api/time-travel/diff/${encodeURIComponent(C)}`);if(!D.ok)throw new Error(`${D.status} ${D.statusText}`);const j=await D.json();p(j.diff||"(no diff returned)")}catch(D){p(`Failed to load diff: ${D.message}`)}finally{u(!1)}},[]),_=w.useCallback(C=>{E(C)},[]),T=w.useCallback(async()=>{if(!y)return;const C=y;E(null);try{const D=await ge(`/api/time-travel/restore/${encodeURIComponent(C)}`,{method:"POST"});if(!D.ok)throw new Error(`${D.status} ${D.statusText}`);const j=await D.json();j.ok?(m("ok",j.message||`Restored to ${C.slice(0,8)}.`),A()):m("err",j.message||"Restore failed.")}catch(D){m("err",D.message||"Restore failed.")}},[y,A,m]),S=w.useMemo(()=>{const C=i.trim().toLowerCase();return C?t.filter(D=>D.filePath.toLowerCase().includes(C)||D.toolName.toLowerCase().includes(C)||D.id.toLowerCase().includes(C)):t},[t,i]);return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",fontSize:12,background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Time Travel"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," file checkpoints · newest first"]})]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("input",{type:"text",value:i,onChange:C=>o(C.target.value),placeholder:"Filter by file or tool…",style:{background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:6,color:"#fff",fontSize:11,padding:"4px 8px",outline:"none",width:180}}),n.jsx("button",{onClick:A,disabled:s,title:"Refresh checkpoint list",style:{background:"rgba(99,102,241,0.15)",border:"1px solid rgba(99,102,241,0.35)",borderRadius:6,color:"#c7d2fe",fontSize:11,padding:"4px 10px",cursor:s?"wait":"pointer"},children:s?"…":"Refresh"})]})]}),L&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,background:L.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${L.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:L.kind==="ok"?"#86efac":"#fca5a5",fontSize:11},children:L.message}),f&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,background:"rgba(239,68,68,0.12)",border:"1px solid rgba(239,68,68,0.3)",color:"#fca5a5",fontSize:11},children:f}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[n.jsx("div",{style:{flex:1,overflow:"auto",borderRight:"1px solid rgba(255,255,255,0.06)"},children:s&&t.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)"},children:"Loading checkpoints…"}):S.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)"},children:i?"No matches for that filter.":"No file checkpoints yet. They're created automatically whenever TITAN writes or edits a file."}):S.map(C=>n.jsxs("div",{onClick:()=>k(C.id),style:{padding:"8px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",cursor:"pointer",background:c===C.id?"rgba(99,102,241,0.08)":"transparent",borderLeft:c===C.id?"2px solid #818cf8":"2px solid transparent"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:2},children:[n.jsx("span",{style:{fontSize:11,fontFamily:"ui-monospace, monospace",color:"#a5b4fc"},children:C.commitHash.slice(0,8)}),n.jsx("span",{style:{fontSize:10,color:"rgba(255,255,255,0.5)"},children:_g(C.timestamp)})]}),n.jsx("div",{style:{fontSize:12,color:"#e2e8f5",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:C.filePath,children:kg(C.filePath)}),n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:4},children:[n.jsxs("span",{style:{fontSize:10,color:"rgba(255,255,255,0.4)"},children:["before ",n.jsx("code",{style:{color:"#fbbf24"},children:C.toolName})]}),n.jsx("button",{onClick:D=>{D.stopPropagation(),_(C.id)},title:"Restore this file to the state it was in at this checkpoint",style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"rgba(34,197,94,0.12)",border:"1px solid rgba(34,197,94,0.3)",color:"#86efac",cursor:"pointer"},children:"Restore"})]})]},C.id))}),n.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:c?g?n.jsx("div",{style:{color:"rgba(255,255,255,0.4)"},children:"Loading diff…"}):n.jsx("pre",{style:{margin:0,fontFamily:'ui-monospace, "SF Mono", Menlo, monospace',fontSize:11,lineHeight:1.5,color:"#e2e8f5",whiteSpace:"pre-wrap",wordBreak:"break-all"},children:(l||"").split(`
969
+ `).map((C,D)=>{let j="rgba(255,255,255,0.7)";return C.startsWith("+")&&!C.startsWith("+++")?j="#86efac":C.startsWith("-")&&!C.startsWith("---")?j="#fca5a5":C.startsWith("@@")?j="#a5b4fc":(C.startsWith("diff")||C.startsWith("index")||C.startsWith("+++")||C.startsWith("---"))&&(j="rgba(255,255,255,0.45)"),n.jsx("div",{style:{color:j},children:C||" "},D)})}):n.jsx("div",{style:{color:"rgba(255,255,255,0.4)"},children:"Select a checkpoint on the left to see its diff vs the current file."})})]}),y&&n.jsx("div",{onClick:()=>E(null),style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.5)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:10},children:n.jsxs("div",{onClick:C=>C.stopPropagation(),style:{background:"#0d0f1d",border:"1px solid rgba(255,255,255,0.1)",borderRadius:10,padding:18,maxWidth:380,color:"#e2e8f5"},children:[n.jsx("div",{style:{fontSize:14,fontWeight:600,marginBottom:8},children:"Restore this checkpoint?"}),n.jsxs("div",{style:{fontSize:12,color:"rgba(255,255,255,0.7)",marginBottom:12},children:["The file will be overwritten with its state at ",n.jsx("code",{children:y.slice(0,8)}),". A NEW checkpoint of the current state is taken first, so you can always come back."]}),n.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[n.jsx("button",{onClick:()=>E(null),style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.1)",color:"#e2e8f5",borderRadius:6,padding:"6px 12px",fontSize:12,cursor:"pointer"},children:"Cancel"}),n.jsx("button",{onClick:T,style:{background:"rgba(34,197,94,0.18)",border:"1px solid rgba(34,197,94,0.4)",color:"#86efac",borderRadius:6,padding:"6px 12px",fontSize:12,cursor:"pointer"},children:"Restore"})]})]})})]})}const Ji=5e3,Xi={planning:"#a5b4fc",delegating:"#60a5fa",observing:"#22d3ee",iterating:"#f59e0b",verifying:"#a78bfa",reporting:"#34d399",blocked:"#facc15",escalated:"#fb7185",done:"#34d399",failed:"#ef4444",cancelled:"#737373"};function jg(t){if(!Number.isFinite(t)||t<0)return"—";const e=Math.floor(t/1e3);if(e<60)return`${e}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),i=s%60;return`${r}h ${i}m`}function Eg(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function Ng(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(null),[c,d]=w.useState(!1),[l,p]=w.useState(""),[g,u]=w.useState(2),[f,x]=w.useState(!1),[y,E]=w.useState(null),L=w.useCallback(async()=>{try{const _=await ge("/api/missions/active");if(!_.ok)throw new Error(`${_.status} ${_.statusText}`);const T=await _.json();e(T.missions||[]),o(null)}catch(_){o(_.message||"failed to load")}finally{r(!1)}},[]);w.useEffect(()=>{L();const _=setInterval(L,Ji);return()=>clearInterval(_)},[L]);const v=w.useCallback((_,T)=>{E({kind:_,message:T}),setTimeout(()=>E(null),5e3)},[]),A=w.useCallback(async()=>{var T;const _=l.trim();if(_.length<10){v("err","Describe the mission (>=10 chars).");return}x(!0);try{const S=await ge("/api/mission/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:_,budgetUsd:g})});if(!S.ok)throw new Error(`${S.status} ${S.statusText}`);const C=await S.json();v("ok",C.message||`Mission "${((T=C.goal)==null?void 0:T.title)??"?"}" launched.`),p(""),d(!1),L()}catch(S){v("err",S.message||"launch failed")}finally{x(!1)}},[l,g,L,v]),m=w.useCallback(async _=>{try{const T=await ge(`/api/mission/${encodeURIComponent(_)}/cancel`,{method:"POST"});if(!T.ok)throw new Error(`${T.status} ${T.statusText}`);v("ok","Mission marked for cancellation."),L()}catch(T){v("err",T.message||"cancel failed")}},[L,v]),k=w.useMemo(()=>{const _={delegating:0,observing:1,iterating:2,verifying:3,planning:4,reporting:5,blocked:6,escalated:7};return[...t].sort((T,S)=>(_[T.phase]??99)-(_[S.phase]??99))},[t]);return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Mission Driver"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," active · polling every ",Ji/1e3,"s"]})]}),n.jsxs("div",{style:{display:"flex",gap:6},children:[n.jsx("button",{onClick:()=>d(_=>!_),title:"Launch a new autonomous mission",style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid rgba(99,102,241,0.4)",background:c?"rgba(99,102,241,0.25)":"rgba(99,102,241,0.12)",color:"#c7d2fe",cursor:"pointer"},children:c?"× Close":"+ New mission"}),n.jsx("button",{onClick:L,title:"Refresh",style:{fontSize:11,padding:"4px 10px",borderRadius:6,border:"1px solid rgba(255,255,255,0.1)",background:"rgba(255,255,255,0.04)",color:"#e2e8f5",cursor:"pointer"},children:"↻"})]})]}),y&&n.jsx("div",{style:{margin:"8px 14px 0",padding:"6px 10px",borderRadius:6,fontSize:11,background:y.kind==="ok"?"rgba(34,197,94,0.12)":"rgba(239,68,68,0.12)",border:`1px solid ${y.kind==="ok"?"rgba(34,197,94,0.3)":"rgba(239,68,68,0.3)"}`,color:y.kind==="ok"?"#86efac":"#fca5a5"},children:y.message}),c&&n.jsxs("div",{style:{padding:12,borderBottom:"1px solid rgba(255,255,255,0.06)",background:"rgba(99,102,241,0.04)"},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.6,color:"#a5b4fc",marginBottom:6},children:"Describe the mission"}),n.jsx("textarea",{value:l,onChange:_=>p(_.target.value),placeholder:"e.g. 'Research the top 5 AI agent frameworks for 2026, summarize their differentiation in a markdown report, and save to ~/Documents/agent-research.md'",rows:3,style:{width:"100%",background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:12,padding:"6px 10px",resize:"vertical",fontFamily:"inherit",boxSizing:"border-box"}}),n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:8,gap:8},children:[n.jsxs("label",{style:{fontSize:11,color:"rgba(255,255,255,0.6)"},children:["Budget cap: $",n.jsx("input",{type:"number",value:g,onChange:_=>u(Math.max(.05,Math.min(50,Number(_.target.value)||2))),step:"0.5",min:"0.05",max:"50",style:{width:60,marginLeft:4,background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:4,color:"#fff",fontSize:11,padding:"2px 6px"}})]}),n.jsx("button",{onClick:A,disabled:f||l.trim().length<10,style:{fontSize:12,padding:"6px 14px",borderRadius:6,border:"none",background:f?"rgba(255,255,255,0.05)":"rgba(34,197,94,0.18)",color:"#86efac",cursor:f?"wait":"pointer",fontWeight:600},children:f?"Decomposing…":"🚀 Launch"})]})]}),n.jsxs("div",{style:{flex:1,overflow:"auto",padding:8},children:[i&&n.jsx("div",{style:{padding:10,color:"#fca5a5",fontSize:11},children:i}),s&&t.length===0?n.jsx("div",{style:{padding:16,color:"rgba(255,255,255,0.4)",fontSize:12},children:"Loading missions…"}):k.length===0?n.jsxs("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:["No active missions.",n.jsx("br",{}),n.jsx("span",{style:{fontSize:11,color:"rgba(255,255,255,0.35)"},children:'Click "+ New mission" to launch one.'})]}):k.map(_=>{const T=Xi[_.phase]??"#94a3b8",S=_.subtasks.total>0?Math.round(_.subtasks.completed/_.subtasks.total*100):0;return n.jsxs("div",{style:{padding:"10px 12px",marginBottom:6,borderRadius:8,background:"rgba(255,255,255,0.025)",border:`1px solid ${_.phase==="blocked"?"rgba(250,204,21,0.4)":"rgba(255,255,255,0.06)"}`},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[n.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#fafafa",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:_.title,children:_.title}),n.jsx("button",{onClick:()=>m(_.goalId),title:"Cancel this mission",style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"rgba(239,68,68,0.1)",border:"1px solid rgba(239,68,68,0.3)",color:"#fca5a5",cursor:"pointer",marginLeft:6},children:"Cancel"})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:10,color:"rgba(255,255,255,0.7)"},children:[n.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"1px 6px",borderRadius:4,background:`${T}22`,border:`1px solid ${T}55`,color:T,textTransform:"uppercase",letterSpacing:.5,fontWeight:600,fontSize:9},children:_.phase}),n.jsxs("span",{children:[_.subtasks.completed,"/",_.subtasks.total," subtasks (",S,"%)"]}),n.jsx("span",{children:"·"}),n.jsx("span",{children:Eg(_.budget.costUsd)}),n.jsx("span",{children:"·"}),n.jsx("span",{children:jg(Date.now()-new Date(_.startedAt).getTime())})]}),_.blockedReason&&n.jsxs("div",{style:{marginTop:6,padding:"6px 8px",borderRadius:4,background:"rgba(250,204,21,0.08)",border:"1px solid rgba(250,204,21,0.25)",fontSize:11,color:"#fde68a"},children:[n.jsx("strong",{children:"Blocked:"})," ",_.blockedReason.question??"(no reason)"]}),_.lastHistory.length>0&&n.jsx("div",{style:{marginTop:6,fontSize:10,color:"rgba(255,255,255,0.45)",display:"flex",flexDirection:"column",gap:1},children:_.lastHistory.slice(-3).map((C,D)=>n.jsxs("div",{style:{display:"flex",gap:6,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n.jsx("span",{style:{color:Xi[C.phase]??"rgba(255,255,255,0.6)",minWidth:70,fontFamily:"ui-monospace, monospace",fontSize:9},children:C.phase}),n.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:C.note??""})]},D))})]},_.goalId)})]})]})}const Cg=6e4,Tg=[{label:"6h",hours:6},{label:"24h",hours:24},{label:"7d",hours:168}];function Rg(t){return t===0?"$0":t<.01?"$<0.01":`$${t.toFixed(2)}`}function Ag(t){return t<1e3?String(t):t<1e6?`${(t/1e3).toFixed(1)}k`:`${(t/1e6).toFixed(2)}M`}function Lg(){const[t,e]=w.useState(24),[s,r]=w.useState(null),[i,o]=w.useState(!0),[c,d]=w.useState(null),l=w.useCallback(async()=>{o(!0);try{const p=await ge(`/api/missions/digest?hours=${t}`);if(!p.ok)throw new Error(`${p.status} ${p.statusText}`);const g=await p.json();r(g),d(null)}catch(p){d(p.message||"failed")}finally{o(!1)}},[t]);return w.useEffect(()=>{l();const p=setInterval(l,Cg);return()=>clearInterval(p)},[l]),n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsxs("div",{children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Daily digest"}),n.jsx("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:"what TITAN did while you were away"})]}),n.jsx("div",{style:{display:"flex",gap:4},children:Tg.map(p=>n.jsx("button",{onClick:()=>e(p.hours),style:{fontSize:10,padding:"3px 8px",borderRadius:4,border:"1px solid rgba(255,255,255,0.1)",background:t===p.hours?"rgba(99,102,241,0.25)":"rgba(255,255,255,0.03)",color:t===p.hours?"#c7d2fe":"rgba(255,255,255,0.65)",cursor:"pointer"},children:p.label},p.label))})]}),s&&n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:8},children:[n.jsx(Ws,{label:"Done",value:s.stats.completed,color:"#34d399"}),n.jsx(Ws,{label:"Failed",value:s.stats.failed,color:s.stats.failed>0?"#fca5a5":"rgba(255,255,255,0.5)"}),n.jsx(Ws,{label:"Active",value:s.stats.active,color:"#60a5fa"}),n.jsx(Ws,{label:"Blocked",value:s.stats.blocked,color:s.stats.blocked>0?"#facc15":"rgba(255,255,255,0.5)"})]}),s&&(s.stats.totalCostUsd>0||s.stats.totalTokens>0)&&n.jsxs("div",{style:{padding:"6px 14px",borderBottom:"1px solid rgba(255,255,255,0.04)",fontSize:10,color:"rgba(255,255,255,0.55)",display:"flex",justifyContent:"space-between"},children:[n.jsxs("span",{children:["Spend: ",n.jsx("strong",{style:{color:"#e2e8f5"},children:Rg(s.stats.totalCostUsd)})]}),n.jsxs("span",{children:["Tokens: ",n.jsx("strong",{style:{color:"#e2e8f5"},children:Ag(s.stats.totalTokens)})]})]}),n.jsxs("div",{style:{flex:1,overflow:"auto",padding:14},children:[i&&!s&&n.jsx("div",{style:{color:"rgba(255,255,255,0.4)",fontSize:11},children:"Loading…"}),c&&n.jsx("div",{style:{color:"#fca5a5",fontSize:11},children:c}),s&&n.jsxs(n.Fragment,{children:[n.jsx("pre",{style:{margin:0,fontFamily:'ui-monospace, "SF Mono", Menlo, monospace',fontSize:11,lineHeight:1.55,color:"#e2e8f5",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s.summaryText||"(no activity in this window)"}),s.recentLessons.length>0&&n.jsxs("div",{style:{marginTop:16,paddingTop:12,borderTop:"1px solid rgba(255,255,255,0.06)"},children:[n.jsx("div",{style:{fontSize:10,textTransform:"uppercase",letterSpacing:.6,color:"#a5b4fc",marginBottom:6},children:"Lessons learned (Reflexion)"}),s.recentLessons.map((p,g)=>n.jsxs("div",{style:{fontSize:11,color:"rgba(255,255,255,0.8)",padding:"4px 0",borderBottom:"1px dashed rgba(255,255,255,0.04)"},children:["• ",p]},g))]})]})]})]})}function Ws({label:t,value:e,color:s}){return n.jsxs("div",{style:{textAlign:"center",padding:"6px 4px",borderRadius:6,background:"rgba(255,255,255,0.02)"},children:[n.jsx("div",{style:{fontSize:18,fontWeight:700,color:s,lineHeight:1},children:e}),n.jsx("div",{style:{fontSize:9,color:"rgba(255,255,255,0.5)",textTransform:"uppercase",letterSpacing:.5,marginTop:4},children:t})]})}const Bs={pending:"#737373",running:"#60a5fa",done:"#34d399",failed:"#ef4444",skipped:"#a78bfa"},Qi=6e3,_t=180,nr=64,Zi=96,Us=24;function Ig(t){const e=new Map,s=new Map(t.map(i=>[i.id,i])),r=(i,o)=>{if(e.has(i))return e.get(i);if(o.has(i))return 0;const c=s.get(i);if(!c)return 0;o.add(i);const d=(c.dependsOn??[]).filter(p=>s.has(p)),l=d.length===0?0:Math.max(...d.map(p=>r(p,o)))+1;return o.delete(i),e.set(i,l),l};for(const i of t)r(i.id,new Set);return e}function Dg(){const[t,e]=w.useState([]),[s,r]=w.useState(null),[i,o]=w.useState(null),[c,d]=w.useState(null),[l,p]=w.useState(null),g=w.useCallback(async()=>{try{const v=await ge("/api/missions/active");if(!v.ok)throw new Error(`${v.status} ${v.statusText}`);const m=(await v.json()).missions||[];e(m),!s&&m.length>0&&r(m[0].goalId)}catch(v){d(v.message||"failed")}},[s]),u=w.useCallback(async v=>{try{const A=await ge(`/api/mission/${encodeURIComponent(v)}`);if(!A.ok)throw new Error(`${A.status} ${A.statusText}`);const m=await A.json();o(m),d(null)}catch(A){d(A.message||"failed to load mission"),o(null)}},[]);w.useEffect(()=>{g();const v=setInterval(g,Qi);return()=>clearInterval(v)},[g]),w.useEffect(()=>{if(!s){o(null);return}u(s);const v=setInterval(()=>u(s),Qi);return()=>clearInterval(v)},[s,u]);const{layout:f,edges:x,viewBox:y}=w.useMemo(()=>{if(!(i!=null&&i.goal.subtasks))return{layout:[],edges:[],viewBox:"0 0 600 200"};const v=i.goal.subtasks,A=Ig(v),m=new Map;for(const R of v){const P=A.get(R.id)??0;m.has(P)||m.set(P,[]),m.get(P).push(R)}const k=Array.from(m.keys()).sort((R,P)=>R-P),_=Math.max(...Array.from(m.values()).map(R=>R.length),1),T=Math.max(640,_*(_t+Us)+Us),S=k.length*Zi+nr+40,C=new Map,D=[];for(const R of k){const P=m.get(R),B=P.length*_t+(P.length-1)*Us,z=(T-B)/2,q=R*Zi+20;for(let H=0;H<P.length;H++){const J=z+H*(_t+Us);C.set(P[H].id,{x:J,y:q}),D.push({...P[H],x:J,y:q})}}const j=[];for(const R of v){const P=C.get(R.id);if(P)for(const B of R.dependsOn??[]){const z=C.get(B);z&&j.push({from:B,to:R.id,x1:z.x+_t/2,y1:z.y+nr,x2:P.x+_t/2,y2:P.y})}}return{layout:D,edges:j,viewBox:`0 0 ${T} ${S}`}},[i]),E=w.useMemo(()=>new Map(((i==null?void 0:i.goal.subtasks)??[]).map(v=>[v.id,v])),[i]),L=l?E.get(l):null;return n.jsxs("div",{style:{width:"100%",height:"100%",display:"flex",flexDirection:"column",color:"#e2e8f5",background:"transparent"},children:[n.jsxs("div",{style:{padding:"10px 14px",borderBottom:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",gap:10},children:[n.jsxs("div",{style:{flex:1},children:[n.jsx("div",{style:{fontSize:13,fontWeight:600},children:"Mission graph"}),n.jsxs("div",{style:{fontSize:10,color:"rgba(255,255,255,0.45)"},children:[t.length," active mission(s) · subtask DAG"]})]}),t.length>0&&n.jsx("select",{value:s??"",onChange:v=>r(v.target.value||null),style:{background:"rgba(255,255,255,0.04)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:6,color:"#fff",fontSize:11,padding:"4px 8px",maxWidth:240},children:t.map(v=>n.jsxs("option",{value:v.goalId,children:[v.title," [",v.phase,"]"]},v.goalId))})]}),c&&n.jsx("div",{style:{padding:10,color:"#fca5a5",fontSize:11},children:c}),n.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[n.jsx("div",{style:{flex:1,overflow:"auto",padding:14},children:i?f.length===0?n.jsx("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:"This mission has no subtasks yet."}):n.jsxs("svg",{viewBox:y,style:{width:"100%",height:"auto"},role:"img","aria-label":"Mission subtask DAG",children:[n.jsx("defs",{children:n.jsx("marker",{id:"mg-arrow",viewBox:"0 0 10 10",refX:"10",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:n.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"rgba(255,255,255,0.35)"})})}),x.map((v,A)=>n.jsx("line",{x1:v.x1,y1:v.y1,x2:v.x2,y2:v.y2,stroke:"rgba(255,255,255,0.25)",strokeWidth:"1.4",markerEnd:"url(#mg-arrow)"},`e-${A}`)),f.map(v=>{var _;const A=((_=i.driver)==null?void 0:_.currentSubtaskId)===v.id,m=Bs[v.status],k=l===v.id;return n.jsxs("g",{transform:`translate(${v.x}, ${v.y})`,onClick:()=>p(v.id),style:{cursor:"pointer"},children:[n.jsx("rect",{width:_t,height:nr,rx:"8",fill:A?`${m}22`:"rgba(255,255,255,0.04)",stroke:k||A?m:`${m}55`,strokeWidth:A||k?2:1}),n.jsx("circle",{cx:14,cy:14,r:"5",fill:m,children:v.status==="running"&&n.jsx("animate",{attributeName:"r",values:"4;6;4",dur:"1.2s",repeatCount:"indefinite"})}),n.jsx("text",{x:28,y:18,fontSize:"11",fontWeight:"600",fill:"#fafafa",children:v.title.length>22?v.title.slice(0,21)+"…":v.title}),n.jsxs("text",{x:28,y:34,fontSize:"9",fill:"rgba(255,255,255,0.55)",letterSpacing:"0.5",style:{textTransform:"uppercase"},children:[v.status,v.retries>0?` · ${v.retries} retr${v.retries===1?"y":"ies"}`:""]}),n.jsxs("text",{x:14,y:52,fontSize:"9",fill:"rgba(255,255,255,0.45)",children:[(v.description||"").slice(0,30),(v.description||"").length>30?"…":""]}),A&&n.jsx("text",{x:_t-8,y:14,fontSize:"8",fill:m,textAnchor:"end",fontWeight:"700",children:"NOW"})]},v.id)})]}):n.jsx("div",{style:{padding:24,color:"rgba(255,255,255,0.45)",fontSize:12,textAlign:"center"},children:t.length===0?"No active missions. Launch one via the Mission Driver widget.":"Select a mission to view its graph."})}),L&&n.jsxs("div",{style:{width:260,borderLeft:"1px solid rgba(255,255,255,0.06)",padding:14,overflow:"auto",fontSize:11},children:[n.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:8},children:[n.jsx("div",{style:{fontSize:12,fontWeight:700,color:"#fafafa",flex:1},children:L.title}),n.jsx("button",{onClick:()=>p(null),style:{background:"transparent",border:"none",color:"rgba(255,255,255,0.5)",cursor:"pointer",fontSize:14,padding:0,marginLeft:6},children:"×"})]}),n.jsxs("div",{style:{marginBottom:8},children:[n.jsx("span",{style:{padding:"2px 8px",borderRadius:4,fontSize:9,fontWeight:600,textTransform:"uppercase",letterSpacing:.5,background:`${Bs[L.status]}22`,border:`1px solid ${Bs[L.status]}55`,color:Bs[L.status]},children:L.status}),L.retries>0&&n.jsxs("span",{style:{marginLeft:6,color:"rgba(255,255,255,0.5)"},children:[L.retries," retries"]})]}),n.jsx("div",{style:{color:"rgba(255,255,255,0.85)",lineHeight:1.5,marginBottom:10},children:L.description}),L.dependsOn.length>0&&n.jsxs("div",{style:{color:"rgba(255,255,255,0.55)",fontSize:10,marginBottom:6},children:[n.jsx("strong",{children:"Depends on:"})," ",L.dependsOn.map(v=>{var A;return((A=E.get(v))==null?void 0:A.title)||v}).join(", ")]}),L.completedAt&&n.jsxs("div",{style:{color:"rgba(255,255,255,0.45)",fontSize:10},children:["Completed: ",new Date(L.completedAt).toLocaleString()]})]})]}),i&&n.jsxs("div",{style:{padding:"6px 14px",borderTop:"1px solid rgba(255,255,255,0.06)",display:"flex",justifyContent:"space-between",fontSize:10,color:"rgba(255,255,255,0.55)"},children:[n.jsxs("span",{children:[i.goal.subtasks.length," subtasks · ",i.goal.progress,"% progress"]}),i.driver&&n.jsxs("span",{children:[i.driver.phase," · $",i.driver.budget.costUsd.toFixed(2)," spent"]})]})]})}function Mg(){const[t,e]=w.useState([]),[s,r]=w.useState(!0),[i,o]=w.useState(null),c=async()=>{try{const d=await fetch("/api/agents");if(!d.ok)throw new Error(`HTTP ${d.status}`);const l=await d.json();e(Array.isArray(l)?l:l.agents||[]),o(null)}catch(d){o(d.message)}finally{r(!1)}};return w.useEffect(()=>{c();const d=setInterval(c,1e4);return()=>clearInterval(d)},[]),s?n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(no,{className:"w-4 h-4 text-[#6366f1] animate-spin"})}):i?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsxs("div",{className:"text-center",children:[n.jsx(fn,{className:"w-4 h-4 text-red-400 mx-auto mb-1"}),n.jsx("span",{className:"text-[10px] text-red-400",children:i})]})}):t.length===0?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsx("span",{className:"text-[10px] text-[#52525b]",children:"No active agents"})}):n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsx("div",{className:"space-y-2",children:t.map(d=>n.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx(go,{className:`w-3.5 h-3.5 ${d.status==="busy"?"text-[#f59e0b]":d.status==="error"?"text-red-400":"text-[#6366f1]"}`}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-[11px] text-[#a1a1aa] truncate",children:d.name}),n.jsxs("div",{className:"text-[10px] text-[#52525b] truncate",children:[d.role,d.model?` · ${d.model}`:""]})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${d.status==="busy"?"bg-[#f59e0b]/10 text-[#f59e0b]":d.status==="error"?"bg-red-400/10 text-red-400":"bg-[#6366f1]/10 text-[#818cf8]"}`,children:d.status})]},d.id))})})}function Og(){const[t,e]=w.useState(null),[s,r]=w.useState(!0),i=async()=>{try{const[c,d]=await Promise.allSettled([fetch("/api/health").then(g=>g.ok?g.json():null),fetch("/ollama/api/tags").then(g=>g.ok)]),l=c.status==="fulfilled"&&c.value,p=d.status==="fulfilled"&&d.value;e({gateway:l,ollama:p,version:(l==null?void 0:l.version)||"unknown",uptime:(l==null?void 0:l.uptime)||0})}catch{e({gateway:!1,ollama:!1,version:"unknown",uptime:0})}finally{r(!1)}};if(w.useEffect(()=>{i();const c=setInterval(i,3e4);return()=>clearInterval(c)},[]),s)return n.jsx("div",{className:"w-full h-full flex items-center justify-center",children:n.jsx(no,{className:"w-4 h-4 text-[#6366f1] animate-spin"})});const o=c=>{const d=Math.floor(c/3600),l=Math.floor(c%3600/60);return`${d}h ${l}m`};return n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[t!=null&&t.gateway?n.jsx(Dl,{className:"w-3.5 h-3.5 text-emerald-400"}):n.jsx(Gl,{className:"w-3.5 h-3.5 text-red-400"}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa]",children:"TITAN Gateway"})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${t!=null&&t.gateway?"bg-emerald-400/10 text-emerald-400":"bg-red-400/10 text-red-400"}`,children:t!=null&&t.gateway?"Online":"Offline"})]}),n.jsxs("div",{className:"flex items-center justify-between px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Vt,{className:`w-3.5 h-3.5 ${t!=null&&t.ollama?"text-emerald-400":"text-red-400"}`}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa]",children:"Ollama"})]}),n.jsx("span",{className:`text-[9px] px-1.5 py-0.5 rounded-full uppercase ${t!=null&&t.ollama?"bg-emerald-400/10 text-emerald-400":"bg-red-400/10 text-red-400"}`,children:t!=null&&t.ollama?"Online":"Offline"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx("div",{className:"text-[9px] text-[#52525b] uppercase tracking-wider",children:"Version"}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] font-mono mt-0.5",children:t==null?void 0:t.version})]}),n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsx("div",{className:"text-[9px] text-[#52525b] uppercase tracking-wider",children:"Uptime"}),n.jsx("div",{className:"text-[11px] text-[#a1a1aa] font-mono mt-0.5",children:o((t==null?void 0:t.uptime)||0)})]})]})]})})}function Fs({label:t,value:e,icon:s,color:r,unknown:i}){const o=Math.max(0,Math.min(100,Math.round(e)));return n.jsxs("div",{className:"px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a]",children:[n.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[s,n.jsx("span",{className:"text-[10px] text-[#52525b] uppercase tracking-wider",children:t})]}),n.jsx("span",{className:"text-[11px] text-[#a1a1aa] font-mono",children:i?"—":`${o}%`})]}),n.jsx("div",{className:"h-1.5 rounded-full bg-[#27272a] overflow-hidden",children:n.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:i?"0%":`${o}%`,backgroundColor:r}})})]})}function Pg(){const[t,e]=w.useState({cpu:0,memory:0,disk:0,load:0,loaded:!1,error:null,diskAvailable:!0});w.useEffect(()=>{let r=!1;async function i(){try{const c=await ge("/api/stats");if(!c.ok){const y=`HTTP ${c.status}`;r||e(E=>({...E,loaded:!0,error:y}));return}const d=await c.json();if(r)return;const l=d.host;if(!l){e(y=>({...y,loaded:!0,error:"no host metrics"}));return}const p=typeof l.cpuPercent=="number"?l.cpuPercent:0,g=typeof l.memPercent=="number"?l.memPercent:0,u=typeof l.diskPercent=="number"?l.diskPercent:0,f=l.cores||1,x=typeof l.loadAvg1=="number"?Math.min(100,l.loadAvg1/f*100):0;e({cpu:p,memory:g,disk:u,load:x,loaded:!0,error:null,diskAvailable:!l.diskError})}catch(c){r||e(d=>({...d,loaded:!0,error:c.message}))}}i();const o=setInterval(i,3e3);return()=>{r=!0,clearInterval(o)}},[]);const s=!t.loaded||!!t.error;return n.jsxs("div",{className:"w-full h-full p-3 overflow-auto",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx(Fs,{label:"CPU",value:t.cpu,icon:n.jsx(Nr,{className:"w-3 h-3 text-[#6366f1]"}),color:"#6366f1",unknown:s}),n.jsx(Fs,{label:"Memory",value:t.memory,icon:n.jsx(Ml,{className:"w-3 h-3 text-[#a78bfa]"}),color:"#a78bfa",unknown:s}),n.jsx(Fs,{label:"Disk",value:t.disk,icon:n.jsx(Ol,{className:"w-3 h-3 text-[#10b981]"}),color:"#10b981",unknown:s||!t.diskAvailable}),n.jsx(Fs,{label:"Load",value:t.load,icon:n.jsx(Vt,{className:"w-3 h-3 text-[#f59e0b]"}),color:"#f59e0b",unknown:s})]}),t.error&&n.jsx("div",{className:"mt-2 text-[10px] text-[#ef4444]/80",children:t.error})]})}const Wg=[{label:"Nav",source:"system:nav",w:3,h:4,icon:n.jsx(Yl,{className:"w-3.5 h-3.5"})},{label:"Agents",source:"system:agents",w:3,h:4,icon:n.jsx(go,{className:"w-3.5 h-3.5"})},{label:"Health",source:"system:health",w:3,h:3,icon:n.jsx(Vt,{className:"w-3.5 h-3.5"})},{label:"Stats",source:"system:stats",w:3,h:4,icon:n.jsx(Ql,{className:"w-3.5 h-3.5"})},{label:"Chat",source:"system:chat",w:4,h:5,icon:n.jsx(co,{className:"w-3.5 h-3.5"})},{label:"Files",source:"system:files",w:4,h:6,icon:n.jsx(pn,{className:"w-3.5 h-3.5"})},{label:"Skills",source:"system:tools",w:5,h:4,icon:n.jsx(Er,{className:"w-3.5 h-3.5"})},{label:"Soma",source:"system:soma",w:6,h:6,icon:n.jsx(Pl,{className:"w-3.5 h-3.5"})},{label:"Intel",source:"system:intelligence",w:6,h:5,icon:n.jsx(yt,{className:"w-3.5 h-3.5"})},{label:"Infra",source:"system:infra",w:6,h:4,icon:n.jsx(Rr,{className:"w-3.5 h-3.5"})},{label:"Tools",source:"system:tools",w:5,h:4,icon:n.jsx(jr,{className:"w-3.5 h-3.5"})},{label:"Settings",source:"system:settings",w:4,h:6,icon:n.jsx(Sr,{className:"w-3.5 h-3.5"})},{label:"Wiki",source:"system:memory-wiki",w:5,h:5,icon:n.jsx(fs,{className:"w-3.5 h-3.5"})},{label:"Research",source:"system:autoresearch",w:5,h:5,icon:n.jsx(ho,{className:"w-3.5 h-3.5"})},{label:"Proposals",source:"system:self-proposals",w:5,h:5,icon:n.jsx(yo,{className:"w-3.5 h-3.5"})},{label:"Overview",source:"system:overview",w:5,h:4,icon:n.jsx(to,{className:"w-3.5 h-3.5"})},{label:"Sessions",source:"system:sessions",w:5,h:4,icon:n.jsx(ps,{className:"w-3.5 h-3.5"})},{label:"Watch",source:"system:watch",w:6,h:5,icon:n.jsx(Vt,{className:"w-3.5 h-3.5"})},{label:"Backup",source:"system:backup",w:5,h:5,icon:n.jsx(fo,{className:"w-3.5 h-3.5"})},{label:"Training",source:"system:training",w:5,h:5,icon:n.jsx(yt,{className:"w-3.5 h-3.5"})},{label:"Recipes",source:"system:recipes",w:5,h:5,icon:n.jsx(fs,{className:"w-3.5 h-3.5"})},{label:"VRAM",source:"system:vram",w:5,h:5,icon:n.jsx(Nr,{className:"w-3.5 h-3.5"})},{label:"Teams",source:"system:teams",w:5,h:5,icon:n.jsx(Cr,{className:"w-3.5 h-3.5"})},{label:"Cron",source:"system:cron",w:5,h:5,icon:n.jsx(ps,{className:"w-3.5 h-3.5"})},{label:"Checkpoints",source:"system:checkpoints",w:5,h:5,icon:n.jsx(mn,{className:"w-3.5 h-3.5"})},{label:"Organism",source:"system:organism",w:5,h:5,icon:n.jsx(Tr,{className:"w-3.5 h-3.5"})},{label:"Fleet",source:"system:fleet",w:5,h:5,icon:n.jsx(po,{className:"w-3.5 h-3.5"})},{label:"Browser",source:"system:browser",w:5,h:5,icon:n.jsx(so,{className:"w-3.5 h-3.5"})},{label:"Eval",source:"system:eval",w:5,h:5,icon:n.jsx(mo,{className:"w-3.5 h-3.5"})}];function Bg(){const t=(e,s,r)=>{window.dispatchEvent(new CustomEvent("titan:widget:add",{detail:{source:e,w:s,h:r}}))};return n.jsx("div",{className:"w-full h-full p-3 overflow-auto",children:n.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:Wg.map(e=>n.jsxs("button",{onClick:()=>t(e.source,e.w,e.h),className:"flex items-center gap-2 px-2.5 py-2 rounded-lg bg-[#0a0a0f] border border-[#27272a] text-[#71717a] hover:text-[#a1a1aa] hover:border-[#3f3f46] hover:bg-[#27272a]/30 transition-all text-left",children:[n.jsx("span",{className:"text-[#6366f1]",children:e.icon}),n.jsx("span",{className:"text-[10px] font-medium",children:e.label})]},e.source))})})}class Ug extends oe.Component{componentDidCatch(e){this.props.onError(e.message)}render(){return this.props.children}}function Fg({name:t,children:e}){const[s,r]=oe.useState(null);return s?n.jsx("div",{className:"w-full h-full flex items-center justify-center p-4",children:n.jsxs("span",{className:"text-xs text-red-400",children:[t,": ",s]})}):n.jsx(Ug,{onError:r,children:e})}const $g=oe.lazy(()=>le(()=>import("./legacy-BydeSW77.js"),__vite__mapDeps([105,1,2,4])).then(t=>({default:t.Responsive}))),zg={"system:nav":cl,"system:chat":fl,"system:cmd":vl,"system:soma":_l,"system:command-post":Bp,"system:intelligence":Fp,"system:memory-graph":zp,"system:voice":Hp,"system:infra":Gp,"system:tools":Yp,"system:settings":Jp,"system:files":Xp,"system:settings-general":Zp,"system:settings-security":tm,"system:settings-audit":nm,"system:settings-specialists":im,"system:settings-privacy":am,"system:intelligence-autopilot":cm,"system:intelligence-workflows":um,"system:intelligence-learning":fm,"system:intelligence-self-improve":mm,"system:intelligence-personas":ym,"system:intelligence-persona-profiles":xm,"system:intelligence-dream":vm,"system:infra-homelab":km,"system:infra-gpu":jm,"system:infra-files":Nm,"system:infra-logs":Tm,"system:infra-telemetry":Am,"system:tools-skills":Im,"system:tools-mcp":Mm,"system:tools-integrations":Pm,"system:tools-channels":Bm,"system:tools-mesh":Fm,"system:agents":Mg,"system:health":Og,"system:stats":Pg,"system:quick-links":Bg,"system:memory-wiki":zm,"system:autoresearch":Vm,"system:self-proposals":qm,"system:overview":Km,"system:sessions":Xm,"system:watch":Zm,"system:backup":tg,"system:training":ng,"system:recipes":ig,"system:vram":ag,"system:teams":cg,"system:cron":ug,"system:checkpoints":fg,"system:organism":mg,"system:fleet":yg,"system:browser":xg,"system:eval":vg,"system:time-travel":Sg,"system:mission-driver":Ng,"system:daily-digest":Lg,"system:mission-graph":Dg},Hg={lg:12,md:10,sm:6,xs:4,xxs:2},Vg=60,Gg={lg:1200,md:996,sm:768,xs:480,xxs:0},qg=[12,12],Yg=["se","sw","ne","nw","e","w","n","s"],kl=oe.forwardRef(({widget:t,space:e,onRemove:s,style:r,className:i,onMouseDown:o,onMouseUp:c,onTouchStart:d,onTouchEnd:l,children:p},g)=>{const u=w.useCallback(()=>s(t.id),[t.id,s]);return n.jsxs("div",{ref:g,style:r,className:i,onMouseDown:o,onMouseUp:c,onTouchStart:d,onTouchEnd:l,children:[n.jsx(Xg,{widget:t,space:e,onRemove:u}),p]})});kl.displayName="MemoWidgetItem";const Kg=oe.memo(kl);function Jg({widget:t,space:e,onRemove:s}){const r=w.useRef(null),i=w.useRef(null),o=w.useRef(e),[c,d]=w.useState(null),[l,p]=w.useState(!0);if(w.useEffect(()=>{o.current=e},[e]),w.useEffect(()=>{if(t.format==="system"||!r.current)return;if(!t.source||t.source.trim()===""){d("Empty widget — no source code"),p(!1);return}p(!0),d(null),i.current=new ll(r.current,{onLog:u=>console.log(`[Widget ${t.id}]`,u)}),i.current.setMessageHandler(u=>{var x,y,E,L;const f=o.current;if(u.type==="canvas"&&((x=u.payload)==null?void 0:x.action)==="createWidget"){const v=u.payload.def;if(!v)return{ok:!1,error:"createWidget requires a `def` object"};const A=Number.isFinite(v.w)?v.w:4,m=Number.isFinite(v.h)?v.h:4,k=Number.isFinite(v.x)&&Number.isFinite(v.y)?{x:v.x,y:v.y}:Gs(f.widgets||[],A,m);try{const _=ke.addWidget(f.id,{name:v.name||"Agent Widget",format:v.format||"react",source:v.source||"",x:k.x,y:k.y,w:A,h:m});return window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0,widgetId:_.id}}catch(_){return{ok:!1,error:_.message}}}if(u.type==="canvas"&&((y=u.payload)==null?void 0:y.action)==="updateWidget"){const{id:v,patch:A}=u.payload;return v?(ke.updateWidget(f.id,v,A||{}),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0,id:v}):{ok:!1,error:"updateWidget requires an `id`"}}if(u.type==="canvas"&&((E=u.payload)==null?void 0:E.action)==="listWidgets")return{ok:!0,widgets:f.widgets||[]};if(u.type==="canvas"&&((L=u.payload)==null?void 0:L.action)==="removeWidget"){const v=u.payload.id;return v?(ke.removeWidget(f.id,v),window.dispatchEvent(new CustomEvent("titan:space:refresh",{detail:{spaceId:f.id}})),{ok:!0}):{ok:!1,error:"removeWidget requires an `id`"}}return{ok:!1,error:"Unknown message type"}});const g=setTimeout(()=>{p(!1),d("Sandbox timeout: widget took longer than 30s to render. The widget source may have an infinite loop or an unhandled exception. Open DevTools (F12) → Console to see the iframe-side error.")},3e4);return i.current.render(t.format,t.source).then(()=>{clearTimeout(g),p(!1)}).catch(u=>{clearTimeout(g),p(!1),d(String(u))}),()=>{var u;clearTimeout(g),(u=i.current)==null||u.destroy()}},[t.format,t.source,t.id]),t.format==="system"){const g=zg[t.source];return g?n.jsxs("div",{className:"w-full h-full rounded-xl overflow-hidden flex flex-col group transition-colors shadow-md",style:{background:"var(--color-desk-widget-bg)",border:"1px solid var(--color-desk-border)",boxShadow:"0 4px 12px var(--theme-shadow, rgba(60,40,15,0.15))"},children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b panel-drag-handle cursor-move",style:{borderColor:"var(--color-desk-border-light)",background:"var(--theme-leather, rgba(58,37,24,0.05))"},children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--color-desk-accent)"},children:t.name}),n.jsx("button",{onClick:s,className:"opacity-0 group-hover:opacity-100 text-xs px-1 transition-opacity",style:{color:"var(--color-desk-text-muted)"},children:"×"})]}),n.jsx("div",{className:"flex-1 overflow-auto relative",children:n.jsx(Fg,{name:t.name,children:n.jsx(g,{space:e,widget:t,onRemove:s})})})]}):n.jsxs("div",{className:"w-full h-full flex items-center justify-center text-xs text-red-400",children:["Unknown system widget: ",t.source]})}return n.jsxs("div",{className:"w-full h-full rounded-xl overflow-hidden flex flex-col shadow-md",style:{background:"var(--color-desk-widget-bg)",border:"1px solid var(--color-desk-border)",boxShadow:"0 4px 12px var(--theme-shadow, rgba(60,40,15,0.15))"},children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b panel-drag-handle cursor-move",style:{borderColor:"var(--color-desk-border-light)",background:"var(--theme-leather, rgba(58,37,24,0.05))"},children:[n.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--color-desk-accent)"},children:t.name}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("button",{onClick:g=>{g.stopPropagation(),window.dispatchEvent(new CustomEvent("titan:widget:edit",{detail:{spaceId:e.id,widgetId:t.id}}))},onMouseDown:g=>g.stopPropagation(),className:"px-1",style:{color:"var(--color-desk-text-muted)"},title:"Edit widget",children:n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"m18 2 4 4-14 14H4v-4L18 2z"})})}),n.jsx("button",{onClick:s,className:"text-xs px-1",style:{color:"var(--color-desk-text-muted)"},children:"×"})]})]}),n.jsx("div",{className:"flex-1 relative",children:c?n.jsx("div",{className:"p-3 text-xs text-red-400 font-mono whitespace-pre-wrap",children:c}):n.jsxs(n.Fragment,{children:[n.jsx("iframe",{ref:r,className:"w-full h-full border-0",sandbox:"allow-scripts",title:t.name}),l&&n.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-xs",style:{background:"var(--theme-paper, rgba(253,246,227,0.85))",color:"var(--color-desk-text-muted)",fontFamily:"var(--theme-font-display, 'Georgia', serif)"},children:n.jsx("span",{className:"animate-pulse",children:"Loading widget…"})})]})})]})}const Xg=oe.memo(Jg);function Qg(){const{spaceId:t}=Wl(),e=eo(),[s,r]=w.useState(null),[i]=w.useState(!1),[o,c]=w.useState(!1),[d,l]=w.useState(null),[p,g]=w.useState(!1),[u,f]=w.useState(!1),[x,y]=w.useState(!1),[E,L]=w.useState(1200),v=w.useRef(null),A=w.useRef(null),{info:m,triggerUpdate:k,waitForReload:_}=kf(),[T,S]=w.useState(!1);w.useEffect(()=>{const $=t||"home",F=ke.get($);F?r(F):e("/space/home",{replace:!0})},[t,e]),w.useEffect(()=>{const $=()=>{const se=A.current;if(!se)return null;const Y=new ResizeObserver(te=>{for(const Q of te)L(Q.contentRect.width)});return Y.observe(se),L(se.getBoundingClientRect().width||1200),Y};let F=$();const V=setInterval(()=>{F||(F=$()),F&&clearInterval(V)},200);return()=>{F==null||F.disconnect(),clearInterval(V)}},[s==null?void 0:s.id]),w.useEffect(()=>{const $=F=>{(F.metaKey||F.ctrlKey)&&F.key==="k"&&(F.preventDefault(),f(V=>!V)),(F.metaKey||F.ctrlKey)&&F.key==="j"&&(F.preventDefault(),window.dispatchEvent(new CustomEvent("titan:chat:toggle")))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[]),Sf([{key:"?",action:()=>y(!0),description:"Show keyboard shortcuts help"},{key:"g",shift:!0,action:()=>e("/space/command"),description:"Go to Command Post space"},{key:"h",shift:!0,action:()=>e("/space/home"),description:"Go to Home space"},{key:"s",shift:!0,action:()=>e("/space/settings"),description:"Go to Settings space"},{key:"i",shift:!0,action:()=>e("/space/intelligence"),description:"Go to Intelligence space"}]);const C=w.useCallback(()=>{},[]),D=w.useRef(null),j=w.useRef(null),R=w.useCallback($=>{s&&(j.current=$,D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{const F=j.current;!F||!s||(ke.updateLayout(s.id,F.map(V=>({i:V.i,x:V.x,y:V.y,w:V.w,h:V.h}))),j.current=null,D.current=null)},50))},[s]),P=w.useCallback($=>{var se;if(!s)return;const F=(se=s.widgets)==null?void 0:se.find(Y=>Y.id===$);Dn("canvas_panel_removed",{widgetId:$,format:F==null?void 0:F.format,source:F==null?void 0:F.source}),ke.removeWidget(s.id,$);const V=Array.isArray(s.widgets)?s.widgets:[];r({...s,widgets:V.filter(Y=>Y.id!==$)})},[s]),B=w.useCallback($=>{if(!s)return;const F=ke.addWidget(s.id,$),V=Array.isArray(s.widgets)?s.widgets:[];return r({...s,widgets:[...V,F]}),Dn($.format==="system"?"canvas_system_panel_created":"canvas_panel_created",{source:$.source,name:$.name,format:$.format}),F},[s]),z=w.useCallback(($,F)=>{if(!s||!Array.isArray(s.widgets)||s.widgets.length===0)return{x:0,y:0};const V=12,se=new Set;for(const Y of s.widgets)for(let te=0;te<Y.w;te++)for(let Q=0;Q<Y.h;Q++)se.add(`${Y.x+te},${Y.y+Q}`);for(let Y=0;Y<200;Y++)for(let te=0;te<=V-$;te++){let Q=!0;for(let be=0;be<$;be++){for(let Ce=0;Ce<F;Ce++)if(se.has(`${te+be},${Y+Ce}`)){Q=!1;break}if(!Q)break}if(Q)return{x:te,y:Y}}return{x:0,y:0}},[s]),q=w.useCallback(($,F,V=4,se=4)=>{const Y=z(V,se);B({name:F,format:"system",source:$,x:Y.x,y:Y.y,w:V,h:se})},[B,z]);w.useEffect(()=>{const $=F=>{const V=F.detail;if(console.log("[TitanCanvas] titan:space:refresh received:",V),!!s&&(V==null?void 0:V.spaceId)===s.id){const se=ke.get(s.id);se&&(console.log("[TitanCanvas] Refreshing space, widget count:",se.widgets.length),r(se))}};return window.addEventListener("titan:space:refresh",$),()=>window.removeEventListener("titan:space:refresh",$)},[s]),w.useEffect(()=>{const $=F=>{const V=F.detail;if(s&&V!=null&&V.source){const se=Number.isFinite(V.w)?V.w:4,Y=Number.isFinite(V.h)?V.h:4,te=typeof V.name=="string"&&V.name.trim()?V.name.trim():String(V.source).replace("system:","").replace(/-/g," "),Q=V.format==="react"||V.format==="vanilla"||V.format==="html"||V.format==="system"?V.format:String(V.source).startsWith("system:")?"system":"react",be=z(se,Y);B({name:te,format:Q,source:String(V.source),x:be.x,y:be.y,w:se,h:Y})}};return window.addEventListener("titan:widget:add",$),()=>window.removeEventListener("titan:widget:add",$)},[s,B,z]),w.useEffect(()=>{const $=F=>{const V=F.detail;s&&(V==null?void 0:V.spaceId)===s.id&&typeof(V==null?void 0:V.widgetId)=="string"&&l(V.widgetId)};return window.addEventListener("titan:widget:edit",$),()=>window.removeEventListener("titan:widget:edit",$)},[s]),w.useEffect(()=>s?ke.observe(s.id,F=>{console.log("[TitanCanvas] CRDT observer fired, widgets:",F.length),r(V=>V&&{...V,widgets:F})}):void 0,[s==null?void 0:s.id]);const H=w.useMemo(()=>{const $=s==null?void 0:s.widgets;return Array.isArray($)?$.filter(Boolean):[]},[s]),J=w.useMemo(()=>H.map(($,F)=>({i:$.id,x:Number.isFinite($.x)?$.x:F%3*4,y:Number.isFinite($.y)?$.y:Math.floor(F/3)*4,w:Number.isFinite($.w)?$.w:4,h:Number.isFinite($.h)?$.h:4,minW:2,minH:2,maxW:12,maxH:40})),[H]);return s?n.jsxs("div",{className:"h-full w-full flex",children:[n.jsx(vp,{}),n.jsxs("div",{ref:v,className:"flex-1 relative overflow-auto",children:[n.jsx("style",{children:`
970
970
  .titan-canvas-grid .react-grid-item > .react-resizable-handle {
971
971
  background: none;
972
972
  padding: 0;
@@ -1041,7 +1041,7 @@ function Widget({ titan }) {
1041
1041
  }
1042
1042
  `}),n.jsx("div",{className:"fixed inset-0 opacity-[0.04] pointer-events-none",style:{backgroundImage:"radial-gradient(circle at 1px 1px, var(--theme-metal-dark, rgba(120,90,50,0.4)) 1px, transparent 0)",backgroundSize:"24px 24px"}}),n.jsxs("div",{className:"absolute top-0 left-0 right-0 h-10 flex items-center justify-between px-4 z-40 border-b backdrop-blur-sm",style:{borderColor:"var(--color-desk-border)",background:"var(--color-desk-header-bg)"},children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",style:{color:s.color||"var(--color-desk-accent)"},children:s.name}),n.jsxs("button",{onClick:()=>e("/mission"),className:"group relative inline-flex items-center gap-2 px-3 py-1.5 rounded-full transition-all",title:"Open Mission Chat — a chat-style team-control surface with a real desk view",style:{background:"linear-gradient(120deg, rgba(176,138,58,0.18) 0%, rgba(99,102,241,0.16) 100%)",border:"1px solid var(--theme-metal, rgba(176,138,58,0.45))",boxShadow:"0 0 0 0 rgba(176,138,58,0.4)"},children:[n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",style:{color:"var(--theme-metal-bright, #f5d27a)",flexShrink:0},children:[n.jsx("path",{d:"M3 17h18",strokeLinecap:"round"}),n.jsx("path",{d:"M5 17V9a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v8"}),n.jsx("rect",{x:"8",y:"9",width:"6",height:"6",rx:"0.5",fill:"var(--theme-paper, rgba(247,245,238,0.85))",stroke:"var(--theme-ink, rgba(40,30,15,0.6))",strokeWidth:"0.8"}),n.jsx("rect",{x:"13",y:"10.5",width:"4",height:"4",rx:"0.3",fill:"var(--theme-sticky-yellow, rgba(255,242,168,0.95))",stroke:"var(--theme-metal-dark, rgba(120,90,30,0.5))",strokeWidth:"0.7"}),n.jsx("path",{d:"M7 17v3M17 17v3",strokeLinecap:"round"})]}),n.jsx("span",{className:"text-[11px] font-semibold tracking-tight group-hover:text-white",style:{color:"var(--theme-metal-bright, #f5d27a)"},children:"Mission Chat"}),n.jsx("span",{className:"text-[8px] font-bold uppercase tracking-widest text-bg-deep px-1.5 py-[1px] rounded-full",style:{background:"linear-gradient(180deg, var(--theme-metal-bright, #ffd86e) 0%, var(--theme-metal-dark, #b07a1a) 100%)",boxShadow:"0 1px 2px var(--theme-shadow, rgba(0,0,0,0.4))",animation:"missionPulse 2.4s ease-in-out infinite"},children:"NEW"}),n.jsx("style",{children:"@keyframes missionPulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.7; transform: scale(1.06); } }"})]}),n.jsxs("button",{onClick:()=>c(!0),className:"flex items-center gap-1.5 text-[10px] text-[#52525b] hover:text-[#a5b4fc] truncate max-w-md transition-colors",title:"Edit agent instructions for this space",children:[n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:n.jsx("path",{d:"m18 2 4 4-14 14H4v-4L18 2z"})}),s.agentInstructions?n.jsx("span",{className:"truncate",children:s.agentInstructions}):n.jsx("span",{className:"italic",children:"add agent instructions"})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"text-[10px]",style:{color:"var(--color-desk-text-muted)"},children:[H.length," panel",H.length!==1?"s":""]}),n.jsx("button",{onClick:()=>q("system:nav","Nav",3,4),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Navigation",children:"Nav"}),n.jsx("button",{onClick:()=>q("system:agents","Agents",3,4),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Agents",children:"Agents"}),n.jsx("button",{onClick:()=>q("system:health","Health",3,3),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Health",children:"Health"}),n.jsx("button",{onClick:()=>q("system:stats","Stats",3,4),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Stats",children:"Stats"}),n.jsx("button",{onClick:()=>q("system:quick-links","Quick Links",3,4),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Quick Links",children:"Links"}),n.jsx("button",{onClick:()=>q("system:chat","Chat",4,5),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},title:"Add Chat",children:"Chat"}),H.length>0&&n.jsx("button",{onClick:async()=>{Dn("canvas_clear_all",{panelCount:H.length}),s&&(await ke.clearSpace(s.id),r({...s,widgets:[]}))},className:"text-[10px] px-2 py-1 rounded-md bg-[#ef4444]/5 border border-[#ef4444]/10 text-[#ef4444]/70 hover:bg-[#ef4444]/10 transition-colors",children:"Clear"}),n.jsx("button",{disabled:T,className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${m!=null&&m.isNewer?"bg-[#f59e0b]/10 border-[#f59e0b]/30 text-[#f59e0b] hover:bg-[#f59e0b]/20 cursor-pointer":"border text-[#6b5a45]"}`,style:m!=null&&m.isNewer?void 0:{background:"var(--theme-paper, rgba(253,246,227,0.7))",borderColor:"var(--color-desk-border)"},title:m!=null&&m.isNewer?`Update available: ${m.current} → ${m.latest}`:`TITAN ${(m==null?void 0:m.current)||""}`,onClick:async()=>{if(!(m!=null&&m.isNewer)||T||!confirm(`Update TITAN from ${m.current} → ${m.latest}?
1043
1043
 
1044
- Your data in ~/.titan/ will be preserved. The gateway will restart after the update.`))return;const $=m.current;S(!0);const F=await k(!0);if(!F.ok){S(!1),alert(`Update failed: ${F.error||"Unknown error"}`);return}const V=await _($);S(!1),V?window.location.reload():alert("Update sent, but the gateway did not come back within 30s. Check service status manually.")},children:T?"…":m!=null&&m.isNewer?`↑ ${m.latest}`:`v${(m==null?void 0:m.current)||""}`}),n.jsxs("button",{onClick:()=>g(!0),className:"text-[10px] px-2 py-1 rounded-md transition-colors flex items-center gap-1.5",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-accent)"},title:"Widget gallery",children:[n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 3l1.9 5.8L20 10l-5 3.6 1.5 6L12 16l-4.5 3.6L9 13.6 4 10l6.1-1.2L12 3z"})}),"Gallery"]}),n.jsx("button",{onClick:()=>f(!0),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},children:"⌘K"}),n.jsx("button",{onClick:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle")),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},children:"⌘J"})]})]}),n.jsx("div",{ref:A,className:"relative pt-24 min-h-[5000px]",children:H.length===0?n.jsx(Xg,{space:s,onAddWidget:q,onOpenChat:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle",{detail:{open:!0}}))}):n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"pt-12 text-center",children:n.jsx("div",{className:"inline-block rounded-xl px-6 py-3 border text-sm font-serif",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)"},children:"Loading grid..."})}),children:n.jsx(Ug,{className:"layout titan-canvas-grid",width:E,layouts:{lg:J},breakpoints:Hg,cols:$g,rowHeight:zg,margin:Vg,containerPadding:[12,12],isDraggable:!0,isResizable:!0,draggableHandle:".panel-drag-handle",resizeHandles:Gg,compactType:null,preventCollision:!1,allowOverlap:!0,useCSSTransforms:!0,onLayoutChange:C,onDragStop:$=>{R($)},onResizeStop:$=>{R($)},children:H.map($=>n.jsx(qg,{widget:$,space:s,onRemove:P},$.id))})})}),n.jsx("div",{className:"fixed right-4 bottom-32 z-50",children:n.jsx(ll,{currentSpaceId:s.id,onSpaceSelect:$=>e(`/space/${$}`)})}),n.jsx(hp,{space:s,defaultExpanded:i}),n.jsx(mp,{}),n.jsx(_p,{space:s,open:o,onClose:()=>c(!1),onSaved:$=>{r(F=>F&&{...F,agentInstructions:$||void 0})}}),d&&(()=>{const $=H.find(F=>F.id===d);return!$||$.format==="system"?(l(null),null):n.jsx(jp,{widget:$,spaceId:s.id,open:!0,onClose:()=>l(null),onSaved:F=>{const V=H.map(se=>se.id===F.id?{...se,...F}:se);r(se=>se&&{...se,widgets:V})}})})(),n.jsx(Rp,{open:p,onClose:()=>g(!1)}),n.jsx(Mp,{}),u&&n.jsx(bl,{currentSpaceId:s.id,onSpaceSelect:$=>{e(`/space/${$}`),f(!1)},onAction:$=>{$.type==="widget"&&q($.source,$.name,$.w,$.h),f(!1)},onClose:()=>f(!1)}),n.jsx(kf,{open:x,onClose:()=>y(!1)})]})]}):n.jsx("div",{className:"h-full w-full flex items-center justify-center",children:n.jsx("div",{className:"rounded-xl px-6 py-3 border text-sm",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)",fontFamily:"var(--theme-font-display, 'Georgia', serif)"},children:"Loading space..."})})}function Xg({space:t,onAddWidget:e,onOpenChat:s}){const r=[{title:"System",items:[{label:"SOMA",source:"system:soma",w:6,h:6},{label:"Command Post",source:"system:command-post",w:8,h:6},{label:"Overview",source:"system:overview",w:6,h:5},{label:"Organism",source:"system:organism",w:6,h:6},{label:"Infra",source:"system:infra",w:6,h:4},{label:"VRAM",source:"system:vram",w:6,h:6},{label:"Fleet",source:"system:fleet",w:6,h:5}]},{title:"Intelligence",items:[{label:"Intelligence",source:"system:intelligence",w:6,h:5},{label:"Memory Graph",source:"system:memory-graph",w:8,h:7},{label:"Memory Wiki",source:"system:memory-wiki",w:6,h:6},{label:"Autoresearch",source:"system:autoresearch",w:6,h:6},{label:"Self-Proposals",source:"system:self-proposals",w:6,h:6},{label:"Training",source:"system:training",w:6,h:6},{label:"Eval",source:"system:eval",w:6,h:6}]},{title:"Tools",items:[{label:"Tools",source:"system:tools",w:5,h:4},{label:"Files",source:"system:files",w:4,h:6},{label:"Browser",source:"system:browser",w:6,h:5},{label:"Recipes",source:"system:recipes",w:6,h:6},{label:"Voice",source:"system:voice",w:5,h:5}]},{title:"Workflows",items:[{label:"Mission Driver",source:"system:mission-driver",w:7,h:7},{label:"Mission Graph",source:"system:mission-graph",w:8,h:7},{label:"Daily Digest",source:"system:daily-digest",w:5,h:7},{label:"Time Travel",source:"system:time-travel",w:8,h:6},{label:"Sessions",source:"system:sessions",w:6,h:5},{label:"Checkpoints",source:"system:checkpoints",w:6,h:5},{label:"Cron",source:"system:cron",w:6,h:6}]},{title:"Comms",items:[{label:"Watch",source:"system:watch",w:8,h:7},{label:"Backup",source:"system:backup",w:6,h:6},{label:"Teams",source:"system:teams",w:6,h:6}]}];return n.jsx("div",{className:"h-full flex items-start justify-center pt-10 pb-32 px-6",children:n.jsxs("div",{className:"text-center w-full max-w-3xl rounded-2xl px-8 py-10 border",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",boxShadow:"0 4px 16px var(--theme-shadow)"},children:[n.jsx("style",{children:`
1044
+ Your data in ~/.titan/ will be preserved. The gateway will restart after the update.`))return;const $=m.current;S(!0);const F=await k(!0);if(!F.ok){S(!1),alert(`Update failed: ${F.error||"Unknown error"}`);return}const V=await _($);S(!1),V?window.location.reload():alert("Update sent, but the gateway did not come back within 30s. Check service status manually.")},children:T?"…":m!=null&&m.isNewer?`↑ ${m.latest}`:`v${(m==null?void 0:m.current)||""}`}),n.jsxs("button",{onClick:()=>g(!0),className:"text-[10px] px-2 py-1 rounded-md transition-colors flex items-center gap-1.5",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-accent)"},title:"Widget gallery",children:[n.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M12 3l1.9 5.8L20 10l-5 3.6 1.5 6L12 16l-4.5 3.6L9 13.6 4 10l6.1-1.2L12 3z"})}),"Gallery"]}),n.jsx("button",{onClick:()=>f(!0),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},children:"⌘K"}),n.jsx("button",{onClick:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle")),className:"text-[10px] px-2 py-1 rounded-md transition-colors",style:{background:"var(--theme-paper, rgba(253,246,227,0.7))",border:"1px solid var(--color-desk-border)",color:"var(--color-desk-text-secondary)"},children:"⌘J"})]})]}),n.jsx("div",{ref:A,className:"relative pt-24 min-h-[5000px]",children:H.length===0?n.jsx(Zg,{space:s,onAddWidget:q,onOpenChat:()=>window.dispatchEvent(new CustomEvent("titan:chat:toggle",{detail:{open:!0}}))}):n.jsx(w.Suspense,{fallback:n.jsx("div",{className:"pt-12 text-center",children:n.jsx("div",{className:"inline-block rounded-xl px-6 py-3 border text-sm font-serif",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)"},children:"Loading grid..."})}),children:n.jsx($g,{className:"layout titan-canvas-grid",width:E,layouts:{lg:J},breakpoints:Gg,cols:Hg,rowHeight:Vg,margin:qg,containerPadding:[12,12],isDraggable:!0,isResizable:!0,draggableHandle:".panel-drag-handle",resizeHandles:Yg,compactType:null,preventCollision:!1,allowOverlap:!0,useCSSTransforms:!0,onLayoutChange:C,onDragStop:$=>{R($)},onResizeStop:$=>{R($)},children:H.map($=>n.jsx(Kg,{widget:$,space:s,onRemove:P},$.id))})})}),n.jsx("div",{className:"fixed right-4 bottom-32 z-50",children:n.jsx(cl,{currentSpaceId:s.id,onSpaceSelect:$=>e(`/space/${$}`)})}),n.jsx(mp,{space:s,defaultExpanded:i}),n.jsx(bp,{}),n.jsx(Sp,{space:s,open:o,onClose:()=>c(!1),onSaved:$=>{r(F=>F&&{...F,agentInstructions:$||void 0})}}),d&&(()=>{const $=H.find(F=>F.id===d);return!$||$.format==="system"?(l(null),null):n.jsx(Np,{widget:$,spaceId:s.id,open:!0,onClose:()=>l(null),onSaved:F=>{const V=H.map(se=>se.id===F.id?{...se,...F}:se);r(se=>se&&{...se,widgets:V})}})})(),n.jsx(Lp,{open:p,onClose:()=>g(!1)}),n.jsx(Pp,{}),u&&n.jsx(vl,{currentSpaceId:s.id,onSpaceSelect:$=>{e(`/space/${$}`),f(!1)},onAction:$=>{$.type==="widget"&&q($.source,$.name,$.w,$.h),f(!1)},onClose:()=>f(!1)}),n.jsx(Ef,{open:x,onClose:()=>y(!1)})]})]}):n.jsx("div",{className:"h-full w-full flex items-center justify-center",children:n.jsx("div",{className:"rounded-xl px-6 py-3 border text-sm",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",color:"var(--color-desk-text-muted)",fontFamily:"var(--theme-font-display, 'Georgia', serif)"},children:"Loading space..."})})}function Zg({space:t,onAddWidget:e,onOpenChat:s}){const r=[{title:"System",items:[{label:"SOMA",source:"system:soma",w:6,h:6},{label:"Command Post",source:"system:command-post",w:8,h:6},{label:"Overview",source:"system:overview",w:6,h:5},{label:"Organism",source:"system:organism",w:6,h:6},{label:"Infra",source:"system:infra",w:6,h:4},{label:"VRAM",source:"system:vram",w:6,h:6},{label:"Fleet",source:"system:fleet",w:6,h:5}]},{title:"Intelligence",items:[{label:"Intelligence",source:"system:intelligence",w:6,h:5},{label:"Memory Graph",source:"system:memory-graph",w:8,h:7},{label:"Memory Wiki",source:"system:memory-wiki",w:6,h:6},{label:"Autoresearch",source:"system:autoresearch",w:6,h:6},{label:"Self-Proposals",source:"system:self-proposals",w:6,h:6},{label:"Training",source:"system:training",w:6,h:6},{label:"Eval",source:"system:eval",w:6,h:6}]},{title:"Tools",items:[{label:"Tools",source:"system:tools",w:5,h:4},{label:"Files",source:"system:files",w:4,h:6},{label:"Browser",source:"system:browser",w:6,h:5},{label:"Recipes",source:"system:recipes",w:6,h:6},{label:"Voice",source:"system:voice",w:5,h:5}]},{title:"Workflows",items:[{label:"Mission Driver",source:"system:mission-driver",w:7,h:7},{label:"Mission Graph",source:"system:mission-graph",w:8,h:7},{label:"Daily Digest",source:"system:daily-digest",w:5,h:7},{label:"Time Travel",source:"system:time-travel",w:8,h:6},{label:"Sessions",source:"system:sessions",w:6,h:5},{label:"Checkpoints",source:"system:checkpoints",w:6,h:5},{label:"Cron",source:"system:cron",w:6,h:6}]},{title:"Comms",items:[{label:"Watch",source:"system:watch",w:8,h:7},{label:"Backup",source:"system:backup",w:6,h:6},{label:"Teams",source:"system:teams",w:6,h:6}]}];return n.jsx("div",{className:"h-full flex items-start justify-center pt-10 pb-32 px-6",children:n.jsxs("div",{className:"text-center w-full max-w-3xl rounded-2xl px-8 py-10 border",style:{background:"var(--color-desk-widget-bg)",borderColor:"var(--color-desk-border)",boxShadow:"0 4px 16px var(--theme-shadow)"},children:[n.jsx("style",{children:`
1045
1045
  .titan-empty-hero {
1046
1046
  background: linear-gradient(180deg,
1047
1047
  color-mix(in srgb, var(--theme-metal-bright) 22%, transparent) 0%,
@@ -1089,4 +1089,4 @@ Your data in ~/.titan/ will be preserved. The gateway will restart after the upd
1089
1089
  color-mix(in srgb, var(--theme-metal) 50%, transparent) 50%,
1090
1090
  transparent 100%);
1091
1091
  }
1092
- `}),n.jsx("div",{className:"w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-5",style:{background:"color-mix(in srgb, var(--theme-metal) 16%, transparent)",border:"1px solid color-mix(in srgb, var(--theme-metal) 35%, transparent)"},children:n.jsx("svg",{className:"w-7 h-7",style:{color:"var(--theme-metal)"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"})})}),n.jsx("h2",{className:"text-xl font-bold mb-2",style:{color:"var(--theme-ink)",fontFamily:"var(--theme-font-display)"},children:t.name}),n.jsx("p",{className:"text-sm mb-7",style:{color:"var(--theme-ink-soft)",fontFamily:"var(--theme-font-display)"},children:"This space is empty. Ask the agent to materialize something for you, or place a system panel below."}),n.jsx("div",{className:"flex justify-center mb-8",children:n.jsxs("button",{onClick:s,className:"titan-empty-hero inline-flex items-center gap-2 px-6 py-3 rounded-xl text-base font-semibold",children:[n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a7 7 0 0 0-4 12.7V17a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-2.3A7 7 0 0 0 12 2z"}),n.jsx("path",{d:"M10 22h4"})]}),"Ask Agent"]})}),n.jsx("div",{className:"space-y-5 text-left",children:r.map(i=>n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-3 mb-2.5 px-1",children:[n.jsx("span",{className:"titan-empty-group-label text-[10px] font-bold uppercase",children:i.title}),n.jsx("span",{className:"titan-empty-rule flex-1 h-px"})]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:i.items.map(o=>n.jsxs("button",{onClick:()=>e(o.source,o.label,o.w,o.h),className:"titan-empty-chip px-3 py-1.5 rounded-lg text-[11px] text-center",title:`Add ${o.label}`,children:["+ ",o.label]},o.source))})]},i.title))})]})})}const Cy=Object.freeze(Object.defineProperty({__proto__:null,default:Jg},Symbol.toStringTag,{value:"Module"}));export{ql as D,go as G,Cy as T};
1092
+ `}),n.jsx("div",{className:"w-16 h-16 rounded-2xl flex items-center justify-center mx-auto mb-5",style:{background:"color-mix(in srgb, var(--theme-metal) 16%, transparent)",border:"1px solid color-mix(in srgb, var(--theme-metal) 35%, transparent)"},children:n.jsx("svg",{className:"w-7 h-7",style:{color:"var(--theme-metal)"},fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"})})}),n.jsx("h2",{className:"text-xl font-bold mb-2",style:{color:"var(--theme-ink)",fontFamily:"var(--theme-font-display)"},children:t.name}),n.jsx("p",{className:"text-sm mb-7",style:{color:"var(--theme-ink-soft)",fontFamily:"var(--theme-font-display)"},children:"This space is empty. Ask the agent to materialize something for you, or place a system panel below."}),n.jsx("div",{className:"flex justify-center mb-8",children:n.jsxs("button",{onClick:s,className:"titan-empty-hero inline-flex items-center gap-2 px-6 py-3 rounded-xl text-base font-semibold",children:[n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M12 2a7 7 0 0 0-4 12.7V17a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-2.3A7 7 0 0 0 12 2z"}),n.jsx("path",{d:"M10 22h4"})]}),"Ask Agent"]})}),n.jsx("div",{className:"space-y-5 text-left",children:r.map(i=>n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-3 mb-2.5 px-1",children:[n.jsx("span",{className:"titan-empty-group-label text-[10px] font-bold uppercase",children:i.title}),n.jsx("span",{className:"titan-empty-rule flex-1 h-px"})]}),n.jsx("div",{className:"flex gap-2 flex-wrap",children:i.items.map(o=>n.jsxs("button",{onClick:()=>e(o.source,o.label,o.w,o.h),className:"titan-empty-chip px-3 py-1.5 rounded-lg text-[11px] text-center",title:`Add ${o.label}`,children:["+ ",o.label]},o.source))})]},i.title))})]})})}const Ry=Object.freeze(Object.defineProperty({__proto__:null,default:Qg},Symbol.toStringTag,{value:"Module"}));export{Jl as D,yo as G,Ry as T};