@johpaz/hive-agents 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (248) hide show
  1. package/README.md +5 -5
  2. package/dist/hive.js +88127 -103024
  3. package/dist/tool-worker.js +13243 -17002
  4. package/dist/ui/assets/A2UIPage-CS0VPY6a.js +8 -0
  5. package/dist/ui/assets/AgentCreateForm-DXkjtXaS.js +1 -0
  6. package/dist/ui/assets/AgentDetailPage-DUIX_cuQ.js +1 -0
  7. package/dist/ui/assets/AgentNewPage-SNXz2wik.js +1 -0
  8. package/dist/ui/assets/AgentsPage-CGsdgx5F.js +10 -0
  9. package/dist/ui/assets/{ApiClientPage-6a6KFwsQ.js → ApiClientPage-MNMjfSDs.js} +2 -2
  10. package/dist/ui/assets/ChannelsPage-BEwxWUcE.js +8 -0
  11. package/dist/ui/assets/DashboardPage-D6cRFKWW.js +6 -0
  12. package/dist/ui/assets/LoginPage-ByYmIa2p.js +1 -0
  13. package/dist/ui/assets/LogsPage-Bmk9rohg.js +1 -0
  14. package/dist/ui/assets/MeetingPage-Dm97Mbiw.js +1 -0
  15. package/dist/ui/assets/ModelSelector-gubC8j_Q.js +1 -0
  16. package/dist/ui/assets/NotFound-PUg3gEO0.js +1 -0
  17. package/dist/ui/assets/{Office3DPage-C3SIzd2H.css → Office3DPage-31AMJ-LN.css} +1 -1
  18. package/dist/ui/assets/Office3DPage-Bfi-S2kG.js +727 -0
  19. package/dist/ui/assets/ProvidersPage-CSo0MYxd.js +1 -0
  20. package/dist/ui/assets/RecoverPage-YY2QU-qh.js +1 -0
  21. package/dist/ui/assets/SettingsPage-DrafhhKw.js +9 -0
  22. package/dist/ui/assets/SetupPage-LXnd2XbV.js +1 -0
  23. package/dist/ui/assets/Vignette-BcPWkNhm.js +4302 -0
  24. package/dist/ui/assets/VoicePage-p-hTMAq7.js +307 -0
  25. package/dist/ui/assets/VoicePage-uLWdtoD4.css +1 -0
  26. package/dist/ui/assets/WebChatPage-B61ZDjQ8.js +29 -0
  27. package/dist/ui/assets/agentCapabilities-PfTEVxG1.js +1 -0
  28. package/dist/ui/assets/alert-CjiX20jI.js +1 -0
  29. package/dist/ui/assets/badge-B5AKge1b.js +1 -0
  30. package/dist/ui/assets/bia-4LFKOyxR.webp +0 -0
  31. package/dist/ui/assets/bia-BFcUpOu3.glb +0 -0
  32. package/dist/ui/assets/card-mTJ4oZbL.js +1 -0
  33. package/dist/ui/assets/conversationsStore-BlwA3yd2.js +1 -0
  34. package/dist/ui/assets/dialog-B04KpdNt.js +1 -0
  35. package/dist/ui/assets/dist-js-Dh18rcg9.js +1 -0
  36. package/dist/ui/assets/{dist-js-CLxM1g2B.js → dist-js-q7C_AB0j.js} +1 -1
  37. package/dist/ui/assets/index-ByTufXPh.css +2 -0
  38. package/dist/ui/assets/index-DKJFLL3a.js +116 -0
  39. package/dist/ui/assets/label-D_fvqJyD.js +1 -0
  40. package/dist/ui/assets/lock-3IApZyVy.js +1 -0
  41. package/dist/ui/assets/{square-psq7k_CB.js → mic-CpDU_2as.js} +1 -1
  42. package/dist/ui/assets/pencil-L3Li7_pz.js +1 -0
  43. package/dist/ui/assets/rotate-ccw-LoM1AuqK.js +1 -0
  44. package/dist/ui/assets/scroll-area-CbH8FOo8.js +1 -0
  45. package/dist/ui/assets/select-v_3QBYrD.js +1 -0
  46. package/dist/ui/assets/slider-DXS4h1LB.js +1 -0
  47. package/dist/ui/assets/square-D5zdNkAY.js +1 -0
  48. package/dist/ui/assets/switch-ndx8VCpm.js +1 -0
  49. package/dist/ui/assets/tabs-epu-3Tl4.js +1 -0
  50. package/dist/ui/assets/textarea-BgZJFZTX.js +1 -0
  51. package/dist/ui/assets/useAudioDevices-B2stUHvr.js +41 -0
  52. package/dist/ui/assets/useHiveAgentsModelLoad-B4EjHvj4.js +1 -0
  53. package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +1 -0
  54. package/dist/ui/assets/{useProviders-CiLSc05q.js → useProviders-B1NS24md.js} +1 -1
  55. package/dist/ui/assets/vendor-react-kUOwxn0g.js +1 -0
  56. package/dist/ui/assets/volume-2-EaA0JRvD.js +1 -0
  57. package/dist/ui/assets/volume-x-CROXNMGT.js +1 -0
  58. package/dist/ui/index.html +6 -6
  59. package/package.json +10 -6
  60. package/packages/cli/src/adapters/config.ts +11 -3
  61. package/packages/cli/src/commands/causal.ts +1 -1
  62. package/packages/cli/src/commands/doctor.ts +101 -46
  63. package/packages/cli/src/commands/onboard.ts +4 -2
  64. package/packages/core/src/agent/agent-catalog.ts +47 -47
  65. package/packages/core/src/agent/agent-loop.ts +67 -14
  66. package/packages/core/src/agent/capability-search.ts +2 -1
  67. package/packages/core/src/agent/compaction.ts +19 -7
  68. package/packages/core/src/agent/context-compiler.ts +166 -28
  69. package/packages/core/src/agent/conversation-store.ts +26 -2
  70. package/packages/core/src/agent/goal-runner.ts +2 -2
  71. package/packages/core/src/agent/jev-decisions.ts +148 -0
  72. package/packages/core/src/agent/jev-planner.ts +293 -0
  73. package/packages/core/src/agent/llm-client.ts +29 -7
  74. package/packages/core/src/agent/llm-providers/ollama.ts +17 -4
  75. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +27 -12
  76. package/packages/core/src/agent/llm-providers/opencode-go.ts +37 -0
  77. package/packages/core/src/agent/prompt-builder.ts +1 -1
  78. package/packages/core/src/agent/realtime-providers/gemini-live.ts +233 -0
  79. package/packages/core/src/agent/realtime-providers/index.ts +29 -0
  80. package/packages/core/src/agent/realtime-providers/interface.ts +108 -0
  81. package/packages/core/src/agent/skill-selector.ts +5 -3
  82. package/packages/core/src/agent/thread-id.ts +71 -0
  83. package/packages/core/src/agent/thread-store.ts +230 -0
  84. package/packages/core/src/agent/tool-selector.ts +2 -0
  85. package/packages/core/src/agent/tracer.ts +2 -0
  86. package/packages/core/src/canvas/canvas-manager.ts +145 -27
  87. package/packages/core/src/canvas/emitter.ts +24 -0
  88. package/packages/core/src/channels/telegram.ts +19 -1
  89. package/packages/core/src/channels/webchat.ts +47 -45
  90. package/packages/core/src/config/loader.ts +9 -6
  91. package/packages/core/src/events/tool-narration.ts +1 -0
  92. package/packages/core/src/gateway/channel-notify.ts +24 -5
  93. package/packages/core/src/gateway/delegation-groups.ts +5 -5
  94. package/packages/core/src/gateway/delegation-notify.ts +34 -5
  95. package/packages/core/src/gateway/durable-queue.ts +22 -0
  96. package/packages/core/src/gateway/failure-notify.ts +8 -2
  97. package/packages/core/src/gateway/initializer.ts +17 -10
  98. package/packages/core/src/gateway/job-executors.ts +3 -3
  99. package/packages/core/src/gateway/realtime/bridge-tools.ts +470 -0
  100. package/packages/core/src/gateway/realtime/index.ts +305 -0
  101. package/packages/core/src/gateway/realtime/prompt.ts +182 -0
  102. package/packages/core/src/gateway/realtime/protocol.ts +60 -0
  103. package/packages/core/src/gateway/realtime/voice-session.ts +442 -0
  104. package/packages/core/src/gateway/resolver.ts +31 -4
  105. package/packages/core/src/gateway/routes/artifacts.ts +13 -0
  106. package/packages/core/src/gateway/routes/chat.ts +20 -4
  107. package/packages/core/src/gateway/routes/conversations.ts +121 -0
  108. package/packages/core/src/gateway/routes/providers.ts +16 -1
  109. package/packages/core/src/gateway/routes/setup.ts +25 -14
  110. package/packages/core/src/gateway/routes/system.ts +4 -2
  111. package/packages/core/src/gateway/routes/tts-local.ts +2 -1
  112. package/packages/core/src/gateway/server.ts +171 -13
  113. package/packages/core/src/gateway/slash-commands.ts +48 -10
  114. package/packages/core/src/gateway/tts/src/server.ts +2 -1
  115. package/packages/core/src/gateway/webchat-turn.ts +68 -10
  116. package/packages/core/src/index.ts +2 -0
  117. package/packages/core/src/scheduler/CronScheduler.ts +20 -8
  118. package/packages/core/src/scheduler/cron/cron-engine.test.ts +295 -0
  119. package/packages/core/src/scheduler/cron/expression.ts +165 -0
  120. package/packages/core/src/scheduler/cron/index.ts +10 -0
  121. package/packages/core/src/scheduler/cron/job.ts +340 -0
  122. package/packages/core/src/scheduler/cron/next-run.ts +121 -0
  123. package/packages/core/src/scheduler/cron/zoned-time.ts +139 -0
  124. package/packages/core/src/scheduler/integration.ts +16 -5
  125. package/packages/core/src/scheduler/types.ts +3 -18
  126. package/packages/core/src/storage/bootstrap.ts +23 -0
  127. package/packages/core/src/storage/collections.ts +38 -1
  128. package/packages/core/src/storage/crypto.ts +23 -12
  129. package/packages/core/src/storage/onboarding.ts +39 -39
  130. package/packages/core/src/storage/reconcile.ts +6 -1
  131. package/packages/core/src/storage/seed.ts +82 -8
  132. package/packages/core/src/storage/usage.ts +53 -1
  133. package/packages/core/src/tool-runtime/index.ts +19 -1
  134. package/packages/core/src/tools/a2ui/index.ts +65 -1
  135. package/packages/core/src/tools/agents/get-available-models.ts +3 -1
  136. package/packages/core/src/tools/core/index.ts +39 -4
  137. package/packages/core/src/tools/cron/index.ts +4 -4
  138. package/packages/core/src/tools/index.ts +2 -1
  139. package/packages/core/src/tools/office/office-escribir-xlsx.ts +2 -1
  140. package/packages/core/src/tools/office/office-leer-xlsx.ts +2 -1
  141. package/packages/core/src/tools/office/xlsx-loader.ts +19 -0
  142. package/packages/core/src/tools/web/browser-backend.ts +141 -44
  143. package/packages/core/src/tools/web/browser-click.ts +2 -2
  144. package/packages/core/src/tools/web/browser-extract.ts +2 -2
  145. package/packages/core/src/tools/web/browser-navigate.ts +2 -2
  146. package/packages/core/src/tools/web/browser-screenshot.ts +12 -5
  147. package/packages/core/src/tools/web/browser-script.ts +2 -2
  148. package/packages/core/src/tools/web/browser-service.ts +63 -384
  149. package/packages/core/src/tools/web/browser-session.ts +125 -0
  150. package/packages/core/src/tools/web/browser-type.ts +2 -2
  151. package/packages/core/src/tools/web/browser-wait.ts +2 -2
  152. package/packages/core/src/tools/web/computer-use.ts +553 -0
  153. package/packages/core/src/tools/web/index.ts +5 -1
  154. package/packages/core/src/tools/web/webview-backend.ts +559 -21
  155. package/packages/core/src/utils/port.ts +33 -0
  156. package/packages/core/src/voice/index.ts +2 -1
  157. package/packages/mcp/src/config.ts +2 -1
  158. package/packages/mcp/src/manager.ts +9 -0
  159. package/packages/mcp/src/transports/index.ts +42 -1
  160. package/packages/mcp/src/transports/sse.ts +11 -5
  161. package/packages/skills/src/bundled/a2ui/a2ui_dashboard/SKILL.md +2 -2
  162. package/packages/skills/src/bundled/a2ui/a2ui_form/SKILL.md +2 -2
  163. package/packages/skills/src/bundled/a2ui/a2ui_interactive/SKILL.md +4 -4
  164. package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +7 -7
  165. package/packages/skills/src/bundled/agents/memory_manager/SKILL.md +9 -9
  166. package/packages/skills/src/bundled/agents/research_and_remember/SKILL.md +8 -8
  167. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +8 -8
  168. package/packages/skills/src/bundled/artifacts/artifact_reader/SKILL.md +104 -0
  169. package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +6 -6
  170. package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +5 -5
  171. package/packages/skills/src/bundled/cron_manager/SKILL.md +29 -19
  172. package/packages/skills/src/bundled/cron_reminder/SKILL.md +5 -5
  173. package/packages/skills/src/bundled/filesystem/file_manager/SKILL.md +4 -4
  174. package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +7 -7
  175. package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +10 -10
  176. package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +8 -8
  177. package/packages/skills/src/bundled/web/browser_automate/SKILL.md +21 -12
  178. package/packages/skills/src/bundled/web/browser_scrape/SKILL.md +28 -13
  179. package/packages/skills/src/bundled/web/web_monitor/SKILL.md +6 -6
  180. package/packages/skills/src/bundled/web/web_research/SKILL.md +5 -5
  181. package/packages/skills/src/bundled-data.generated.ts +837 -783
  182. package/dist/ui/assets/A2UIPage-7Ry5rHh9.js +0 -8
  183. package/dist/ui/assets/AgentCreateForm-Dh5W0q_t.js +0 -1
  184. package/dist/ui/assets/AgentDetailPage-CIoPjtsS.js +0 -1
  185. package/dist/ui/assets/AgentNewPage-BNsZcJQf.js +0 -1
  186. package/dist/ui/assets/AgentsPage-YZrDmgNI.js +0 -10
  187. package/dist/ui/assets/ChannelsPage-Dice4dkJ.js +0 -8
  188. package/dist/ui/assets/DashboardPage-B9r0sc0F.js +0 -6
  189. package/dist/ui/assets/LoginPage-BkAAX_tu.js +0 -1
  190. package/dist/ui/assets/LogsPage-8-H1OJs3.js +0 -1
  191. package/dist/ui/assets/MeetingPage-14JoQo71.js +0 -1
  192. package/dist/ui/assets/ModelSelector-CrgJQ7DG.js +0 -1
  193. package/dist/ui/assets/NotFound-B06kVW7N.js +0 -1
  194. package/dist/ui/assets/Office3DPage-BMUZWkFS.js +0 -4614
  195. package/dist/ui/assets/ProvidersPage-BiL3QxCs.js +0 -1
  196. package/dist/ui/assets/RecoverPage-D1o8yxNz.js +0 -1
  197. package/dist/ui/assets/SettingsPage-GP8UwQIL.js +0 -9
  198. package/dist/ui/assets/SetupPage-B_gU1YQU.js +0 -1
  199. package/dist/ui/assets/WebChatPage-Yahufnth.js +0 -29
  200. package/dist/ui/assets/agentCapabilities-Dg72UAFj.js +0 -1
  201. package/dist/ui/assets/alert-DChoEVJw.js +0 -1
  202. package/dist/ui/assets/badge-uRjRSt86.js +0 -1
  203. package/dist/ui/assets/card-DwQizslL.js +0 -1
  204. package/dist/ui/assets/dialog--mljnfAi.js +0 -1
  205. package/dist/ui/assets/dist-js-B0s_TDau.js +0 -1
  206. package/dist/ui/assets/index-BHHUQZJd.js +0 -116
  207. package/dist/ui/assets/index-CEFhf4dF.css +0 -2
  208. package/dist/ui/assets/label-BceoUB2w.js +0 -1
  209. package/dist/ui/assets/pencil-CUbpCfeG.js +0 -1
  210. package/dist/ui/assets/scroll-area-DMEaZZUp.js +0 -1
  211. package/dist/ui/assets/select-BBEBtcLm.js +0 -1
  212. package/dist/ui/assets/slider-DcmBdvYD.js +0 -1
  213. package/dist/ui/assets/switch-CgiDezVR.js +0 -1
  214. package/dist/ui/assets/tabs-gUXIjjZv.js +0 -1
  215. package/dist/ui/assets/textarea-DedxQYBx.js +0 -1
  216. package/dist/ui/assets/useHiveAgentsModelLoad-C7bhWPDG.js +0 -1
  217. package/dist/ui/assets/useOfficeModel-BAFasrg8.js +0 -1
  218. package/dist/ui/assets/vendor-react-DYyYpuMy.js +0 -1
  219. package/dist/ui/assets/volume-x-BDlMCDYT.js +0 -1
  220. /package/dist/ui/assets/{core-Sjunb8Z1.js → core-B_5cyOSV.js} +0 -0
  221. /package/dist/ui/assets/{download-D0aDV8Y_.js → download-BQXrpH0m.js} +0 -0
  222. /package/dist/ui/assets/{ellipsis-vertical-BOW_iEOO.js → ellipsis-vertical-D7uFJLGh.js} +0 -0
  223. /package/dist/ui/assets/{external-link-5cujQzfV.js → external-link-6oTH9pUM.js} +0 -0
  224. /package/dist/ui/assets/{eye-sRPY5qOa.js → eye-CxvxtQT5.js} +0 -0
  225. /package/dist/ui/assets/{file-text-DNSyNLUh.js → file-text-D5ZJEx3E.js} +0 -0
  226. /package/dist/ui/assets/{gateway-url-BZj_2-jf.js → gateway-url-BALS_wVh.js} +0 -0
  227. /package/dist/ui/assets/{gauge-C__zxC3_.js → gauge-CEu7PhTW.js} +0 -0
  228. /package/dist/ui/assets/{history-BHQWfE-7.js → history-DLK5rTlP.js} +0 -0
  229. /package/dist/ui/assets/{info-CG1VohyH.js → info-8ReWzubE.js} +0 -0
  230. /package/dist/ui/assets/{key-BC28VCjO.js → key-DPkOY-J0.js} +0 -0
  231. /package/dist/ui/assets/{lock-open-Bhp0UJlL.js → lock-open-v0EphssG.js} +0 -0
  232. /package/dist/ui/assets/{mail-Biwn8WrV.js → mail-vwCEHyhQ.js} +0 -0
  233. /package/dist/ui/assets/{pause-C2l5G2Py.js → pause-Cm9LzIZK.js} +0 -0
  234. /package/dist/ui/assets/{play-CMAscR3a.js → play-zqogwA2l.js} +0 -0
  235. /package/dist/ui/assets/{plus-DzvRxH4U.js → plus-Bm08ABhc.js} +0 -0
  236. /package/dist/ui/assets/{radio-DfGzov4y.js → radio-Cii1BjMt.js} +0 -0
  237. /package/dist/ui/assets/{refresh-cw-DZXu5FrG.js → refresh-cw-DXv3XgEt.js} +0 -0
  238. /package/dist/ui/assets/{search-ykSx-zZU.js → search-BMwCI-pX.js} +0 -0
  239. /package/dist/ui/assets/{send-DAhlz2i9.js → send-D6fgWV7m.js} +0 -0
  240. /package/dist/ui/assets/{settings-DL0REysC.js → settings-qV3kVkeG.js} +0 -0
  241. /package/dist/ui/assets/{shield-BPZZhjCT.js → shield-CIarwBvx.js} +0 -0
  242. /package/dist/ui/assets/{sparkles-BViXTAh7.js → sparkles-DVvY6jDT.js} +0 -0
  243. /package/dist/ui/assets/{terminal-CzxPKG-h.js → terminal-BEcTK780.js} +0 -0
  244. /package/dist/ui/assets/{trash-2-SgYCWiVk.js → trash-2-D6oziYAK.js} +0 -0
  245. /package/dist/ui/assets/{utils-SGUggNJc.js → utils-DEmd_M8c.js} +0 -0
  246. /package/dist/ui/assets/{vendor-router-Dsg8fxNQ.js → vendor-router-DP84b3LQ.js} +0 -0
  247. /package/dist/ui/assets/{wifi-CyPHteEm.js → wifi-BUJuOcgP.js} +0 -0
  248. /package/dist/ui/assets/{zap-OVVrfEHr.js → zap-DSoX9NDk.js} +0 -0
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Thread store — el registro de conversaciones (`conversationThreads`).
3
+ *
4
+ * `conversations` no tiene índice secundario: los mensajes se leen por prefijo del
5
+ * threadId. Esta colección es el catálogo que permite listar las conversaciones de
6
+ * un usuario, ponerles título y borrarlas sin escanear todos los mensajes.
7
+ *
8
+ * El id de cada fila ES el threadId. La única fila cuyo id no tiene formato
9
+ * `${user}/${canal}/${peer}` es la del hilo legacy anterior a la separación por
10
+ * canal (ver ensureLegacyThread).
11
+ */
12
+
13
+ import { col, updateDoc } from "../storage/hive"
14
+ import { logger } from "../utils/logger"
15
+ import type { ConversationThreadDoc, ConversationDoc, SummaryDoc } from "../storage/collections"
16
+ import { makeThreadId, parseThreadId, newWebConversationId } from "./thread-id"
17
+
18
+ const log = logger.child("thread-store")
19
+
20
+ const TITLE_MAX_CHARS = 60
21
+
22
+ export interface EnsureThreadInput {
23
+ userId: string
24
+ channel: string
25
+ peerId: string
26
+ peerKind?: "direct" | "group"
27
+ }
28
+
29
+ async function threadsCol() {
30
+ return col<ConversationThreadDoc>("conversationThreads")
31
+ }
32
+
33
+ export async function getThread(threadId: string): Promise<ConversationThreadDoc | null> {
34
+ const c = await threadsCol()
35
+ const entry = await c.get(threadId)
36
+ return entry?.doc ?? null
37
+ }
38
+
39
+ /**
40
+ * Crea la fila de la conversación si aún no existe y devuelve su threadId.
41
+ * Idempotente: se llama en cada turno desde resolveContext.
42
+ */
43
+ export async function ensureThread(input: EnsureThreadInput): Promise<string> {
44
+ const threadId = makeThreadId(input.userId, input.channel, input.peerId)
45
+ const c = await threadsCol()
46
+ const existing = await c.get(threadId)
47
+ if (existing) return threadId
48
+
49
+ const now = Date.now()
50
+ try {
51
+ await c.put(threadId, {
52
+ id: threadId,
53
+ user_id: input.userId,
54
+ channel: input.channel,
55
+ peer_id: input.peerId,
56
+ peer_kind: input.peerKind ?? "direct",
57
+ title: null,
58
+ archived: false,
59
+ created_at: now,
60
+ last_message_at: now,
61
+ message_count: 0,
62
+ }, { expectedVersion: 0 })
63
+ } catch {
64
+ // Otro turno del mismo canal la creó primero — ambos quieren lo mismo.
65
+ }
66
+ return threadId
67
+ }
68
+
69
+ /** Conversación nueva de la web. El id lo elige el servidor, nunca el cliente. */
70
+ export async function createWebConversation(userId: string, title?: string): Promise<ConversationThreadDoc> {
71
+ const peerId = newWebConversationId()
72
+ const threadId = await ensureThread({ userId, channel: "webchat", peerId, peerKind: "direct" })
73
+ if (title?.trim()) await renameThread(threadId, title)
74
+ const doc = await getThread(threadId)
75
+ if (!doc) throw new Error(`No pude crear la conversación ${threadId}`)
76
+ return doc
77
+ }
78
+
79
+ /**
80
+ * Título derivado del primer mensaje del usuario. El contenido llega con el
81
+ * prefijo `[Timestamp: ...]` que le añaden el gateway y las rutas REST: esa línea
82
+ * no describe nada, así que se descarta antes de recortar.
83
+ */
84
+ export function deriveTitle(text: string): string | null {
85
+ const withoutTimestamp = text.replace(/^\[Timestamp:[^\]]*\]\s*/, "").trim()
86
+ const firstLine = withoutTimestamp.split("\n").find((l) => l.trim().length > 0)?.trim()
87
+ if (!firstLine) return null
88
+ return firstLine.length > TITLE_MAX_CHARS
89
+ ? `${firstLine.slice(0, TITLE_MAX_CHARS - 1)}…`
90
+ : firstLine
91
+ }
92
+
93
+ /**
94
+ * Registra actividad en el hilo: contador, fecha del último mensaje y —la primera
95
+ * vez que habla el usuario— el título.
96
+ *
97
+ * Si el hilo tiene formato y no existe la fila, la crea (es el caso de un hilo que
98
+ * nació fuera de resolveContext, como el de una tarea programada). Si no lo tiene
99
+ * —hilo legacy, hilos aislados `task-*`— solo actualiza una fila ya existente:
100
+ * nunca inventa conversaciones para los hilos internos de los workers.
101
+ */
102
+ export async function touchThread(
103
+ threadId: string,
104
+ opts: { role: "user" | "assistant" | "tool"; text?: string; internal?: boolean }
105
+ ): Promise<void> {
106
+ try {
107
+ const c = await threadsCol()
108
+ let existing = await c.get(threadId)
109
+
110
+ if (!existing) {
111
+ const parts = parseThreadId(threadId)
112
+ if (!parts) return
113
+ await ensureThread({ userId: parts.userId, channel: parts.channel, peerId: parts.peerId })
114
+ existing = await c.get(threadId)
115
+ if (!existing) return
116
+ }
117
+
118
+ const patch: Partial<ConversationThreadDoc> = {
119
+ last_message_at: Date.now(),
120
+ message_count: existing.doc.message_count + 1,
121
+ }
122
+ // El título sale del primer mensaje humano: ni de la respuesta del agente ni
123
+ // de un evento interno (fan-in de delegación), que no describen el tema.
124
+ if (!existing.doc.title && opts.role === "user" && !opts.internal && opts.text) {
125
+ const title = deriveTitle(opts.text)
126
+ if (title) patch.title = title
127
+ }
128
+ await updateDoc<ConversationThreadDoc>("conversationThreads", threadId, patch)
129
+ } catch (err) {
130
+ // El registro es un catálogo, no la fuente de verdad: nunca debe tumbar un turno.
131
+ log.warn(`no pude actualizar el hilo ${threadId}: ${(err as Error).message}`)
132
+ }
133
+ }
134
+
135
+ export async function listThreads(
136
+ userId: string,
137
+ opts?: { channel?: string; includeArchived?: boolean }
138
+ ): Promise<ConversationThreadDoc[]> {
139
+ const c = await threadsCol()
140
+ const rows = await c.findBy("user_id", userId)
141
+ return rows
142
+ .map((r) => r.doc)
143
+ .filter((d) => (opts?.channel ? d.channel === opts.channel : true))
144
+ .filter((d) => (opts?.includeArchived ? true : !d.archived))
145
+ .sort((a, b) => b.last_message_at - a.last_message_at)
146
+ }
147
+
148
+ /** La conversación de webchat en la que seguiría escribiendo el usuario. */
149
+ export async function mostRecentWebThread(userId: string): Promise<ConversationThreadDoc | null> {
150
+ const threads = await listThreads(userId, { channel: "webchat" })
151
+ return threads[0] ?? null
152
+ }
153
+
154
+ export async function renameThread(threadId: string, title: string): Promise<void> {
155
+ const clean = title.trim().slice(0, 200)
156
+ await updateDoc<ConversationThreadDoc>("conversationThreads", threadId, { title: clean || null })
157
+ }
158
+
159
+ /**
160
+ * Borra la conversación entera: mensajes, resumen, notas y la fila del registro.
161
+ * Los mensajes se localizan por prefijo, igual que los lee conversation-store.
162
+ */
163
+ export async function deleteThread(threadId: string): Promise<void> {
164
+ const conversations = await col<ConversationDoc>("conversations")
165
+ const messages = await conversations.scan({ prefix: `${threadId}:` })
166
+ for (const m of messages) await conversations.delete(m.id)
167
+
168
+ const summaries = await col<SummaryDoc>("summaries")
169
+ await summaries.delete(threadId).catch(() => {})
170
+
171
+ const scratchpad = await col<{ threadId: string }>("scratchpad")
172
+ const notes = await scratchpad.scan({ prefix: `${threadId}:` })
173
+ for (const n of notes) await scratchpad.delete(n.id)
174
+
175
+ const c = await threadsCol()
176
+ await c.delete(threadId).catch(() => {})
177
+
178
+ log.info(`conversación ${threadId} borrada (${messages.length} mensajes)`)
179
+ }
180
+
181
+ /**
182
+ * El hilo por el que hablarle a alguien en un canal cuando no venimos de un
183
+ * mensaje suyo (avisos de tareas programadas, por ejemplo).
184
+ *
185
+ * En la web es la conversación activa; en los demás canales, el contacto al que
186
+ * apunta `userIdentities`. Devuelve null si no hay ninguno, y quien llame decide
187
+ * el fallback.
188
+ */
189
+ export async function threadForChannel(userId: string, channel: string): Promise<string | null> {
190
+ if (channel === "webchat") return (await mostRecentWebThread(userId))?.id ?? null
191
+
192
+ const identities = await col<{ channel_user_id?: string }>("userIdentities")
193
+ const identity = await identities.get(`${userId}:${channel}`)
194
+ const peerId = identity?.doc.channel_user_id
195
+ return peerId ? makeThreadId(userId, channel, peerId) : null
196
+ }
197
+
198
+ /**
199
+ * Registra el hilo anterior a la separación por canal —`thread_id = userId`, un
200
+ * único hilo compartido por todos los canales— como una conversación más de la
201
+ * web, para que su historial siga siendo accesible. No mueve ni reescribe ningún
202
+ * mensaje: la fila apunta al mismo prefijo de siempre.
203
+ */
204
+ export async function ensureLegacyThread(userId: string): Promise<boolean> {
205
+ const c = await threadsCol()
206
+ if (await c.get(userId)) return false
207
+
208
+ const conversations = await col<ConversationDoc>("conversations")
209
+ const sample = await conversations.scan({ prefix: `${userId}:`, limit: 1 })
210
+ if (sample.length === 0) return false
211
+
212
+ const all = await conversations.scan({ prefix: `${userId}:` })
213
+ const lastAt = all.reduce((max, e) => Math.max(max, e.doc.created_at), 0)
214
+
215
+ await c.put(userId, {
216
+ id: userId,
217
+ user_id: userId,
218
+ channel: "webchat",
219
+ peer_id: "legacy",
220
+ peer_kind: "direct",
221
+ title: "Conversación anterior",
222
+ archived: false,
223
+ created_at: all[0]?.doc.created_at ?? Date.now(),
224
+ last_message_at: lastAt || Date.now(),
225
+ message_count: all.length,
226
+ }, { expectedVersion: 0 }).catch(() => {})
227
+
228
+ log.info(`hilo legacy ${userId} registrado como conversación (${all.length} mensajes)`)
229
+ return true
230
+ }
@@ -161,6 +161,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
161
161
  // Browser automation
