@johpaz/hive-agents 0.0.47 → 1.0.1

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 (322) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -897
  3. package/dist/hive.js +222237 -206295
  4. package/dist/tool-worker.js +226 -927
  5. package/dist/ui/assets/A2UIPage-D4nzp5NV.js +8 -0
  6. package/dist/ui/assets/AgentCreateForm-M2RhjeA1.js +1 -0
  7. package/dist/ui/assets/AgentDetailPage-DkFRtj8g.js +1 -0
  8. package/dist/ui/assets/AgentNewPage-CfBU7puz.js +1 -0
  9. package/dist/ui/assets/AgentsPage-Ctzq2LWx.js +10 -0
  10. package/dist/ui/assets/ApiClientPage-DKbGO1QW.js +3 -0
  11. package/dist/ui/assets/ChannelsPage-H6rgr8DQ.js +8 -0
  12. package/dist/ui/assets/DashboardPage-BIjYGf4m.js +6 -0
  13. package/dist/ui/assets/{LoginPage-BTxJdFVG.js → LoginPage-DazoxtBJ.js} +1 -1
  14. package/dist/ui/assets/{LogsPage-DVV2eHbh.js → LogsPage-DMZ6KtQ3.js} +1 -1
  15. package/dist/ui/assets/MeetingPage-CSLFvHL7.js +1 -0
  16. package/dist/ui/assets/ModelSelector-BCfvugHB.js +1 -0
  17. package/dist/ui/assets/{NotFound-BIUDlIXU.js → NotFound-Bpr12V51.js} +1 -1
  18. package/dist/ui/assets/Office3DPage-BE6Epe0d.js +4614 -0
  19. package/dist/ui/assets/Office3DPage-C3SIzd2H.css +1 -0
  20. package/dist/ui/assets/ProvidersPage-D0cApfM1.js +1 -0
  21. package/dist/ui/assets/{RecoverPage-7YDQysBL.js → RecoverPage-BVUPHG9z.js} +1 -1
  22. package/dist/ui/assets/SettingsPage-DCZ4nql4.js +9 -0
  23. package/dist/ui/assets/SetupPage-In19p30M.js +1 -0
  24. package/dist/ui/assets/WebChatPage-ByVBSzxL.js +29 -0
  25. package/dist/ui/assets/{activity-c3pNngT_.js → activity-BIIli7ET.js} +1 -1
  26. package/dist/ui/assets/agentCapabilities-D1PD9yFH.js +1 -0
  27. package/dist/ui/assets/alert-CQlRq6sv.js +1 -0
  28. package/dist/ui/assets/arrow-left-BfcnX8Er.js +1 -0
  29. package/dist/ui/assets/arrow-right-Q-dzAn8k.js +1 -0
  30. package/dist/ui/assets/arrow-up-right-Bf-8wrUQ.js +1 -0
  31. package/dist/ui/assets/badge-DKGZbVZJ.js +1 -0
  32. package/dist/ui/assets/{calendar-B-KZ9RQO.js → calendar-S9-_Q6QR.js} +1 -1
  33. package/dist/ui/assets/{card-CNf6BS2e.js → card-D3Nw3kh3.js} +1 -1
  34. package/dist/ui/assets/check-CryV78SQ.js +1 -0
  35. package/dist/ui/assets/chevron-down-QCtMs-Af.js +1 -0
  36. package/dist/ui/assets/chevron-left-dTGbyl5G.js +1 -0
  37. package/dist/ui/assets/chevron-right-D0GjXbnO.js +1 -0
  38. package/dist/ui/assets/chevron-up-Cg0jO8uT.js +1 -0
  39. package/dist/ui/assets/{circle-alert-KuAm2FWh.js → circle-alert-DTVW4R94.js} +1 -1
  40. package/dist/ui/assets/circle-check-BAolxswA.js +1 -0
  41. package/dist/ui/assets/{circle-x-DjLkFDO8.js → circle-x-CJXbXzRh.js} +1 -1
  42. package/dist/ui/assets/{copy-Bu5d7C-0.js → copy-X_TPpA-A.js} +1 -1
  43. package/dist/ui/assets/{dialog-Jk4bieO4.js → dialog-uUBz_NIB.js} +1 -1
  44. package/dist/ui/assets/dist-CD_qfA30.js +1 -0
  45. package/dist/ui/assets/{download-Cjbk4Rek.js → download-C-fXu08w.js} +1 -1
  46. package/dist/ui/assets/earth-CTsVjCmp.js +1 -0
  47. package/dist/ui/assets/ellipsis-vertical-5zBh5yzc.js +1 -0
  48. package/dist/ui/assets/{external-link-6sTlRDUR.js → external-link-CvpRhwC_.js} +1 -1
  49. package/dist/ui/assets/{eye-Df8o0tkC.js → eye-CM-HQEWU.js} +1 -1
  50. package/dist/ui/assets/{file-text-lnxnjBp0.js → file-text-lwkvYGtA.js} +1 -1
  51. package/dist/ui/assets/{gateway-url-DwzPmoc8.js → gateway-url-BlnabM5e.js} +1 -1
  52. package/dist/ui/assets/gauge-CB-cas-h.js +1 -0
  53. package/dist/ui/assets/{history-CAF_R34_.js → history-eSHspWRr.js} +1 -1
  54. package/dist/ui/assets/index-D489S18g.css +2 -0
  55. package/dist/ui/assets/index-ZjAc-KQS.js +116 -0
  56. package/dist/ui/assets/{info-WjromB4Y.js → info-DTgFQ_jA.js} +1 -1
  57. package/dist/ui/assets/key-CeM9JJkq.js +1 -0
  58. package/dist/ui/assets/label-k0jYxoWW.js +1 -0
  59. package/dist/ui/assets/loader-circle-Dtfz4FWw.js +1 -0
  60. package/dist/ui/assets/lock-open-B089GUAJ.js +1 -0
  61. package/dist/ui/assets/mail--gNFIe4M.js +1 -0
  62. package/dist/ui/assets/{pause-VqeUmp2Z.js → pause-DjT1nwQM.js} +1 -1
  63. package/dist/ui/assets/pencil-6PRgdjiU.js +1 -0
  64. package/dist/ui/assets/play-tOrP0xUJ.js +1 -0
  65. package/dist/ui/assets/plus-Cnom3j47.js +1 -0
  66. package/dist/ui/assets/progress-DrI2UDu-.js +1 -0
  67. package/dist/ui/assets/radio-D-joO9J0.js +1 -0
  68. package/dist/ui/assets/{refresh-cw-CCzDCAuz.js → refresh-cw-BRrzoHQW.js} +1 -1
  69. package/dist/ui/assets/scroll-area-CfHn94Vb.js +1 -0
  70. package/dist/ui/assets/search-D277MUP0.js +1 -0
  71. package/dist/ui/assets/select-BOR8MsSL.js +1 -0
  72. package/dist/ui/assets/{send-BPk9XbIq.js → send-DIlj81PT.js} +1 -1
  73. package/dist/ui/assets/{settings-BGfrZ_zM.js → settings-CkBjgAEm.js} +1 -1
  74. package/dist/ui/assets/{shield-CxhcUT39.js → shield-U0hIjGzm.js} +1 -1
  75. package/dist/ui/assets/slider-CmE_z1Ii.js +1 -0
  76. package/dist/ui/assets/{sparkles-BhwlS1pc.js → sparkles-VXHGDbNh.js} +1 -1
  77. package/dist/ui/assets/{square-DMNWw4Hi.js → square-OHeetvN3.js} +1 -1
  78. package/dist/ui/assets/switch-DXcELPsM.js +1 -0
  79. package/dist/ui/assets/tabs-CxiybXcw.js +1 -0
  80. package/dist/ui/assets/terminal-C6YPcJl_.js +1 -0
  81. package/dist/ui/assets/{textarea-B6Z1Zc6W.js → textarea-rp6vsOZl.js} +1 -1
  82. package/dist/ui/assets/{trash-2-xD2o4SgX.js → trash-2-DQxm7DUM.js} +1 -1
  83. package/dist/ui/assets/{triangle-alert-pVIJGjga.js → triangle-alert-Dj8ZhmWj.js} +1 -1
  84. package/dist/ui/assets/{useHiveAgentsModelLoad-BnC4jLE-.js → useHiveAgentsModelLoad-COLvs-Ho.js} +1 -1
  85. package/dist/ui/assets/useOfficeModel-Cy7cAyEn.js +1 -0
  86. package/dist/ui/assets/useProviders-q6iROeWE.js +1 -0
  87. package/dist/ui/assets/utils-Dyb7SC2_.js +1 -0
  88. package/dist/ui/assets/vendor-charts-K3xcRl0X.js +60 -0
  89. package/dist/ui/assets/{vendor-query-DsWPbQdG.js → vendor-query-Dj8xYhQD.js} +1 -1
  90. package/dist/ui/assets/vendor-radix-D0s_k6Gp.js +63 -0
  91. package/dist/ui/assets/vendor-react-CPJEWbIG.js +1 -0
  92. package/dist/ui/assets/{vendor-router-gqiZ7xhx.js → vendor-router-zpB-76nT.js} +1 -1
  93. package/dist/ui/assets/volume-x-Bm735CXN.js +1 -0
  94. package/dist/ui/assets/wifi-DklBfOZ6.js +1 -0
  95. package/dist/ui/assets/{zap-B4RaNNO5.js → zap-BEZNJ0i0.js} +1 -1
  96. package/dist/ui/index.html +16 -13
  97. package/dist/ui/logoblack.png +0 -0
  98. package/dist/ui/logocolor-dark.png +0 -0
  99. package/dist/ui/logocolorbg.png +0 -0
  100. package/dist/ui/logodoradobg.png +0 -0
  101. package/package.json +18 -15
  102. package/packages/cli/src/adapters/config.ts +1 -80
  103. package/packages/cli/src/adapters/factory.ts +0 -45
  104. package/packages/cli/src/adapters/index.ts +0 -8
  105. package/packages/cli/src/commands/doctor.ts +156 -1
  106. package/packages/cli/src/commands/gateway.ts +2 -9
  107. package/packages/cli/src/commands/onboard.ts +126 -59
  108. package/packages/cli/src/index.ts +9 -11
  109. package/packages/cli/src/ui-bundle.generated.ts +9 -92
  110. package/packages/core/src/agent/acceptance-checks.ts +172 -0
  111. package/packages/core/src/agent/agent-catalog.ts +348 -0
  112. package/packages/core/src/agent/agent-loop.ts +204 -28
  113. package/packages/core/src/agent/capability-search.ts +5 -5
  114. package/packages/core/src/agent/catalog-selector.ts +103 -0
  115. package/packages/core/src/agent/compaction.ts +52 -42
  116. package/packages/core/src/agent/context-compiler.ts +185 -63
  117. package/packages/core/src/agent/conversation-store.ts +56 -3
  118. package/packages/core/src/agent/curator.ts +129 -34
  119. package/packages/core/src/agent/delegation-runtime.ts +241 -0
  120. package/packages/core/src/agent/goal-runner.ts +111 -32
  121. package/packages/core/src/agent/index.ts +17 -0
  122. package/packages/core/src/agent/llm-client.ts +34 -2
  123. package/packages/core/src/agent/llm-providers/anthropic.ts +10 -7
  124. package/packages/core/src/agent/llm-providers/hiveagents.ts +1 -1
  125. package/packages/core/src/agent/llm-providers/interface.ts +16 -5
  126. package/packages/core/src/agent/llm-providers/modelscope.ts +5 -0
  127. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
  128. package/packages/core/src/agent/llm-providers/z-ai.ts +5 -0
  129. package/packages/core/src/agent/minimal-loadout.ts +47 -0
  130. package/packages/core/src/agent/playbook-selector.ts +1 -1
  131. package/packages/core/src/agent/prompt-builder.ts +4 -0
  132. package/packages/core/src/agent/proof-packet.ts +6 -1
  133. package/packages/core/src/agent/providers/index.ts +9 -4
  134. package/packages/core/src/agent/routing-intent.ts +22 -0
  135. package/packages/core/src/agent/run-store.ts +24 -3
  136. package/packages/core/src/agent/service.ts +2 -2
  137. package/packages/core/src/agent/skill-selector.ts +12 -31
  138. package/packages/core/src/agent/tool-selector.ts +61 -36
  139. package/packages/core/src/agent/tracer.ts +5 -1
  140. package/packages/core/src/artifacts/store.ts +162 -0
  141. package/packages/core/src/canvas/canvas-manager.ts +5 -234
  142. package/packages/core/src/canvas/emitter.ts +121 -69
  143. package/packages/core/src/canvas/index.ts +0 -2
  144. package/packages/core/src/channels/base.ts +3 -1
  145. package/packages/core/src/channels/manager.ts +117 -25
  146. package/packages/core/src/channels/webchat.ts +4 -8
  147. package/packages/core/src/channels/whatsapp.ts +6 -1
  148. package/packages/core/src/config/loader.ts +13 -23
  149. package/packages/core/src/events/agent-bus.ts +0 -31
  150. package/packages/core/src/events/channel-narration.ts +150 -0
  151. package/packages/core/src/events/narration.ts +82 -0
  152. package/packages/core/src/events/tool-narration.ts +62 -0
  153. package/packages/core/src/gateway/channel-notify.ts +43 -10
  154. package/packages/core/src/gateway/delegation-groups.ts +258 -0
  155. package/packages/core/src/gateway/delegation-notify.ts +103 -0
  156. package/packages/core/src/gateway/durable-queue.ts +33 -2
  157. package/packages/core/src/gateway/helpers/index.ts +2 -2
  158. package/packages/core/src/gateway/helpers/narration.ts +4 -57
  159. package/packages/core/src/gateway/helpers/redact.ts +1 -1
  160. package/packages/core/src/gateway/helpers/ui-source.ts +67 -0
  161. package/packages/core/src/gateway/initializer.ts +15 -13
  162. package/packages/core/src/gateway/job-executors.ts +197 -104
  163. package/packages/core/src/gateway/lane-queue.ts +1 -1
  164. package/packages/core/src/gateway/notification-inbox.ts +57 -0
  165. package/packages/core/src/gateway/resolver.ts +11 -25
  166. package/packages/core/src/gateway/routes/agents.ts +91 -1
  167. package/packages/core/src/gateway/routes/auth.ts +21 -42
  168. package/packages/core/src/gateway/routes/channels.ts +15 -1
  169. package/packages/core/src/gateway/routes/chat.ts +6 -6
  170. package/packages/core/src/gateway/routes/cron-api.ts +0 -4
  171. package/packages/core/src/gateway/routes/mcp.ts +0 -63
  172. package/packages/core/src/gateway/routes/meeting.ts +245 -0
  173. package/packages/core/src/gateway/routes/models.ts +69 -12
  174. package/packages/core/src/gateway/routes/providers.ts +111 -28
  175. package/packages/core/src/gateway/routes/setup.ts +92 -35
  176. package/packages/core/src/gateway/routes/skills.ts +2 -2
  177. package/packages/core/src/gateway/routes/system.ts +31 -10
  178. package/packages/core/src/gateway/routes/users.ts +24 -1
  179. package/packages/core/src/gateway/routes/voice.ts +3 -0
  180. package/packages/core/src/gateway/server.ts +207 -141
  181. package/packages/core/src/gateway/session.ts +6 -4
  182. package/packages/core/src/gateway/slash-commands.ts +7 -6
  183. package/packages/core/src/gateway/webchat-turn.ts +63 -13
  184. package/packages/core/src/index.ts +3 -0
  185. package/packages/core/src/mcp/hot-reload.ts +14 -7
  186. package/packages/core/src/mcp/singleton.ts +0 -3
  187. package/packages/core/src/mcp/tool-sync.ts +2 -2
  188. package/packages/core/src/resilience/retry.ts +1 -1
  189. package/packages/core/src/scheduler/CronScheduler.ts +3 -1
  190. package/packages/core/src/scheduler/integration.ts +1 -1
  191. package/packages/core/src/storage/bootstrap.ts +34 -10
  192. package/packages/core/src/storage/collections.ts +167 -27
  193. package/packages/core/src/storage/crypto.ts +147 -58
  194. package/packages/core/src/storage/hivedb.ts +9 -0
  195. package/packages/core/src/storage/model-id.ts +53 -0
  196. package/packages/core/src/storage/onboarding.ts +160 -34
  197. package/packages/core/src/storage/reconcile.ts +2 -5
  198. package/packages/core/src/storage/seed.ts +436 -158
  199. package/packages/core/src/storage/usage.ts +61 -132
  200. package/packages/core/src/storage/user-email.ts +11 -0
  201. package/packages/core/src/tool-runtime/index.ts +69 -23
  202. package/packages/core/src/tool-runtime/worker-tools.ts +4 -2
  203. package/packages/core/src/{canvas/a2ui-tools.ts → tools/a2ui/index.ts} +17 -8
  204. package/packages/core/src/tools/agents/index.ts +566 -85
  205. package/packages/core/src/tools/core/index.ts +28 -10
  206. package/packages/core/src/tools/cron/index.ts +1 -6
  207. package/packages/core/src/tools/index.ts +19 -46
  208. package/packages/core/src/tools/types.ts +1 -1
  209. package/packages/core/src/tools/web/artifact-inspect.ts +23 -0
  210. package/packages/core/src/tools/web/browser-backend.ts +129 -0
  211. package/packages/core/src/tools/web/browser-screenshot.ts +26 -5
  212. package/packages/core/src/tools/web/browser-service.ts +75 -35
  213. package/packages/core/src/tools/web/index.ts +3 -0
  214. package/packages/core/src/tools/web/webview-backend.ts +412 -0
  215. package/packages/core/src/utils/logger.ts +58 -30
  216. package/packages/core/src/utils/toon.ts +0 -20
  217. package/packages/core/src/voice/index.ts +108 -17
  218. package/packages/mcp/src/manager.ts +8 -7
  219. package/packages/mcp/src/transports/sse.ts +0 -4
  220. package/packages/mcp/src/transports/websocket.ts +0 -6
  221. package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_dashboard/SKILL.md +4 -4
  222. package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_form/SKILL.md +4 -4
  223. package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_interactive/SKILL.md +5 -5
  224. package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +24 -18
  225. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +48 -148
  226. package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +9 -10
  227. package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +1 -1
  228. package/packages/skills/src/bundled/cli/software_engineering/SKILL.md +23 -0
  229. package/packages/skills/src/bundled/cron_manager/SKILL.md +2 -2
  230. package/packages/skills/src/bundled/cron_reminder/SKILL.md +7 -7
  231. package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +11 -10
  232. package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +29 -35
  233. package/packages/skills/src/bundled/filesystem/workspace_file_operator/SKILL.md +22 -0
  234. package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +5 -4
  235. package/packages/skills/src/bundled-data.generated.ts +640 -1226
  236. package/dist/ui/assets/AgentCreateForm-DzaIT-dA.js +0 -1
  237. package/dist/ui/assets/AgentDetailPage-DgqcJceY.js +0 -1
  238. package/dist/ui/assets/AgentNewPage-CNSpoOSA.js +0 -1
  239. package/dist/ui/assets/AgentsPage-BMUJzTD6.js +0 -10
  240. package/dist/ui/assets/ApiClientPage-Cum_a_3j.js +0 -3
  241. package/dist/ui/assets/CanvasPage-o6oCP6uq.js +0 -33
  242. package/dist/ui/assets/ChannelsPage-WrB0zwLq.js +0 -8
  243. package/dist/ui/assets/DashboardPage-BCd6kNw0.js +0 -6
  244. package/dist/ui/assets/MeetingPage-BULIAWzq.js +0 -1
  245. package/dist/ui/assets/ModelSelector-BMYOChYb.js +0 -1
  246. package/dist/ui/assets/ProvidersPage-BVN5UZrI.js +0 -1
  247. package/dist/ui/assets/SettingsPage-CYmpFfDn.js +0 -9
  248. package/dist/ui/assets/SetupPage-Dnmb1Lbv.js +0 -1
  249. package/dist/ui/assets/WebChatPage-DmmdFhIC.js +0 -16
  250. package/dist/ui/assets/accordion-CnLzKNHK.js +0 -1
  251. package/dist/ui/assets/alert-B9J6KHmt.js +0 -1
  252. package/dist/ui/assets/alert-dialog-KcYQWcJ6.js +0 -1
  253. package/dist/ui/assets/arrow-left-CBcbX5EZ.js +0 -1
  254. package/dist/ui/assets/badge-88dRb4M8.js +0 -1
  255. package/dist/ui/assets/bell-8BqRYmzf.js +0 -1
  256. package/dist/ui/assets/chevron-down-DIosfU_U.js +0 -1
  257. package/dist/ui/assets/chevron-left-D4U-5A27.js +0 -1
  258. package/dist/ui/assets/chevron-right-CR4Skrf3.js +0 -1
  259. package/dist/ui/assets/chevron-up-CI-W21Fy.js +0 -1
  260. package/dist/ui/assets/circle-check-6Ard1-2z.js +0 -1
  261. package/dist/ui/assets/dropdown-menu-DDiaHg5y.js +0 -1
  262. package/dist/ui/assets/es-4I-joeZz.js +0 -1
  263. package/dist/ui/assets/folder-open-DJBLDFjv.js +0 -1
  264. package/dist/ui/assets/format-DsLPBxvt.js +0 -1
  265. package/dist/ui/assets/gauge-B8Tj43rC.js +0 -1
  266. package/dist/ui/assets/hexagon-6L79pgVK.js +0 -1
  267. package/dist/ui/assets/index-BmwTAwOF.css +0 -2
  268. package/dist/ui/assets/index-Cyw7L0Li.js +0 -116
  269. package/dist/ui/assets/key-DyKOoQh5.js +0 -1
  270. package/dist/ui/assets/label-B_15zZlR.js +0 -1
  271. package/dist/ui/assets/loader-circle-BmBOgYze.js +0 -1
  272. package/dist/ui/assets/lock-BS6OLXPv.js +0 -1
  273. package/dist/ui/assets/play-zJpWuhrr.js +0 -1
  274. package/dist/ui/assets/plus-BZQX26Dr.js +0 -1
  275. package/dist/ui/assets/progress-D5c-Eilm.js +0 -1
  276. package/dist/ui/assets/scroll-area-CihOx0cb.js +0 -1
  277. package/dist/ui/assets/search-DzDptO9s.js +0 -1
  278. package/dist/ui/assets/select-BQCOjM2j.js +0 -1
  279. package/dist/ui/assets/slider-bcUiUfx0.js +0 -14
  280. package/dist/ui/assets/switch-BR30E4ej.js +0 -1
  281. package/dist/ui/assets/table-B3aGEaVp.js +0 -1
  282. package/dist/ui/assets/tabs-LQidMKRS.js +0 -1
  283. package/dist/ui/assets/terminal--7G943As.js +0 -1
  284. package/dist/ui/assets/useProviders-C1xVKLxB.js +0 -1
  285. package/dist/ui/assets/utils-3pnRFmFe.js +0 -1
  286. package/dist/ui/assets/vendor-charts-Bu2lyBKP.js +0 -65
  287. package/dist/ui/assets/vendor-radix-D6rA7xKY.js +0 -63
  288. package/dist/ui/assets/vendor-react-BU5iQU4f.js +0 -1
  289. package/dist/ui/assets/volume-2-BekVQl6P.js +0 -1
  290. package/packages/core/src/agent/context-guard.ts +0 -91
  291. package/packages/core/src/agent/hooks.ts +0 -166
  292. package/packages/core/src/agent/providers.ts +0 -1
  293. package/packages/core/src/auth/auth.ts +0 -111
  294. package/packages/core/src/auth/index.ts +0 -1
  295. package/packages/core/src/canvas/canvas-tools.ts +0 -448
  296. package/packages/core/src/gateway/router.ts +0 -126
  297. package/packages/core/src/scheduler/dag/AgentExecutor.ts +0 -53
  298. package/packages/core/src/scheduler/dag/DAGScheduler.ts +0 -250
  299. package/packages/core/src/scheduler/dag/EventBridge.ts +0 -122
  300. package/packages/core/src/scheduler/dag/TaskGraph.ts +0 -192
  301. package/packages/core/src/scheduler/dag/TaskNode.ts +0 -97
  302. package/packages/core/src/scheduler/dag/TaskResult.ts +0 -22
  303. package/packages/core/src/scheduler/dag/errors.ts +0 -37
  304. package/packages/core/src/scheduler/dag/index.ts +0 -26
  305. package/packages/core/src/scheduler/dag/presets/ResearchPreset.ts +0 -97
  306. package/packages/core/src/scheduler/dag/strategies/ParallelStrategy.ts +0 -21
  307. package/packages/core/src/scheduler/dag/strategies/PriorityStrategy.ts +0 -46
  308. package/packages/core/src/scheduler/index.ts +0 -22
  309. package/packages/core/src/scheduler/task-driver.ts +0 -216
  310. package/packages/core/src/tools/canvas/index.ts +0 -420
  311. package/packages/core/src/tools/meeting/index.ts +0 -336
  312. package/packages/core/src/tools/projects/index.ts +0 -348
  313. package/packages/core/src/tools/voice/index.ts +0 -104
  314. package/packages/core/src/utils/index.ts +0 -5
  315. package/packages/skills/src/bundled/agents/code_delegator/SKILL.md +0 -156
  316. package/packages/skills/src/bundled/canvas/canvas_dashboard/SKILL.md +0 -146
  317. package/packages/skills/src/bundled/canvas/canvas_interact/SKILL.md +0 -148
  318. package/packages/skills/src/bundled/canvas/canvas_report/SKILL.md +0 -146
  319. package/packages/skills/src/bundled/meeting/meeting_transcription/SKILL.md +0 -213
  320. package/packages/skills/src/bundled/voice/voice_assistant/SKILL.md +0 -174
  321. package/packages/skills/src/bundled/voice/voice_input/SKILL.md +0 -146
  322. package/packages/skills/src/bundled/voice/voice_output/SKILL.md +0 -151
