@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
@@ -19,6 +19,8 @@
19
19
  import { col } from "../storage/hive"
20
20
  import type { SkillDoc } from "../storage/collections"
21
21
  import { logger } from "../utils/logger"
22
+ import { isMinimalSkill } from "./minimal-loadout"
23
+ import { isCalendarOperation } from "./routing-intent"
22
24
  import {
23
25
  searchCapabilities,
24
26
  applyRelativeCutoff,
@@ -28,20 +30,7 @@ import {
28
30
 
29
31
  const log = logger.child("skill-selector")
30
32
 
31
- // ─── Minimal Skill Set ─────────────────────────────────────────────────────────
32
33
 
33
- /**
34
- * Skills mínimas que SIEMPRE están disponibles (asociadas a las 4 tools iniciales)
35
- * - memory_manager: usa save_note (notas persistentes)
36
- * - canvas_report: usa report_progress (reportes de progreso)
37
- * - task_orchestrator: usa notify (comunicación entre agentes)
38
- */
39
- export const MINIMAL_SKILL_NAMES = new Set([
40
- "capability_discovery", // Core: cómo descubrir tools, MCP, skills, playbook
41
- "memory_manager", // Asociada a save_note
42
- "canvas_report", // Asociada a report_progress
43
- "task_orchestrator", // Asociada a notify y agent coordination
44
- ])
45
34
 
46
35
  // ─── Types ───────────────────────────────────────────────────────────────────────
47
36
 
@@ -217,7 +206,10 @@ export async function selectSkills(userMessage: string): Promise<SkillDescriptor
217
206
 
218
207
  // Step 2: Check explicit triggers first (high priority)
219
208
  const skillsCol = await col<SkillDoc>("skills")
220
- const allSkills = (await skillsCol.scan({})).filter(e => e.doc.active).map(e => toSkillDescriptor(e.doc))
209
+ const calendarOperation = isCalendarOperation(userMessage)
210
+ const allSkills = (await skillsCol.scan({}))
211
+ .filter(e => e.doc.active && !(calendarOperation && e.doc.category === "cron"))
212
+ .map(e => toSkillDescriptor(e.doc))
221
213
 
222
214
  // Check trigger match - if found, return immediately with high confidence
223
215
  for (const skill of allSkills) {
@@ -278,16 +270,17 @@ export async function selectSkills(userMessage: string): Promise<SkillDescriptor
278
270
  // ─── Minimal Skills Loader ───────────────────────────────────────────────────
279
271
 
280
272
  /**
281
- * Load minimal skills that are ALWAYS available (associated with MINIMAL_TOOLS)
282
- * These are loaded at startup, not via FTS5 search.
273
+ * Load the skills that ride along with the minimal tool loadout.
283
274
  *
284
- * @returns Array of minimal skills (memory_manager, canvas_report, task_orchestrator)
275
+ * Derived, not listed: a skill qualifies when every tool it documents is in
276
+ * MINIMAL_TOOLS (see minimal-loadout.ts). Any other skill reaches the agent
277
+ * through discovery, which injects it together with the tools it teaches.
285
278
  */
286
279
  export async function getMinimalSkills(): Promise<SkillDescriptor[]> {
287
280
  try {
288
281
  const skillsCol = await col<SkillDoc>("skills")
289
282
  const skills = (await skillsCol.scan({}))
290
- .filter(e => MINIMAL_SKILL_NAMES.has(e.doc.name) && e.doc.active)
283
+ .filter(e => e.doc.active && isMinimalSkill(e.doc.tools))
291
284
  .map(e => toSkillDescriptor(e.doc))
292
285
 
293
286
  log.info(`[skill-selector] Loaded ${skills.length} minimal skills: ${skills.map(s => s.name).join(", ")}`)
@@ -306,7 +299,7 @@ export async function getMinimalSkills(): Promise<SkillDescriptor[]> {
306
299
  * Replaces all `type=skill` documents atomically (delete-by-filter + one
307
300
  * batch commit).
308
301
  */
309
- export async function syncSkillsToFTS(): Promise<void> {
302
+ export async function syncSkillsToIndex(): Promise<void> {
310
303
  try {
311
304
  // Step 1: Get all enabled skills from database
312
305
  const skillsCol = await col<SkillDoc>("skills")
@@ -337,18 +330,6 @@ export async function syncSkillsToFTS(): Promise<void> {
337
330
  throw err // Re-throw to inform initializer
338
331
  }
339
332
  }
340
- // ─── Initialization ───────────────────────────────────────────────────────
341
-
342
- /**
343
- * Initialize the skill selector
344
- * DEPRECATED: syncSkillsToFTS() is now called from gateway/initializer.ts
345
- * This function is kept for backward compatibility but is no longer needed
346
- */
347
- export function initializeSkillSelector(): void {
348
- log.info(`[skill-selector] Initializing skill selector (deprecated - sync is done in gateway/initializer.ts)`)
349
- // syncSkillsToFTS() - No longer needed here, done in gateway/initializer.ts
350
- }
351
-
352
333
  // ─── Debug/Test Helpers ─────────────────────────────────────────────────────
353
334
 
354
335
  /**
@@ -35,7 +35,7 @@
35
35
  * - browser (browser automation)
36
36
  * - memory (notes, memory operations)
37
37
  * - code (exec, terminal)
38
- * - canvas (UI rendering)
38
+ * - a2ui (interactive panel rendering)
39
39
  * - agents (agent creation/management)
40
40
  * - core (notify, report_progress, save_note)
41
41
  */
@@ -49,6 +49,7 @@ import {
49
49
  replaceCapabilityDocs,
50
50
  type CapabilityDoc,
51
51
  } from "./capability-search"
52
+ import { isCalendarOperation } from "./routing-intent"
52
53
 
53
54
  const log = logger.child("tool-selector")
54
55
 
@@ -122,7 +123,7 @@ const CONVERSATIONAL_PATTERNS = [
122
123
 
123
124
  export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
124
125
  // Cron tools (cron.*)
125
- { name: "cron.create", description: "Create new cron job: recurring (cron expression) or one-shot (fire_at). Requires 'task' field with instruction for the agent. Spanish keywords: programar tarea, crear recordatorio, agendar, automatizar horario, tarea recurrente, recordatorio diario, una vez", category: "scheduling", abstractionLevel: "atomic" },
126
+ { name: "cron.create", description: "Create a Hive scheduled automation: recurring (cron expression) or one-shot (fire_at). Requires a task instruction. Spanish keywords: programar tarea, crear automatización, ejecutar después, tarea recurrente, recordatorio automático, una vez", category: "scheduling", abstractionLevel: "atomic" },
126
127
  { name: "cron.list", description: "List all cron jobs with next execution times and status. Spanish keywords: ver tareas programadas, listar cronograma, próximas ejecuciones, tareas activas, recordatorios pendientes", category: "scheduling", abstractionLevel: "atomic" },
127
128
  { name: "cron.update", description: "Update an existing cron job: change expression, task instruction, channel, time window, etc. Use cron.list first to get task_id. Spanish keywords: actualizar tarea, modificar cron, editar recordatorio, cambiar horario, actualizar programación", category: "scheduling", abstractionLevel: "atomic" },
128
129
  { name: "cron.pause", description: "Pause a cron job temporarily without deleting it. Spanish keywords: pausar tarea programada, detener temporalmente, suspender recordatorio", category: "scheduling", abstractionLevel: "atomic" },
@@ -146,8 +147,8 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
146
147
  { name: "memory_delete", description: "Delete memory entry, remove saved memory from long-term storage. Spanish keywords: borrar memoria, eliminar información guardada, borrar dato, eliminar memoria", category: "memory", abstractionLevel: "atomic" },
147
148
 
148
149
  // Agent/worker management
149
- { name: "agent_create", description: "Create specialized worker agent, spawn new agent for specific task execution. Spanish keywords: crear agente, nuevo agente, trabajador, crear worker, nuevo trabajador", category: "agents", abstractionLevel: "orchestration" },
150
- { name: "agent_find", description: "Find existing worker agents, locate running or idle worker agents. Spanish keywords: buscar agente, encontrar trabajador, localizar, buscar worker, encontrar agente", category: "agents", abstractionLevel: "atomic" },
150
+ { name: "agent_create", description: "Create a specialized worker, including one persistent MCP server after user confirmation. Spanish keywords: crear agente, nuevo agente, trabajador, crear worker, especialista MCP", category: "agents", abstractionLevel: "orchestration" },
151
+ { name: "agent_find", description: "Discover available system catalog agents and user-owned workers. Not an execution monitor. Spanish keywords: buscar agente, encontrar trabajador, localizar, buscar worker, encontrar agente", category: "agents", abstractionLevel: "atomic" },
151
152
  { name: "agent_archive", description: "Archive unnecessary worker, terminate and archive idle or completed agents. Spanish keywords: archivar agente, terminar agente, borrar trabajador, desactivar agente", category: "agents", abstractionLevel: "atomic" },
152
153
 
153
154
  // Notes/persistence
@@ -166,24 +167,11 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
166
167
  { name: "browser_script", description: "Execute arbitrary JavaScript in the browser page context and get the result. Spanish keywords: ejecutar javascript, script, código, función, evaluar, js en página", category: "browser", abstractionLevel: "atomic" },
167
168
  { name: "browser_wait", description: "Wait for an element to appear or condition to be met on the page. Spanish keywords: esperar, wait, condición, elemento, selector, aguardar carga", category: "browser", abstractionLevel: "atomic" },
168
169
 
169
- // Canvas/UI rendering tools
170
- { name: "canvas_render", description: "Render component on canvas, display UI components and data visualizations. Spanish keywords: renderizar, mostrar en canvas, visualizar, mostrar componente, dibujar", category: "canvas", abstractionLevel: "atomic" },
171
- { name: "canvas_ask", description: "Display form and wait for response, show interactive form and collect user input. Spanish keywords: mostrar formulario, pedir datos, solicitar información, formulario interactivo", category: "canvas", abstractionLevel: "atomic" },
172
- { name: "canvas_clear", description: "Clear canvas for session, reset canvas display and start fresh. Spanish keywords: limpiar canvas, borrar pantalla, reiniciar, limpiar, borrar", category: "canvas", abstractionLevel: "atomic" },
173
- { name: "canvas_show_card", description: "Display card with labeled items, show structured data in card format. Spanish keywords: mostrar tarjeta, visualizar datos, tarjeta de información, mostrar datos", category: "canvas", abstractionLevel: "atomic" },
174
- { name: "canvas_show_progress", description: "Display progress bars, show progress indicators and completion status. Spanish keywords: mostrar progreso, barra de progreso, indicador de progreso, avance", category: "canvas", abstractionLevel: "atomic" },
175
- { name: "canvas_show_list", description: "Display key-value list, show information in structured list format. Spanish keywords: mostrar lista, listar elementos, lista de valores, mostrar elementos", category: "canvas", abstractionLevel: "atomic" },
176
- { name: "canvas_confirm", description: "Show confirmation dialog, request user confirmation for actions. Spanish keywords: confirmar, diálogo de confirmación, confirmar acción, validación", category: "canvas", abstractionLevel: "atomic" },
177
-
178
170
  // A2UI v0.9 rich interactive surfaces
179
171
  { name: "a2ui_create_surface", description: "Create A2UI v0.9 surface for rich interactive UIs with forms, dashboards, and workflows. Spanish keywords: crear superficie A2UI, iniciar UI interactiva, crear formulario rico, interfaz A2UI, crear surface", category: "a2ui", abstractionLevel: "orchestration" },
180
172
  { name: "a2ui_update_components", description: "Send A2UI v0.9 components to an existing surface (Text, Button, TextField, Row, Column, Card, etc.). Spanish keywords: enviar componentes A2UI, actualizar UI, renderizar componentes, A2UI componentes, update components", category: "a2ui", abstractionLevel: "atomic" },
181
173
  { name: "a2ui_update_data_model", description: "Update A2UI v0.9 surface data model with JSON Pointer for dynamic data binding. Spanish keywords: actualizar datos A2UI, poblar formulario, cambiar valores, data model A2UI, actualizar modelo de datos", category: "a2ui", abstractionLevel: "atomic" },
182
- { name: "a2ui_delete_surface", description: "Delete A2UI v0.9 surface and remove it from the user's canvas. Spanish keywords: eliminar superficie A2UI, borrar UI, limpiar superficie A2UI, cerrar formulario, delete surface", category: "a2ui", abstractionLevel: "atomic" },
183
-
184
- // Voice tools
185
- { name: "voice_transcribe", description: "Transcribe audio to text, convert speech to written text from audio files. Spanish keywords: transcribir audio, voz a texto, convertir audio, transcripción", category: "voice", abstractionLevel: "atomic" },
186
- { name: "voice_speak", description: "Convert text to audio and play, synthesize speech from text. Spanish keywords: hablar, sintetizar voz, texto a voz, reproducir audio, voz", category: "voice", abstractionLevel: "atomic" },
174
+ { name: "a2ui_delete_surface", description: "Delete A2UI v0.9 surface from the user's interactive panel. Spanish keywords: eliminar superficie A2UI, borrar UI, limpiar superficie A2UI, cerrar formulario, delete surface", category: "a2ui", abstractionLevel: "atomic" },
187
175
 
188
176
  // Filesystem tools
189
177
  { name: "fs_read", description: "Read file content from workspace. Spanish keywords: leer archivo, ver contenido, abrir archivo, leer fichero, mostrar archivo", category: "filesystem", abstractionLevel: "atomic" },
@@ -196,10 +184,35 @@ export const CORE_TOOL_CATALOG: ToolDescriptor[] = [
196
184
 
197
185
  // Agent delegation and communication
198
186
  { name: "task_delegate", description: "Delegate general task to worker agent. Spanish keywords: delegar tarea, asignar worker, ejecutar por agente, encomendar tarea", category: "agents", abstractionLevel: "orchestration" },
199
- { name: "task_delegate_code", description: "Delegate coding task to CLI subagent (Qwen, Claude Code, Gemini CLI). Spanish keywords: delegar código, subagente CLI, programación, codificar", category: "agents", abstractionLevel: "orchestration" },
187
+ { name: "task_revise", description: "Send a delegated task back to its worker with feedback when it does not meet its acceptance criteria. Spanish keywords: corregir tarea, devolver al worker, pedir correccion, reencolar tarea", category: "agents", abstractionLevel: "orchestration" },
188
+ { name: "task_list", description: "List real delegated task executions for the current user from persisted tasks and jobs. Spanish keywords: listar tareas activas, subagentes trabajando, ejecuciones reales", category: "agents", abstractionLevel: "atomic" },
200
189
  { name: "task_status", description: "Get execution status of delegated tasks. Spanish keywords: estado tarea delegada, verificar progreso, consultar tarea, progreso delegado", category: "agents", abstractionLevel: "atomic" },
201
190
  { name: "bus_publish", description: "Publish message to Agent Bus for worker-to-worker communication. Spanish keywords: publicar mensaje, comunicar workers, enviar bus, mensaje bus", category: "agents", abstractionLevel: "atomic" },
202
191
  { name: "bus_read", description: "Read unread messages from Agent Bus. Spanish keywords: leer mensajes bus, recibir mensajes, verificar bus, mensajes workers", category: "agents", abstractionLevel: "atomic" },
192
+
193
+ // Model discovery
194
+ { name: "get_available_models", description: "List configured providers and models with their capabilities and context windows. Spanish keywords: modelos disponibles, proveedores activos, qué modelos hay, listar modelos", category: "agents", abstractionLevel: "atomic" },
195
+
196
+ // Capability discovery
197
+ { 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" },
198
+
199
+ // HTTP / REST
200
+ { 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" },
201
+
202
+ // Artifacts
203
+ { name: "artifact_inspect", description: "Inspect a managed artifact's integrity and metadata without modifying it. Spanish keywords: inspeccionar artefacto, verificar archivo generado, metadatos artefacto, comprobar entrega", category: "web", abstractionLevel: "atomic" },
204
+
205
+ // Office documents — read
206
+ { name: "office_leer_pdf", description: "Read and extract text from a PDF document. Spanish keywords: leer pdf, extraer texto pdf, abrir pdf, contenido pdf", category: "office", abstractionLevel: "atomic" },
207
+ { name: "office_leer_docx", description: "Read and extract text from a Word document. Spanish keywords: leer word, leer docx, abrir documento word, contenido word", category: "office", abstractionLevel: "atomic" },
208
+ { name: "office_leer_xlsx", description: "Read rows and sheets from an Excel spreadsheet. Spanish keywords: leer excel, leer xlsx, abrir hoja de cálculo, contenido excel, leer planilla", category: "office", abstractionLevel: "atomic" },
209
+ { name: "office_leer_pptx", description: "Read slides and text from a PowerPoint presentation. Spanish keywords: leer powerpoint, leer pptx, abrir presentación, contenido diapositivas", category: "office", abstractionLevel: "atomic" },
210
+
211
+ // Office documents — write
212
+ { name: "office_escribir_pdf", description: "Generate a PDF document. Spanish keywords: crear pdf, generar pdf, escribir pdf, exportar a pdf", category: "office", abstractionLevel: "atomic" },
213
+ { name: "office_escribir_docx", description: "Generate a Word document. Spanish keywords: crear word, generar docx, escribir documento word, exportar a word", category: "office", abstractionLevel: "atomic" },
214
+ { name: "office_escribir_xlsx", description: "Generate an Excel spreadsheet. Spanish keywords: crear excel, generar xlsx, escribir hoja de cálculo, exportar a excel, armar planilla", category: "office", abstractionLevel: "atomic" },
215
+ { name: "office_escribir_pptx", description: "Generate a PowerPoint presentation. Spanish keywords: crear powerpoint, generar pptx, escribir presentación, armar diapositivas", category: "office", abstractionLevel: "atomic" },
203
216
  ]
204
217
 
205
218
  // ─── Helper Functions ───────────────────────────────────────────────────────-
@@ -308,13 +321,37 @@ export async function selectTools(
308
321
  return []
309
322
  }
310
323
 
311
- // Step 4: Map to tool descriptors with additional metadata
324
+ // Step 4: Map to tool descriptors with additional metadata.
325
+ //
326
+ // El mapa tiene que cubrir lo mismo que se indexó, o el hit se descarta en
327
+ // silencio. `syncToolCatalogToIndex` indexa CORE_TOOL_CATALOG **más** las
328
+ // filas de la colección `tools`; resolver sólo contra `fullToolList` (que
329
+ // por defecto es CORE_TOOL_CATALOG) hace que una tool registrada en runtime
330
+ // puntúe primera en BM25 y aun así nunca se le ofrezca al modelo. Acá no se
331
+ // nota porque todas las tools de hive están en el catálogo estático, pero
332
+ // cualquier tool que llegue sólo por la colección cae en el mismo pozo.
312
333
  const toolMap = new Map(fullToolList.map(t => [t.name, t]))
334
+ const unresolved = relevantHits.filter(h => !toolMap.has(h.rawId))
335
+ if (unresolved.length > 0) {
336
+ const toolsCol = await col<ToolDoc>("tools")
337
+ for (const hit of unresolved) {
338
+ const entry = await toolsCol.get(hit.rawId)
339
+ if (!entry?.doc.enabled || !entry.doc.active) continue
340
+ toolMap.set(entry.doc.name, {
341
+ name: entry.doc.name,
342
+ description: entry.doc.description ?? entry.doc.name,
343
+ category: (entry.doc.category ?? "core") as any,
344
+ abstractionLevel: "atomic",
345
+ })
346
+ }
347
+ }
348
+
349
+ const calendarOperation = isCalendarOperation(userMessage)
313
350
 
314
351
  const scoredTools: SelectedTool[] = []
315
352
  for (const hit of relevantHits) {
316
353
  const tool = toolMap.get(hit.rawId)
317
- if (tool) {
354
+ if (tool && !(calendarOperation && tool.category === "scheduling")) {
318
355
  scoredTools.push({
319
356
  name: tool.name,
320
357
  score: hit.score,
@@ -376,7 +413,7 @@ export async function selectTools(
376
413
  *
377
414
  * @param tools - Optional array of tools to sync. If not provided, fetches from DB.
378
415
  */
379
- export async function syncToolCatalogToFTS(tools?: ToolDescriptor[]): Promise<void> {
416
+ export async function syncToolCatalogToIndex(tools?: ToolDescriptor[]): Promise<void> {
380
417
  try {
381
418
  // Step 1: Build full catalog = CORE_TOOL_CATALOG + any tools in DB not already covered
382
419
  // CORE_TOOL_CATALOG has bilingual keywords; DB tools may be dynamically registered
@@ -451,10 +488,9 @@ function enrichToolDescription(tool: ToolDescriptor): string {
451
488
  browser: "navegador browser click screenshot form automation web page UI",
452
489
  memory: "recordar nota guardar memory store remember persist knowledge",
453
490
  code: "code ejecutar run script bash shell terminal command devops",
454
- canvas: "canvas diagram visualization graph node edge flow chart",
455
- agents: "agente worker specialist create delegate hire team manager",
491
+ a2ui: "A2UI interactive panel interface form dashboard visualization",
492
+ agents: "agente worker catalog create delegate hire team manager",
456
493
  core: "notificar message alert notify communicate progress status",
457
- voice: "voz audio transcribir speech speak sintetizar audio voice transcription",
458
494
  }
459
495
 
460
496
  const extra = keywordsByCategory[tool.category] ?? ""
@@ -493,17 +529,6 @@ export function mcpToolFullName(serverName: string, toolName: string): string {
493
529
  return /^[a-zA-Z_]/.test(full) ? full : `_${full}`.substring(0, MAX)
494
530
  }
495
531
 
496
- /**
497
- * Initialize the tool selector
498
- *
499
- * DEPRECATED: syncToolCatalogToFTS() is now called from gateway/initializer.ts
500
- * This function is kept for backward compatibility but is no longer needed
501
- */
502
- export function initializeToolSelector(): void {
503
- log.info(`[tool-selector] Initializing (deprecated - sync is done in gateway/initializer.ts)`)
504
- // syncToolCatalogToFTS() - No longer needed here, done in gateway/initializer.ts
505
- }
506
-
507
532
  // ─── Debug/Test Helpers ─────────────────────────────────────────────────────
508
533
 
509
534
  /**
@@ -25,6 +25,7 @@ export interface TraceInput {
25
25
  tokensUsed?: number
26
26
  /** G9 causal stream id for this run, when the causal log is enabled. */
27
27
  causalStreamId?: string | null
28
+ catalogAgentId?: string | null
28
29
  }
29
30
 
30
31
  /**
@@ -38,6 +39,9 @@ export function saveTrace(trace: TraceInput): void {
38
39
  const tracesCol = await col<TraceDoc>("traces")
39
40
  const id = await nextId("traces")
40
41
  const now = Date.now()
42
+ const agentsCol = await col<AgentDoc>("agents")
43
+ const agentEntry = await agentsCol.get(trace.agentId)
44
+ const catalogAgentId = trace.catalogAgentId ?? (agentEntry?.doc.source === "catalog" ? agentEntry.doc.id : null)
41
45
  await tracesCol.put(id, {
42
46
  id,
43
47
  thread_id: trace.threadId,
@@ -52,12 +56,12 @@ export function saveTrace(trace: TraceInput): void {
52
56
  tokens_used: trace.tokensUsed ?? null,
53
57
  created_at: now,
54
58
  causal_stream_id: trace.causalStreamId ?? null,
59
+ catalog_agent_id: catalogAgentId ?? undefined,
55
60
  })
56
61
 
57
62
  // Denormalized field the Curator scans for stale-worker detection,
58
63
  // avoiding a correlated MAX(created_at) query HiveDB has no primitive for.
59
64
  await updateDoc<AgentDoc>("agents", trace.agentId, { lastTraceAt: now }).catch(() => { /* agent may not exist */ })
60
-
61
65
  // Trigger reflector check in background
62
66
  checkReflectorTrigger().catch(() => { /* ignore */ })
63
67
  } catch (err) {
@@ -0,0 +1,162 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import {
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ statSync,
7
+ unlinkSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { extname, join } from "node:path";
11
+ import { getHiveDir } from "../config/loader";
12
+ import { col, updateDoc } from "../storage/hive";
13
+ import type { ArtifactDoc } from "../storage/collections";
14
+
15
+ const ARTIFACT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
16
+
17
+ function extensionFor(mimeType: string): string {
18
+ if (mimeType === "image/png") return "png";
19
+ if (mimeType === "image/jpeg") return "jpg";
20
+ if (mimeType === "image/webp") return "webp";
21
+ return "bin";
22
+ }
23
+
24
+ function hash(bytes: Uint8Array): string {
25
+ return createHash("sha256").update(bytes).digest("hex");
26
+ }
27
+
28
+ function detectedMime(bytes: Uint8Array, fallback: string): string {
29
+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) {
30
+ return "image/png";
31
+ }
32
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
33
+ return "image/jpeg";
34
+ }
35
+ if (
36
+ bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
37
+ bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50
38
+ ) {
39
+ return "image/webp";
40
+ }
41
+ return fallback;
42
+ }
43
+
44
+ export async function createArtifact(input: {
45
+ bytes: Uint8Array;
46
+ mimeType: string;
47
+ kind: string;
48
+ userId: string;
49
+ runId?: string | null;
50
+ taskId?: string | null;
51
+ rootDir?: string;
52
+ width?: number | null;
53
+ height?: number | null;
54
+ now?: number;
55
+ }): Promise<ArtifactDoc> {
56
+ const now = input.now ?? Date.now();
57
+ const id = randomUUID();
58
+ const root = input.rootDir ?? getHiveDir();
59
+ const mimeType = detectedMime(input.bytes, input.mimeType);
60
+ const day = new Date(now).toISOString().slice(0, 10);
61
+ const dir = join(root, "artifacts", day);
62
+ mkdirSync(dir, { recursive: true });
63
+ const path = join(dir, `${id}.${extensionFor(mimeType)}`);
64
+ writeFileSync(path, input.bytes, { flag: "wx" });
65
+
66
+ const doc: ArtifactDoc = {
67
+ id,
68
+ run_id: input.runId ?? null,
69
+ task_id: input.taskId ?? null,
70
+ user_id: input.userId,
71
+ kind: input.kind,
72
+ path,
73
+ mime_type: mimeType,
74
+ size: input.bytes.byteLength,
75
+ sha256: hash(input.bytes),
76
+ width: input.width ?? null,
77
+ height: input.height ?? null,
78
+ status: "active",
79
+ created_at: now,
80
+ expires_at: now + ARTIFACT_RETENTION_MS,
81
+ expired_at: null,
82
+ };
83
+
84
+ try {
85
+ const artifacts = await col<ArtifactDoc>("artifacts");
86
+ await artifacts.put(id, doc, { expectedVersion: 0 });
87
+ return doc;
88
+ } catch (error) {
89
+ try { unlinkSync(path); } catch { /* best effort rollback */ }
90
+ throw error;
91
+ }
92
+ }
93
+
94
+ export async function inspectArtifact(
95
+ artifactId: string,
96
+ options: { userId?: string } = {},
97
+ ): Promise<Record<string, unknown>> {
98
+ const artifacts = await col<ArtifactDoc>("artifacts");
99
+ const entry = await artifacts.get(artifactId);
100
+ if (!entry) return { ok: false, artifact_id: artifactId, error: "Artifact not found" };
101
+ const artifact = entry.doc;
102
+ if (options.userId && artifact.user_id && artifact.user_id !== options.userId) {
103
+ return { ok: false, artifact_id: artifactId, error: "Artifact not accessible" };
104
+ }
105
+ if (artifact.status !== "active") {
106
+ return {
107
+ ok: false,
108
+ artifact_id: artifactId,
109
+ status: artifact.status,
110
+ expired_at: artifact.expired_at,
111
+ error: "Artifact binary has expired",
112
+ };
113
+ }
114
+ if (!existsSync(artifact.path)) {
115
+ return {
116
+ ok: false,
117
+ artifact_id: artifactId,
118
+ status: "missing",
119
+ error: "Artifact binary is missing",
120
+ };
121
+ }
122
+
123
+ const bytes = readFileSync(artifact.path);
124
+ const actualHash = hash(bytes);
125
+ const stat = statSync(artifact.path);
126
+ return {
127
+ ok: actualHash === artifact.sha256 && stat.size === artifact.size,
128
+ artifact_id: artifact.id,
129
+ kind: artifact.kind,
130
+ mime_type: detectedMime(bytes, artifact.mime_type),
131
+ extension: extname(artifact.path),
132
+ size: stat.size,
133
+ expected_size: artifact.size,
134
+ sha256: actualHash,
135
+ sha256_matches: actualHash === artifact.sha256,
136
+ width: artifact.width,
137
+ height: artifact.height,
138
+ created_at: artifact.created_at,
139
+ expires_at: artifact.expires_at,
140
+ status: artifact.status,
141
+ };
142
+ }
143
+
144
+ export async function expireArtifacts(now = Date.now()): Promise<{ expired: number }> {
145
+ const artifacts = await col<ArtifactDoc>("artifacts");
146
+ const rows = await artifacts.scan({});
147
+ let expired = 0;
148
+ for (const row of rows) {
149
+ if (row.doc.status !== "active" || row.doc.expires_at > now) continue;
150
+ try {
151
+ if (existsSync(row.doc.path)) unlinkSync(row.doc.path);
152
+ } catch {
153
+ continue;
154
+ }
155
+ await updateDoc<ArtifactDoc>("artifacts", row.id, {
156
+ status: "expired",
157
+ expired_at: now,
158
+ });
159
+ expired++;
160
+ }
161
+ return { expired };
162
+ }