162
162
  { name: "browser_navigate", description: "Navigate to URL and get content, open web pages and extract information. Spanish keywords: navegar web, abrir página, ir a sitio, navegar, ir a página", category: "browser", abstractionLevel: "atomic" },
163
163
  { name: "browser_screenshot", description: "Take webpage screenshot, capture visual snapshot of web page. Spanish keywords: captura de pantalla, screenshot, fotografiar página, imagen de página", category: "browser", abstractionLevel: "atomic" },
164
+ { name: "computer_use_task", description: "Operate the browser by looking at the screen: click by coordinates, type and navigate when no stable CSS selector exists (canvas, generated UIs, embedded viewers). Acts on Hive's own browser, never on the user screen. Spanish keywords: usar el navegador, hacer clic donde veas, operar una página, rellenar formulario, computer use, mirar la pantalla", category: "browser", abstractionLevel: "orchestration" },
164
165
  { name: "browser_click", description: "Click element on page, interact with buttons and links in browser. Spanish keywords: hacer clic, presionar botón, clickear, pulsar, botón", category: "browser", abstractionLevel: "atomic" },
165
166
  { name: "browser_type", description: "Type into input field, fill forms and text inputs in browser. Spanish keywords: escribir en página, llenar formulario, introducir texto, completar formulario", category: "browser", abstractionLevel: "atomic" },