@@ -7,7 +7,7 @@ import { createWebChatChannel, type WebChatConfig } from "./webchat.ts";
7
7
  import { createWhatsAppChannel, WhatsAppChannel, type WhatsAppConfig } from "./whatsapp.ts";
8
8
  import { createSlackChannel, type SlackConfig } from "./slack.ts";
9
9
  import { col } from "../storage/hive.ts";
10
- import type { ChannelDoc, AgentDoc } from "../storage/collections.ts";
10
+ import type { ChannelDoc, AgentDoc, UserIdentityDoc } from "../storage/collections.ts";
11
11
  import { loadChannelConfig } from "../storage/crypto.ts";
12
12
 
13
13
  export class ChannelManager {
@@ -15,11 +15,44 @@ export class ChannelManager {
15
15
  private channels: Map<string, IChannel> = new Map();
16
16
  private messageHandler?: MessageHandler;
17
17
  private log = logger.child("channels");
18
+ /**
19
+ * `channel:sessionId` → accountId of the account that received the message.
20
+ *
21
+ * Outbound calls (agent reply, narration, notify tools, scheduler) only carry
22
+ * a channel name and a routing session id. With two accounts of the same type
23
+ * connected — two WhatsApp numbers — picking a channel by name alone sends the
24
+ * reply out through whichever account happens to be first, to a peer that may
25
+ * not even exist there. Every inbound message records its account here so the
26
+ * reply goes back out the way it came in.
27
+ *
28
+ * Known limit: if the same peer id talks to two accounts of one type, the
29
+ * routing session id is identical for both and the most recent inbound
30
+ * message wins. Distinguishing them would require the account in the session
31
+ * id itself.
32
+ */
33
+ private sessionAccounts: Map<string, string> = new Map();
18
34
 
19
35
  constructor(config: Config) {
20
36
  this.config = config;
21
37
  }
22
38
 
39
+ private sessionKey(channelName: string, sessionId: string): string {
40
+ return `${channelName}:${sessionId}`;
41
+ }
42
+
43
+ /**
44
+ * Resolves which account owns an outbound session: an explicit account wins,
45
+ * then the account that last received a message on it.
46
+ */
47
+ private resolveAccountId(
48
+ channelName: string,
49
+ sessionId: string,
50
+ explicit?: string
51
+ ): string | undefined {
52
+ if (explicit) return explicit;
53
+ return this.sessionAccounts.get(this.sessionKey(channelName, sessionId));
54
+ }
55
+
23
56
  onMessage(handler: MessageHandler): void {
24
57
  this.messageHandler = handler;
25
58
  }
@@ -33,9 +66,31 @@ export class ChannelManager {
33
66
  await this.initializeFromConfig();
34
67
  }
35
68
 
69
+ await this.seedSessionAccounts();
70
+
36
71
  this.log.info(`Initialized ${this.channels.size} channel(s)`);
37
72
  }
38
73
 
74
+ /**
75
+ * Restores session→account routing from persisted identities. Without this, a
76
+ * durable worker that finishes after a restart would have no record of which
77
+ * account its conversation came in on.
78
+ */
79
+ private async seedSessionAccounts(): Promise<void> {
80
+ try {
81
+ const identitiesCol = await col<UserIdentityDoc>("userIdentities");
82
+ for (const { doc } of await identitiesCol.scan({})) {
83
+ if (!doc.account_id || !doc.channel_user_id) continue;
84
+ // Skip identities whose account is gone (disconnected and replaced by
85
+ // another one) — pinning a session to it would only fail every send.
86
+ if (!this.channels.has(`${doc.channel}:${doc.account_id}`)) continue;
87
+ this.sessionAccounts.set(this.sessionKey(doc.channel, doc.channel_user_id), doc.account_id);
88
+ }
89
+ } catch (error) {
90
+ this.log.debug(`Could not seed session accounts: ${(error as Error).message}`);
91
+ }
92
+ }
93
+
39
94
  private async initializeFromDB(): Promise<void> {
40
95
  try {
41
96
  const channelsCol = await col<ChannelDoc>("channels");
@@ -84,6 +139,26 @@ export class ChannelManager {
84
139
  }
85
140
  }
86
141
 
142
+ /**
143
+ * Wires a channel into the manager: inbound messages record which account
144
+ * received them before reaching the handler, so replies can be routed back.
145
+ */
146
+ private registerChannel(key: string, channel: IChannel): void {
147
+ channel.onMessage(async (message: IncomingMessage) => {
148
+ if (message.accountId && message.sessionId) {
149
+ this.sessionAccounts.set(
150
+ this.sessionKey(message.channel, message.sessionId),
151
+ message.accountId
152
+ );
153
+ }
154
+ if (this.messageHandler) {
155
+ await this.messageHandler(message);
156
+ }
157
+ });
158
+
159
+ this.channels.set(key, channel);
160
+ }
161
+
87
162
  private async createChannel(
88
163
  channelName: string,
89
164
  accountId: string,
@@ -158,14 +233,8 @@ export class ChannelManager {
158
233
  return;
159
234
  }
160
235
 
161
- channel.onMessage(async (message: IncomingMessage) => {
162
- if (this.messageHandler) {
163
- await this.messageHandler(message);
164
- }
165
- });
166
-
167
236
  const key = `${channelName}:${accountId}`;
168
- this.channels.set(key, channel);
237
+ this.registerChannel(key, channel);
169
238
 
170
239
  this.log.info(`Created channel: ${key}`);
171
240
  } catch (error) {
@@ -217,22 +286,35 @@ export class ChannelManager {
217
286
 
218
287
  getChannel(channelName: string, accountId?: string): IChannel | undefined {
219
288
  if (accountId) {
220
- return this.channels.get(`${channelName}:${accountId}`);
221
- }
222
-
223
- for (const [key, channel] of this.channels) {
224
- if (key.startsWith(channelName)) {
225
- return channel;
289
+ const exact = this.channels.get(`${channelName}:${accountId}`);
290
+ // Deliberately no fallback: delivering through a different account would
291
+ // send someone else's conversation out of the wrong number.
292
+ if (!exact) {
293
+ this.log.warn(`Channel ${channelName}:${accountId} is not instantiated — refusing to fall back to another account`);
226
294
  }
295
+ return exact;
227
296
  }
228
297
 
229
- return undefined;
298
+ const matches = [...this.channels.entries()].filter(([key]) => key.startsWith(`${channelName}:`));
299
+ if (matches.length > 1) {
300
+ this.log.warn(
301
+ `${matches.length} "${channelName}" accounts are connected and no account was given — routing through ${matches[0]![0]}`
302
+ );
303
+ }
304
+ return matches[0]?.[1];
230
305
  }
231
306
 
232
307
  async removeChannel(channelName: string, accountId: string): Promise<void> {
233
308
  const key = `${channelName}:${accountId}`;
234
309
  await this.stopChannel(channelName, accountId);
235
310
  this.channels.delete(key);
311
+ // Drop sessions pinned to this account, otherwise every later send to them
312
+ // resolves to a channel that no longer exists.
313
+ for (const [sessionKey, account] of this.sessionAccounts) {
314
+ if (account === accountId && sessionKey.startsWith(`${channelName}:`)) {
315
+ this.sessionAccounts.delete(sessionKey);
316
+ }
317
+ }
236
318
  this.log.info(`Removed channel: ${key}`);
237
319
  }
238
320
 
@@ -398,12 +480,22 @@ export class ChannelManager {
398
480
  });
399
481
  }
400
482
 
483
+ /** Resolves the account that owns this session (see `sessionAccounts`). */
484
+ private channelForSession(
485
+ channelName: string,
486
+ sessionId: string,
487
+ accountId?: string
488
+ ): IChannel | undefined {
489
+ return this.getChannel(channelName, this.resolveAccountId(channelName, sessionId, accountId));
490
+ }
491
+
401
492
  async send(
402
493
  channelName: string,
403
494
  sessionId: string,
404
- message: unknown
495
+ message: unknown,
496
+ accountId?: string
405
497
  ): Promise<void> {
406
- const channel = this.getChannel(channelName);
498
+ const channel = this.channelForSession(channelName, sessionId, accountId);
407
499
 
408
500
  if (!channel) {
409
501
  throw new Error(`Channel not found: ${channelName}`);
@@ -412,29 +504,29 @@ export class ChannelManager {
412
504
  await channel.send(sessionId, message as any);
413
505
  }
414
506
 
415
- async startTyping(channelName: string, sessionId: string): Promise<void> {
416
- const channel = this.getChannel(channelName);
507
+ async startTyping(channelName: string, sessionId: string, accountId?: string): Promise<void> {
508
+ const channel = this.channelForSession(channelName, sessionId, accountId);
417
509
  if (channel?.startTyping) {
418
510
  await channel.startTyping(sessionId);
419
511
  }
420
512
  }
421
513
 
422
- async stopTyping(channelName: string, sessionId: string): Promise<void> {
423
- const channel = this.getChannel(channelName);
514
+ async stopTyping(channelName: string, sessionId: string, accountId?: string): Promise<void> {
515
+ const channel = this.channelForSession(channelName, sessionId, accountId);
424
516
  if (channel?.stopTyping) {
425
517
  await channel.stopTyping(sessionId);
426
518
  }
427
519
  }
428
520
 
429
- async markAsRead(channelName: string, sessionId: string, messageId?: string): Promise<void> {
430
- const channel = this.getChannel(channelName);
521
+ async markAsRead(channelName: string, sessionId: string, messageId?: string, accountId?: string): Promise<void> {
522
+ const channel = this.channelForSession(channelName, sessionId, accountId);
431
523
  if (channel?.markAsRead) {
432
524
  await channel.markAsRead(sessionId, messageId);
433
525
  }
434
526
  }
435
527
 
436
- async sendAudio(channelName: string, sessionId: string, audio: Buffer, mimeType: string): Promise<void> {
437
- const channel = this.getChannel(channelName);
528
+ async sendAudio(channelName: string, sessionId: string, audio: Buffer, mimeType: string, accountId?: string): Promise<void> {
529
+ const channel = this.channelForSession(channelName, sessionId, accountId);
438
530
  if (!channel) {
439
531
  throw new Error(`Channel not found: ${channelName}`);
440
532
  }
@@ -51,7 +51,8 @@ export class WebChatChannel extends BaseChannel {
51
51
  this.log.debug(`WebChat connection registered: ${data.sessionId}`);
52
52
  }
53
53
 
54
- unregisterConnection(sessionId: string): void {
54
+ unregisterConnection(sessionId: string, ws?: ServerWebSocket<WebSocketData>): void {
55
+ if (ws && this.connections.get(sessionId) !== ws) return;
55
56
  this.connections.delete(sessionId);
56
57
  this.log.debug(`WebChat connection unregistered: ${sessionId}`);
57
58
  }
@@ -91,15 +92,10 @@ export class WebChatChannel extends BaseChannel {
91
92
  const ws = this.connections.get(sessionId);
92
93
 
93
94
  if (!ws) {
94
- this.log.warn(`No WebChat connection for session: ${sessionId}`);
95
- return;
95
+ throw new Error(`No WebChat connection for session: ${sessionId}`);
96
96
  }
97
97
 
98
- try {
99
- ws.send(JSON.stringify(message));
100
- } catch (error) {
101
- this.log.error(`Failed to send WebChat message: ${(error as Error).message}`);
102
- }
98
+ ws.send(JSON.stringify(message));
103
99
  }
104
100
 
105
101
  async sendAudio(sessionId: string, audio: Buffer, mimeType: string): Promise<void> {
@@ -482,7 +482,11 @@ export class WhatsAppChannel extends BaseChannel {
482
482
  throw new Error("WhatsApp not connected");
483
483
  }
484
484
 
485
- await this.stopTyping(sessionId);
485
+ // Progress narration arrives mid-turn. Clearing "typing…" on it would leave
486
+ // the user watching interim messages with no sign the agent is still
487
+ // working — only a final message ends the indicator.
488
+ const isInterim = message.type === "progress";
489
+ if (!isInterim) await this.stopTyping(sessionId);
486
490
 
487
491
  const text = message.content ?? message.chunk ?? "";
488
492
  if (!text) return;
@@ -490,6 +494,7 @@ export class WhatsAppChannel extends BaseChannel {
490
494
  const jid = this.getJid(sessionId);
491
495
 
492
496
  await this.socket.sendMessage(jid, { text });
497
+ if (isInterim) await this.startTyping(sessionId);
493
498
  this.log.debug(`Sent message to ${jid}`);
494
499
  }
495
500
 
@@ -19,8 +19,15 @@ export function loadEnv(hiveDir: string): void {
19
19
 
20
20
  const [key, ...valueParts] = trimmed.split("=");
21
21
  if (key && valueParts.length > 0) {
22
+ const normalizedKey = key.trim();
22
23
  const value = valueParts.join("=").trim().replace(/^['"]|['"]$/g, "");
23
- process.env[key.trim()] = value;
24
+ // Explicit process environment values (for example the random
25
+ // port assigned by the desktop shell) must take precedence over the
26
+ // persisted .env file. This follows dotenv conventions and prevents
27
+ // a previous CLI port from breaking desktop startup.
28
+ if (process.env[normalizedKey] === undefined) {
29
+ process.env[normalizedKey] = value;
30
+ }
24
31
  }
25
32
  }
26
33
  } catch (e) {
@@ -120,6 +127,11 @@ const BrowserConfigSchema = z.object({
120
127
  headless: z.boolean().optional(),
121
128
  timeoutMs: z.number().optional(),
122
129
  sessionName: z.string().optional(),
130
+ // "agent-browser" (default) usa Chrome via CLI y sirve headless/Docker.
131
+ // "webview" usa Bun.WebView in-process — mucho más rápido y sin instalación,
132
+ // pero requiere entorno gráfico. "auto" toma webview sólo si hay display.
133
+ // Lo pisa HIVE_BROWSER_BACKEND.
134
+ backend: z.enum(["agent-browser", "webview", "auto"]).optional(),
123
135
  });
124
136
 
125
137
  const CanvasConfigSchema = z.object({
@@ -346,17 +358,6 @@ const SecurityConfigSchema = z.object({
346
358
  allowedUsers: z.array(z.string()).optional(),
347
359
  });
348
360
 
349
- const CaptchaConfigSchema = z.object({
350
- enabled: z.boolean().optional(),
351
- autoSolve: z.boolean().optional(),
352
- visionProvider: z.enum(["gemini", "openai", "anthropic"]).optional(),
353
- visionModel: z.string().optional(),
354
- maxAttempts: z.number().optional(),
355
- maxRounds: z.number().optional(),
356
- apiKey: z.string().optional(),
357
- enabledSites: z.array(z.string()).optional(),
358
- });
359
-
360
361
  const UserConfigSchema = z.object({
361
362
  id: z.string(),
362
363
  name: z.string(),
@@ -389,7 +390,6 @@ const ConfigSchema = z.object({
389
390
  harness: HarnessConfigSchema.optional(),
390
391
  security: SecurityConfigSchema.optional(),
391
392
  hooks: HooksConfigSchema.optional(),
392
- captcha: CaptchaConfigSchema.optional(),
393
393
  });
394
394
 
395
395
  export type Config = z.infer<typeof ConfigSchema>;
@@ -399,7 +399,6 @@ export type MCPServerConfig = z.infer<typeof MCPServerConfigSchema>;
399
399
  export type AgentEntry = z.infer<typeof AgentEntrySchema>;
400
400
  export type Binding = z.infer<typeof BindingSchema>;
401
401
  export type UserConfig = z.infer<typeof UserConfigSchema>;
402
- export type CaptchaConfig = z.infer<typeof CaptchaConfigSchema>;
403
402
 
404
403
  function buildDefaultConfig(): Config {
405
404
  const hiveDir = getHiveDir();
@@ -564,15 +563,6 @@ function buildDefaultConfig(): Config {
564
563
  hooks: {
565
564
  scripts: {},
566
565
  },
567
- captcha: {
568
- enabled: false,
569
- autoSolve: true,
570
- visionProvider: 'gemini',
571
- visionModel: 'gemini-2.0-flash-exp',
572
- maxAttempts: 3,
573
- maxRounds: 5,
574
- enabledSites: [],
575
- },
576
566
  };
577
567
  }
578
568
 
@@ -224,37 +224,6 @@ export async function getUnreadMessagesForWorker(workerId: string, limit: number
224
224
  }
225
225
  }
226
226
 
227
- /**
228
- * Obtiene el historial de mensajes de un proyecto
229
- */
230
- export async function getProjectMessageHistory(projectId: string, limit: number = 100): Promise<AgentBusMessage[]> {
231
- try {
232
- // Primero obtenemos los task_ids del proyecto
233
- const tasksCol = await col<TaskDoc>("tasks");
234
- const tasks = (await tasksCol.findBy("project_id", projectId)).map(e => e.doc);
235
-
236
- if (tasks.length === 0) return [];
237
-
238
- // Obtenemos los agent_ids de las tareas
239
- const agentIds = new Set(
240
- tasks.map(t => fromIndexable(t.agent_id)).filter((id): id is string => id !== null)
241
- );
242
-
243
- if (agentIds.size === 0) return [];
244
-
245
- // Obtenemos mensajes relacionados a estos agents
246
- const messagesCol = await col<AgentBusMessageDoc>("agentBusMessages");
247
- const entries = (await messagesCol.scan({}))
248
- .filter(e => agentIds.has(fromIndexable(e.doc.from_worker_id) ?? ""))
249
- .sort((a, b) => b.doc.created_at - a.doc.created_at)
250
- .slice(0, limit);
251
-
252
- return entries.map(e => docToMessage(e.doc));
253
- } catch (err) {
254
- log.error(`Failed to get project message history: ${(err as Error).message}`);
255
- return [];
256
- }
257
- }
258
227
 
259
228
  // ─── Agent Bus Implementation ────────────────────────────────────────────────
260
229
 
@@ -0,0 +1,150 @@
1
+ // ─── Narration delivery policy for messaging channels ─────────────────────────
2
+ // WebChat renders narration as ephemeral, collapsible "process" widgets. A
3
+ // messaging channel (WhatsApp, Telegram, Slack, Discord) has no such surface:
4
+ // every narration event becomes a permanent chat message. Without a filter a
5
+ // single turn with a few tools and two delegated workers produces dozens of
6
+ // messages before the actual answer — noise for the user and a rate-limit /
7
+ // ban risk on WhatsApp. This module decides what reaches those channels.
8
+
9
+ import { col } from "../storage/hive";
10
+ import type { ChannelDoc, NarrationEventDoc } from "../storage/collections";
11
+ import { logger } from "../utils/logger";
12
+
13
+ const log = logger.child("narration:channel");
14
+
15
+ /** `off` = silent, `milestones` = delegation lifecycle only, `all` = + per-tool steps. */
16
+ export type NarrationMode = "off" | "milestones" | "all";
17
+
18
+ export const DEFAULT_NARRATION_MODE: NarrationMode = "milestones";
19
+
20
+ /** Legacy `step_delivery_mode` values predate this feature — map them forward. */
21
+ function coerceMode(raw: string | null | undefined): NarrationMode {
22
+ switch (raw) {
23
+ case "off":
24
+ case "milestones":
25
+ case "all":
26
+ return raw;
27
+ // "new_messages" was the original (never-read) default.
28
+ case "new_messages":
29
+ return DEFAULT_NARRATION_MODE;
30
+ default:
31
+ return DEFAULT_NARRATION_MODE;
32
+ }
33
+ }
34
+
35
+ /** High-level events: what the user actually cares about seeing in a chat. */
36
+ const MILESTONE_KINDS = new Set<NarrationEventDoc["kind"]>([
37
+ "delegated",
38
+ "worker_started",
39
+ "verified",
40
+ "failed",
41
+ "group_ready",
42
+ ]);
43
+
44
+ const KIND_PREFIX: Record<NarrationEventDoc["kind"], string> = {
45
+ delegated: "📋",
46
+ worker_started: "▶️",
47
+ tool_call: "⚙️",
48
+ tool_result: "⚠️",
49
+ verified: "✅",
50
+ failed: "❌",
51
+ group_ready: "📝",
52
+ };
53
+
54
+ const DETAIL_MAX_CHARS = 200;
55
+
56
+ // ─── Mode lookup (cached) ─────────────────────────────────────────────────────
57
+ // Resolved per channel *type* because narration events only carry the type, not
58
+ // the account id. Short TTL so a settings change takes effect without a restart.
59
+
60
+ const MODE_CACHE_TTL_MS = 30_000;
61
+ const modeCache = new Map<string, { mode: NarrationMode; expiresAt: number }>();
62
+
63
+ export function invalidateNarrationModeCache(channelType?: string): void {
64
+ if (channelType) modeCache.delete(channelType);
65
+ else modeCache.clear();
66
+ }
67
+
68
+ export async function resolveNarrationMode(channelType: string): Promise<NarrationMode> {
69
+ const cached = modeCache.get(channelType);
70
+ if (cached && cached.expiresAt > Date.now()) return cached.mode;
71
+
72
+ let mode = DEFAULT_NARRATION_MODE;
73
+ try {
74
+ const channels = await col<ChannelDoc>("channels");
75
+ const row = (await channels.scan({})).find((e) => e.doc.type === channelType);
76
+ mode = coerceMode(row?.doc.step_delivery_mode);
77
+ } catch (error) {
78
+ log.debug(`Could not resolve narration mode for ${channelType}: ${(error as Error).message}`);
79
+ }
80
+
81
+ modeCache.set(channelType, { mode, expiresAt: Date.now() + MODE_CACHE_TTL_MS });
82
+ return mode;
83
+ }
84
+
85
+ // ─── Filtering ────────────────────────────────────────────────────────────────
86
+
87
+ export function shouldDeliverToChannel(event: NarrationEventDoc, mode: NarrationMode): boolean {
88
+ if (mode === "off") return false;
89
+ if (MILESTONE_KINDS.has(event.kind)) return true;
90
+ if (mode !== "all") return false;
91
+ // Even in `all`, a successful tool_result only restates the tool_call that
92
+ // preceded it. Errors are the part worth surfacing.
93
+ if (event.kind === "tool_result") return event.status === "error";
94
+ return true;
95
+ }
96
+
97
+ // ─── Formatting ───────────────────────────────────────────────────────────────
98
+
99
+ /** Collapses whitespace and trims — raw error details carry stacks and paths. */
100
+ function compactDetail(detail: string): string {
101
+ const flat = detail.replace(/\s+/g, " ").trim();
102
+ if (flat.length <= DETAIL_MAX_CHARS) return flat;
103
+ return `${flat.slice(0, DETAIL_MAX_CHARS - 1)}…`;
104
+ }
105
+
106
+ export function formatNarrationForChannel(event: NarrationEventDoc): string {
107
+ const prefix = KIND_PREFIX[event.kind] ?? "•";
108
+ const detail = event.detail ? compactDetail(event.detail) : "";
109
+ return detail ? `${prefix} ${event.label}\n${detail}` : `${prefix} ${event.label}`;
110
+ }
111
+
112
+ // ─── Ordered, off-critical-path delivery ──────────────────────────────────────
113
+ // `publishNarration` awaits the delivery adapter, so sending inline would put a
114
+ // round-trip to the channel's servers inside the agent loop for every event.
115
+ // Each conversation gets its own promise chain: the agent loop is never blocked,
116
+ // and messages still arrive in the order they were produced.
117
+
118
+ const sendQueues = new Map<string, Promise<void>>();
119
+
120
+ export function enqueueChannelNarration(
121
+ key: string,
122
+ send: () => Promise<void>,
123
+ ): void {
124
+ const previous = sendQueues.get(key) ?? Promise.resolve();
125
+ const next = previous
126
+ .then(send)
127
+ .catch((error: Error) => {
128
+ log.warn(`Narration delivery failed for ${key}: ${error.message}`);
129
+ })
130
+ .finally(() => {
131
+ // Drop the entry once this send is the last one queued, so the map does
132
+ // not grow with one retained promise per conversation seen.
133
+ if (sendQueues.get(key) === next) sendQueues.delete(key);
134
+ });
135
+ sendQueues.set(key, next);
136
+ }
137
+
138
+ /**
139
+ * Resolves once the narration queued for one conversation has been sent. Call
140
+ * before sending a turn's final answer so it cannot overtake pending progress
141
+ * messages, which would show the user the outcome before the steps.
142
+ */
143
+ export async function awaitChannelNarration(key: string): Promise<void> {
144
+ await (sendQueues.get(key) ?? Promise.resolve());
145
+ }
146
+
147
+ /** Test/shutdown helper: resolves once every queued narration has been sent. */
148
+ export async function flushChannelNarration(): Promise<void> {
149
+ await Promise.allSettled([...sendQueues.values()]);
150
+ }
@@ -0,0 +1,82 @@
1
+ import { createHash } from "node:crypto";
2
+ import { col } from "../storage/hive";
3
+ import type { NarrationEventDoc } from "../storage/collections";
4
+ import { logger } from "../utils/logger";
5
+
6
+ const log = logger.child("narration");
7
+
8
+ export type NarrationDelivery = (event: NarrationEventDoc) => Promise<void>;
9
+ const STATE_KEY = Symbol.for("hive.narration.delivery");
10
+ type NarrationState = { delivery: NarrationDelivery | null };
11
+
12
+ function state(): NarrationState {
13
+ const root = globalThis as any;
14
+ root[STATE_KEY] ??= { delivery: null };
15
+ return root[STATE_KEY];
16
+ }
17
+
18
+ export function setNarrationDelivery(next: NarrationDelivery | null): void {
19
+ state().delivery = next;
20
+ log.info(`Delivery adapter ${next ? "registered" : "cleared"}`);
21
+ }
22
+
23
+ function eventId(turnId: string, dedupeKey: string): string {
24
+ return createHash("sha256").update(`${turnId}\0${dedupeKey}`).digest("hex");
25
+ }
26
+
27
+ export async function publishNarration(input: {
28
+ turnId: string;
29
+ threadId: string;
30
+ channel?: string | null;
31
+ userId?: string | null;
32
+ sessionId?: string | null;
33
+ agentId?: string | null;
34
+ agentName?: string | null;
35
+ kind: NarrationEventDoc["kind"];
36
+ status: NarrationEventDoc["status"];
37
+ label: string;
38
+ detail?: string | null;
39
+ dedupeKey: string;
40
+ }): Promise<NarrationEventDoc> {
41
+ const id = eventId(input.turnId, input.dedupeKey);
42
+ const events = await col<NarrationEventDoc>("narrationEvents");
43
+ const existing = await events.get(id);
44
+ if (existing) return existing.doc;
45
+
46
+ const event: NarrationEventDoc = {
47
+ id,
48
+ turn_id: input.turnId,
49
+ thread_id: input.threadId,
50
+ channel: input.channel ?? "",
51
+ user_id: input.userId ?? "",
52
+ session_id: input.sessionId ?? "",
53
+ agent_id: input.agentId ?? "",
54
+ agent_name: input.agentName ?? "",
55
+ kind: input.kind,
56
+ status: input.status,
57
+ label: input.label,
58
+ detail: input.detail ?? null,
59
+ dedupe_key: input.dedupeKey,
60
+ created_at: Date.now(),
61
+ };
62
+
63
+ try {
64
+ await events.put(id, event, { expectedVersion: 0 });
65
+ } catch {
66
+ const raced = await events.get(id);
67
+ if (raced) return raced.doc;
68
+ throw new Error(`Could not persist narration event ${id}`);
69
+ }
70
+ log.info(`Persisted ${event.kind} for turn=${event.turn_id} agent=${event.agent_id || "coordinator"}`);
71
+
72
+ const delivery = state().delivery;
73
+ if (delivery) {
74
+ try {
75
+ await delivery(event);
76
+ log.info(`Delivered ${event.kind} for turn=${event.turn_id} channel=${event.channel || "none"}`);
77
+ } catch (error) {
78
+ log.warn(`Delivery failed for narration ${id}: ${(error as Error).message}`);
79
+ }
80
+ }
81
+ return event;
82
+ }