166
167
  { name: "browser_extract", description: "Extract text, links, or structured data from page using CSS selectors or XPath. Spanish keywords: extraer datos, obtener información, scraping, selectores, xpath", category: "browser", abstractionLevel: "atomic" },
@@ -195,6 +196,7 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
195
196
 
196
197
  // Capability discovery
197
198
  { name: "search_knowledge", description: "Search everything Hive knows: native tools, MCP tools, skills, catalog agents and playbook rules. Spanish keywords: buscar herramienta, descubrir capacidades, qué puedo hacer, buscar skill, buscar conocimiento", category: "core", abstractionLevel: "atomic" },
199
+ { name: "conversation_read", description: "Read earlier messages from this conversation by ID or search text when context is missing. Spanish keywords: recuperar contexto, leer historial, conversación anterior", category: "core", abstractionLevel: "atomic" },
198
200
 
199
201
  // HTTP / REST
200
202
  { name: "api_request", description: "Perform an authorized HTTP request against a REST endpoint and validate the response. Spanish keywords: llamar api, request rest, consumir endpoint, petición http, hacer get, hacer post", category: "api", abstractionLevel: "atomic" },
@@ -95,6 +95,7 @@ export function recordLLMUsage(opts: {
95
95
  model: string
96
96
  inputTokens: number
97
97
  outputTokens: number
98
+ latencyMs?: number
98
99
  }): void {
99
100
  Promise.resolve().then(async () => {
100
101
  try {
@@ -104,6 +105,7 @@ export function recordLLMUsage(opts: {
104
105
  model: opts.model,
105
106
  inputTokens: opts.inputTokens,
106
107
  outputTokens: opts.outputTokens,
108
+ latencyMs: opts.latencyMs,
107
109
  })
108
110
  } catch { /* ignore */ }
109
111
  })
@@ -7,6 +7,15 @@ export interface WebSocketLike {
7
7
  close(code?: number, reason?: string): void;
8
8
  }
9
9
 
10
+ /** Una conexión concreta a una sesión de lienzo. */
11
+ export interface CanvasClient {
12
+ /** Código único de esta conexión: dos ventanas del mismo usuario son dos. */
13
+ id: string;
14
+ ws: WebSocketLike;
15
+ /** Última señal de vida, en ms. La refresca el pong del latido. */
16
+ lastSeen: number;
17
+ }
18
+
10
19
  export interface A2UISurfaceInfo {
11
20
  surfaceId: string;
12
21
  catalogId?: string;
@@ -15,6 +24,11 @@ export interface A2UISurfaceInfo {
15
24
  hasDataModel: boolean;
16
25
  }
17
26
 
27
+ /** Cada cuánto se pregunta si el cliente sigue ahí. */
28
+ const PING_MS = 30_000;
29
+ /** Latidos sin respuesta que se toleran antes de retirar una conexión. */
30
+ const TOLERANCIA_LATIDOS = 3;
31
+
18
32
  export const WebSocketState = {
19
33
  CONNECTING: 0,
20
34
  OPEN: 1,
@@ -28,8 +42,33 @@ interface A2UISurfaceCache {
28
42
  dataModel?: Record<string, unknown>;
29
43
  }
30
44
 
45
+ /** Overlays `incoming` on `current` by component id, keeping the order of first appearance. */
46
+ export function mergeComponentsById(current: unknown[], incoming: unknown[]): unknown[] {
47
+ const byId = new Map<string, unknown>()
48
+ const idOf = (c: unknown) => (c && typeof c === "object" ? String((c as { id?: unknown }).id ?? "") : "")
49
+ for (const c of current) byId.set(idOf(c), c)
50
+ for (const c of incoming) byId.set(idOf(c), c)
51
+ return [...byId.values()]
52
+ }
53
+
31
54
  export class CanvasManager {
32
- private sessions: Map<string, WebSocketLike> = new Map();
55
+ /**
56
+ * Clientes por sesión, no *un* cliente por sesión.
57
+ *
58
+ * El identificador de sesión es `canvas:<usuario>`, el mismo para la app de
59
+ * escritorio, para la pestaña del navegador y para cada reconexión. Con un
60
+ * único socket guardado, el que se conectaba después le robaba el sitio al
61
+ * anterior: la ventana perdedora se quedaba con el panel vacío para siempre
62
+ * mientras el servidor anotaba "enviado" sin un solo error.
63
+ *
64
+ * Indexado por el propio socket para que registrarse dos veces —el cliente
65
+ * pide `canvas_subscribe` al conectar y al arrancar la tienda— no cuente como
66
+ * dos clientes.
67
+ */
68
+ private sessions: Map<string, Map<WebSocketLike, CanvasClient>> = new Map();
69
+ /** Todos los clientes por su código, para responder al latido en O(1). */
70
+ private clients: Map<string, CanvasClient> = new Map();
71
+ private nextClientId = 1;
33
72
  // Surfaces belong to a canvas session. Keeping this scoped prevents a
34
73
  // desktop reconnect (or another user) from receiving a surface addressed
35
74
  // to a different session and makes surface discovery deterministic.
@@ -44,19 +83,27 @@ export class CanvasManager {
44
83
  private startHeartbeat(): void {
45
84
  if (this.heartbeatInterval) return;
46
85
 
47
- // Enviar ping a todas las sesiones cada 30 segundos
86
+ // Un latido que sólo saluda no sirve: éste también entierra. Un socket que
87
+ // se fue sin avisar —la máquina suspendida, la red caída— se queda en
88
+ // estado OPEN por el lado del servidor y seguiría recibiendo superficies
89
+ // que no va a pintar nadie.
48
90
  this.heartbeatInterval = setInterval(() => {
49
- for (const [sessionId, ws] of this.sessions) {
50
- if (ws.readyState === WebSocketState.OPEN) {
91
+ const limite = Date.now() - PING_MS * TOLERANCIA_LATIDOS;
92
+ for (const sessionId of Array.from(this.sessions.keys())) {
93
+ for (const cliente of this.clientesDe(sessionId)) {
94
+ if (cliente.lastSeen < limite) {
95
+ this.log.info(`Canvas client ${cliente.id} sin señales de vida; se retira`);
96
+ this.olvidar(sessionId, cliente);
97
+ continue;
98
+ }
51
99
  try {
52
- ws.send(JSON.stringify({ type: "canvas:ping", sessionId }));
53
- this.log.debug(`Heartbeat sent to ${sessionId}`);
54
- } catch (e) {
55
- this.log.error(`Failed to send heartbeat to ${sessionId}`);
100
+ cliente.ws.send(JSON.stringify({ type: "canvas:ping", sessionId, connId: cliente.id }));
101
+ } catch {
102
+ this.olvidar(sessionId, cliente);
56
103
  }
57
104
  }
58
105
  }
59
- }, 30000);
106
+ }, PING_MS);
60
107
  }
61
108
 
62
109
  private stopHeartbeat(): void {
@@ -66,9 +113,23 @@ export class CanvasManager {
66
113
  }
67
114
  }
68
115
 
69
- registerSession(sessionId: string, ws: WebSocketLike): void {
70
- this.sessions.set(sessionId, ws);
71
- this.log.info(`Canvas session registered: ${sessionId}`);
116
+ /** @returns el código de esta conexión, que el cliente usa para el latido. */
117
+ registerSession(sessionId: string, ws: WebSocketLike): string {
118
+ const clientes = this.sessions.get(sessionId) ?? new Map<WebSocketLike, CanvasClient>();
119
+ this.sessions.set(sessionId, clientes);
120
+
121
+ const yaEstaba = clientes.get(ws);
122
+ const cliente: CanvasClient = yaEstaba ?? {
123
+ id: `c${this.nextClientId++}`,
124
+ ws,
125
+ lastSeen: Date.now(),
126
+ };
127
+ cliente.lastSeen = Date.now();
128
+ clientes.set(ws, cliente);
129
+ this.clients.set(cliente.id, cliente);
130
+ this.log.info(
131
+ `Canvas session registered: ${sessionId} (cliente ${cliente.id}, ${clientes.size} en esta sesión)`,
132
+ );
72
133
 
73
134
  eventBus.emit("tool:completed" as any, {
74
135
  toolName: "canvas:session:register",
@@ -78,7 +139,7 @@ export class CanvasManager {
78
139
  });
79
140
 
80
141
  // Notify the client that the session is registered
81
- ws.send(JSON.stringify({ type: "canvas:connected", sessionId }));
142
+ ws.send(JSON.stringify({ type: "canvas:connected", sessionId, connId: cliente.id }));
82
143
 
83
144
  // Replay cached A2UI surfaces for this session so late-connecting clients
84
145
  // get current state without leaking another session's surfaces.
@@ -98,12 +159,56 @@ export class CanvasManager {
98
159
  this.log.warn(`Failed to replay A2UI surface '${surfaceId}' to ${sessionId}`);
99
160
  }
100
161
  }
162
+ return cliente.id;
163
+ }
164
+
165
+ /** El cliente sigue ahí: contestó al latido. */
166
+ markAlive(connId: string): void {
167
+ const cliente = this.clients.get(connId);
168
+ if (cliente) cliente.lastSeen = Date.now();
169
+ }
170
+
171
+ /** Clientes vivos de una sesión; de paso retira los sockets ya cerrados. */
172
+ private clientesDe(sessionId: string): CanvasClient[] {
173
+ const clientes = this.sessions.get(sessionId);
174
+ if (!clientes) return [];
175
+ const vivos: CanvasClient[] = [];
176
+ for (const cliente of Array.from(clientes.values())) {
177
+ if (cliente.ws.readyState === WebSocketState.OPEN) vivos.push(cliente);
178
+ else this.olvidar(sessionId, cliente);
179
+ }
180
+ return vivos;
181
+ }
182
+
183
+ private olvidar(sessionId: string, cliente: CanvasClient): void {
184
+ this.clients.delete(cliente.id);
185
+ const clientes = this.sessions.get(sessionId);
186
+ clientes?.delete(cliente.ws);
187
+ if (clientes && clientes.size === 0) this.sessions.delete(sessionId);
101
188
  }
102
189
 
103
190
  unregisterSession(sessionId: string, ws?: WebSocketLike): void {
104
- if (ws && this.sessions.get(sessionId) !== ws) return;
105
- this.sessions.delete(sessionId);
106
- this.log.info(`Canvas session disconnected: ${sessionId}`);
191
+ const clientes = this.sessions.get(sessionId);
192
+ if (!clientes) return;
193
+ // Sin socket concreto se cierra la sesión entera; con él se va sólo esa
194
+ // ventana, y las demás siguen recibiendo.
195
+ if (!ws) {
196
+ for (const cliente of clientes.values()) this.clients.delete(cliente.id);
197
+ this.sessions.delete(sessionId);
198
+ this.log.info(`Canvas session disconnected: ${sessionId}`);
199
+ return;
200
+ }
201
+ const cliente = clientes.get(ws);
202
+ if (!cliente) return;
203
+ this.olvidar(sessionId, cliente);
204
+ this.log.info(
205
+ `Canvas client ${cliente.id} disconnected from ${sessionId} (quedan ${this.sessions.get(sessionId)?.size ?? 0})`,
206
+ );
207
+ }
208
+
209
+ /** What the client is rendering for a surface: every component sent so far, merged by id. */
210
+ getCachedComponents(sessionId: string, surfaceId: string): unknown[] {
211
+ return this.a2uiCache.get(sessionId)?.get(surfaceId)?.components ?? [];
107
212
  }
108
213
 
109
214
  async sendA2UIMessage(sessionId: string, messageType: string, data: Record<string, unknown>): Promise<void> {
@@ -116,7 +221,9 @@ export class CanvasManager {
116
221
  sessionSurfaces.set(surfaceId, { createData: data });
117
222
  } else if (messageType === "a2ui:updateComponents") {
118
223
  const cached = sessionSurfaces.get(surfaceId);
119
- if (cached) cached.components = data.components as unknown[];
224
+ // Merge by id, like the client: replacing the list made a reconnect
225
+ // replay a different surface from the one the user was looking at.
226
+ if (cached) cached.components = mergeComponentsById(cached.components ?? [], data.components as unknown[]);
120
227
  } else if (messageType === "a2ui:updateDataModel") {
121
228
  const cached = sessionSurfaces.get(surfaceId);
122
229
  if (cached) {
@@ -136,27 +243,37 @@ export class CanvasManager {
136
243
  }
137
244
  }
138
245
 
139
- const ws = this.sessions.get(sessionId);
140
-
141
- if (!ws || ws.readyState !== WebSocketState.OPEN) {
246
+ const clientes = this.clientesDe(sessionId);
247
+ if (clientes.length === 0) {
142
248
  const connected = this.getConnectedSessions();
143
249
  this.log.warn(`Session ${sessionId} NOT connected for A2UI message. Cached for replay. Available: ${connected.join(", ")}`);
144
250
  return;
145
251
  }
146
252
 
147
- ws.send(JSON.stringify({ type: messageType, data }));
148
- this.log.debug(`Sent A2UI message '${messageType}' to session ${sessionId}`);
253
+ // A todas las ventanas de esa sesión: el escritorio y la pestaña del
254
+ // navegador son la misma persona mirando lo mismo desde dos sitios.
255
+ const mensaje = JSON.stringify({ type: messageType, data });
256
+ for (const cliente of clientes) {
257
+ try {
258
+ cliente.ws.send(mensaje);
259
+ } catch {
260
+ this.olvidar(sessionId, cliente);
261
+ }
262
+ }
263
+ this.log.debug(`Sent A2UI message '${messageType}' to ${clientes.length} client(s) of ${sessionId}`);
149
264
  }
150
265
 
151
266
  isSessionConnected(sessionId: string): boolean {
152
- const ws = this.sessions.get(sessionId);
153
- return ws !== undefined && ws.readyState === WebSocketState.OPEN;
267
+ return this.clientesDe(sessionId).length > 0;
154
268
  }
155
269
 
156
270
  getConnectedSessions(): string[] {
157
- return Array.from(this.sessions.entries())
158
- .filter(([_, ws]) => ws.readyState === WebSocketState.OPEN)
159
- .map(([id]) => id);
271
+ return Array.from(this.sessions.keys()).filter((id) => this.clientesDe(id).length > 0);
272
+ }
273
+
274
+ /** Cuántas ventanas miran esta sesión. Para diagnóstico. */
275
+ countClients(sessionId: string): number {
276
+ return this.clientesDe(sessionId).length;
160
277
  }
161
278
 
162
279
  getStats(): { totalSessions: number; activeSessions: number } {
@@ -181,6 +298,7 @@ export class CanvasManager {
181
298
 
182
299
  clearAll(): void {
183
300
  this.stopHeartbeat();
301
+ this.clients.clear();
184
302
  this.sessions.clear();
185
303
  this.a2uiCache.clear();
186
304
  this.log.info("Canvas manager cleared");
@@ -15,6 +15,8 @@ export type CanvasEventType =
15
15
  | "canvas:edge_add"
16
16
  | "canvas:edge_remove"
17
17
  | "canvas:work_event"
18
+ | "canvas:jev_decision"
19
+ | "canvas:jev_status"
18
20
  | "ag-ui:event"
19
21
 
20
22
  export type CanvasWorkPhase =
@@ -37,6 +39,23 @@ export interface CanvasWorkEvent {
37
39
  detail?: string | null
38
40
  }
39
41
 
42
+ /** One Jev decision, shown by the office's oracle as a beam to the agent it advised. */
43
+ export interface CanvasJevDecision {
44
+ eventId: string
45
+ agentId: string
46
+ kind: "context" | "iteration" | "parallel"
47
+ /** Short Spanish description of what was selected ("4/15 mensajes · 9/24 herramientas"). */
48
+ summary: string
49
+ /** Estimated main-model input tokens this decision avoided (chars/4); negative when it added context. */
50
+ savedTokens: number
51
+ latencyMs: number
52
+ costUsd: number
53
+ recommendedAgentId?: string | null
54
+ /** MCP servers the recommended specialist needs that are off; the coordinator asks the user to turn them on. */
55
+ mcpOff?: string[]
56
+ totals: { decisions: number; savedTokens: number; costUsd: number }
57
+ }
58
+
40
59
  const subscribers = new Set<{ send: (data: string) => void }>()
41
60
  let workEventSequence = 0
42
61
 
@@ -57,6 +76,11 @@ const LIVE_DEFAULTS: AgentLiveState = {
57
76
  delegatedBy: null,
58
77
  }
59
78
 
79
+ /** What each agent is doing right now (the same state the 3D office draws). */
80
+ export function getAgentLiveStates(): Array<{ agentId: string } & AgentLiveState> {
81
+ return [...agentLiveState.entries()].map(([agentId, state]) => ({ agentId, ...state }))
82
+ }
83
+
60
84
  export function subscribeCanvas(ws: { send: (data: string) => void }) {
61
85
  subscribers.add(ws)
62
86
  }
@@ -165,7 +165,25 @@ export class TelegramChannel extends BaseChannel {
165
165
  }
166
166
 
167
167
  if (text === "/new" || text?.startsWith("/new@")) {
168
- await ctx.reply("🔄 Sesión reiniciada.", { parse_mode: "HTML" });
168
+ // Antes sólo contestaba: el contexto seguía intacto y la conversación
169
+ // continuaba como si nada. Ahora borra de verdad el hilo de ESTE chat —los
170
+ // demás canales y las conversaciones de la web no se tocan.
171
+ try {
172
+ const { resolveContext } = await import("../gateway/resolver");
173
+ const { deleteThread } = await import("../agent/thread-store");
174
+ const { threadId } = await resolveContext({
175
+ channel: this.name,
176
+ channelUserId: peerId,
177
+ accountId: this.accountId,
178
+ peerId,
179
+ peerKind: kind,
180
+ });
181
+ await deleteThread(threadId);
182
+ await ctx.reply("🔄 Listo, empezamos de cero.", { parse_mode: "HTML" });
183
+ } catch (err) {
184
+ this.log.warn(`No pude reiniciar el hilo de ${peerId}: ${(err as Error).message}`);
185
+ await ctx.reply("No pude reiniciar la conversación.", { parse_mode: "HTML" });
186
+ }
169
187
  return;
170
188
  }
171
189