@johpaz/hive-agents 0.0.47 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +119 -902
  3. package/dist/hive.js +68840 -68355
  4. package/dist/tool-worker.js +220 -925
  5. package/dist/ui/assets/A2UIPage-D4nUFe5q.js +8 -0
  6. package/dist/ui/assets/AgentCreateForm-g1mQnIoJ.js +1 -0
  7. package/dist/ui/assets/AgentDetailPage-C3XkU4Ll.js +1 -0
  8. package/dist/ui/assets/AgentNewPage-CEkLeA79.js +1 -0
  9. package/dist/ui/assets/AgentsPage-CNA778Eo.js +10 -0
  10. package/dist/ui/assets/ApiClientPage-t5DpKhmA.js +3 -0
  11. package/dist/ui/assets/ChannelsPage-yY6t0YTU.js +8 -0
  12. package/dist/ui/assets/DashboardPage-BSeNSYg5.js +6 -0
  13. package/dist/ui/assets/{LoginPage-BTxJdFVG.js → LoginPage-eT5zDRDa.js} +1 -1
  14. package/dist/ui/assets/{LogsPage-DVV2eHbh.js → LogsPage-Gczzzsdh.js} +1 -1
  15. package/dist/ui/assets/MeetingPage-Bu4aMMNR.js +1 -0
  16. package/dist/ui/assets/ModelSelector-nNOrW3te.js +1 -0
  17. package/dist/ui/assets/{NotFound-BIUDlIXU.js → NotFound-Bpr12V51.js} +1 -1
  18. package/dist/ui/assets/Office3DPage-B_iXEbyv.js +4614 -0
  19. package/dist/ui/assets/Office3DPage-C3SIzd2H.css +1 -0
  20. package/dist/ui/assets/ProvidersPage-BupHs5yO.js +1 -0
  21. package/dist/ui/assets/{RecoverPage-7YDQysBL.js → RecoverPage-DMqSasKk.js} +1 -1
  22. package/dist/ui/assets/SettingsPage-B6FTSkOn.js +9 -0
  23. package/dist/ui/assets/SetupPage-DhcRbGgg.js +1 -0
  24. package/dist/ui/assets/WebChatPage-CWXjW4Hn.js +29 -0
  25. package/dist/ui/assets/{activity-c3pNngT_.js → activity-CQuPevhB.js} +1 -1
  26. package/dist/ui/assets/agentCapabilities-CDC6y91E.js +1 -0
  27. package/dist/ui/assets/alert-CQlRq6sv.js +1 -0
  28. package/dist/ui/assets/arrow-left-0EBE7nsF.js +1 -0
  29. package/dist/ui/assets/arrow-right-5QIaph-z.js +1 -0
  30. package/dist/ui/assets/arrow-up-right-DQQCY007.js +1 -0
  31. package/dist/ui/assets/badge-DKGZbVZJ.js +1 -0
  32. package/dist/ui/assets/{calendar-B-KZ9RQO.js → calendar-Be23hQGc.js} +1 -1
  33. package/dist/ui/assets/{card-CNf6BS2e.js → card-D3Nw3kh3.js} +1 -1
  34. package/dist/ui/assets/check-Dp6tzwax.js +1 -0
  35. package/dist/ui/assets/chevron-down-33N886NY.js +1 -0
  36. package/dist/ui/assets/chevron-left-C6itJXh3.js +1 -0
  37. package/dist/ui/assets/chevron-right-CFodBS-b.js +1 -0
  38. package/dist/ui/assets/chevron-up-BvSmyBEs.js +1 -0
  39. package/dist/ui/assets/{circle-alert-KuAm2FWh.js → circle-alert-BDVHxmAz.js} +1 -1
  40. package/dist/ui/assets/circle-check-BJWNbLuF.js +1 -0
  41. package/dist/ui/assets/{circle-x-DjLkFDO8.js → circle-x-Cb2Yer4s.js} +1 -1
  42. package/dist/ui/assets/{copy-Bu5d7C-0.js → copy-33tZrzc9.js} +1 -1
  43. package/dist/ui/assets/{dialog-Jk4bieO4.js → dialog-KOZKWbib.js} +1 -1
  44. package/dist/ui/assets/dist-CD_qfA30.js +1 -0
  45. package/dist/ui/assets/{download-Cjbk4Rek.js → download-CiQqqXyz.js} +1 -1
  46. package/dist/ui/assets/earth-DCvN7ynm.js +1 -0
  47. package/dist/ui/assets/ellipsis-vertical-BybFZDk2.js +1 -0
  48. package/dist/ui/assets/{external-link-6sTlRDUR.js → external-link-0iNNBvZm.js} +1 -1
  49. package/dist/ui/assets/{eye-Df8o0tkC.js → eye-C8sKSSkg.js} +1 -1
  50. package/dist/ui/assets/{file-text-lnxnjBp0.js → file-text-DO8jqiJK.js} +1 -1
  51. package/dist/ui/assets/{gateway-url-DwzPmoc8.js → gateway-url-BlnabM5e.js} +1 -1
  52. package/dist/ui/assets/gauge-BRGwuN8G.js +1 -0
  53. package/dist/ui/assets/{history-CAF_R34_.js → history-BtTD1kDo.js} +1 -1
  54. package/dist/ui/assets/index-Bejlp-R1.js +116 -0
  55. package/dist/ui/assets/index-XoTT41Hr.css +2 -0
  56. package/dist/ui/assets/{info-WjromB4Y.js → info-mpk1tsNC.js} +1 -1
  57. package/dist/ui/assets/key-CoQ0qtXt.js +1 -0
  58. package/dist/ui/assets/label-k0jYxoWW.js +1 -0
  59. package/dist/ui/assets/loader-circle-BhqRN2nO.js +1 -0
  60. package/dist/ui/assets/lock-open-Cd2aqwOd.js +1 -0
  61. package/dist/ui/assets/mail-BG0RYSkL.js +1 -0
  62. package/dist/ui/assets/{pause-VqeUmp2Z.js → pause-Cme88_9s.js} +1 -1
  63. package/dist/ui/assets/pencil-f1nJ1xhs.js +1 -0
  64. package/dist/ui/assets/play-CfYDHD6h.js +1 -0
  65. package/dist/ui/assets/plus-C5BxJeOX.js +1 -0
  66. package/dist/ui/assets/progress-DrI2UDu-.js +1 -0
  67. package/dist/ui/assets/radio-B5SpKJ-J.js +1 -0
  68. package/dist/ui/assets/{refresh-cw-CCzDCAuz.js → refresh-cw-CroGQY62.js} +1 -1
  69. package/dist/ui/assets/scroll-area-CfHn94Vb.js +1 -0
  70. package/dist/ui/assets/search-rfBcmohK.js +1 -0
  71. package/dist/ui/assets/select-BhbW0stK.js +1 -0
  72. package/dist/ui/assets/{send-BPk9XbIq.js → send-D6whYpw-.js} +1 -1
  73. package/dist/ui/assets/{settings-BGfrZ_zM.js → settings-BX6q3MGB.js} +1 -1
  74. package/dist/ui/assets/{shield-CxhcUT39.js → shield-BnGyu1xf.js} +1 -1
  75. package/dist/ui/assets/slider-CmE_z1Ii.js +1 -0
  76. package/dist/ui/assets/{sparkles-BhwlS1pc.js → sparkles-BcaOs_Jk.js} +1 -1
  77. package/dist/ui/assets/{square-DMNWw4Hi.js → square-ju5H8nrT.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-Bjfu-TkS.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-DjQXac_0.js} +1 -1
  83. package/dist/ui/assets/{triangle-alert-pVIJGjga.js → triangle-alert-B04mgMcg.js} +1 -1
  84. package/dist/ui/assets/{useHiveAgentsModelLoad-BnC4jLE-.js → useHiveAgentsModelLoad-DT5-4CCj.js} +1 -1
  85. package/dist/ui/assets/useOfficeModel-Cy7cAyEn.js +1 -0
  86. package/dist/ui/assets/useProviders-DSX7eVsz.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-qnVxkRSM.js +1 -0
  94. package/dist/ui/assets/wifi-BA1m2dGO.js +1 -0
  95. package/dist/ui/assets/{zap-B4RaNNO5.js → zap-DT7cM7YS.js} +1 -1
  96. package/dist/ui/index.html +10 -9
  97. package/package.json +8 -9
  98. package/packages/cli/src/adapters/config.ts +1 -80
  99. package/packages/cli/src/adapters/factory.ts +0 -45
  100. package/packages/cli/src/adapters/index.ts +0 -8
  101. package/packages/cli/src/commands/doctor.ts +45 -1
  102. package/packages/cli/src/commands/gateway.ts +2 -9
  103. package/packages/cli/src/index.ts +9 -11
  104. package/packages/core/src/agent/acceptance-verifier.ts +300 -0
  105. package/packages/core/src/agent/agent-catalog.ts +384 -0
  106. package/packages/core/src/agent/agent-loop.ts +185 -28
  107. package/packages/core/src/agent/capability-search.ts +5 -5
  108. package/packages/core/src/agent/catalog-selector.ts +104 -0
  109. package/packages/core/src/agent/compaction.ts +36 -41
  110. package/packages/core/src/agent/context-compiler.ts +182 -62
  111. package/packages/core/src/agent/conversation-store.ts +56 -3
  112. package/packages/core/src/agent/curator.ts +129 -34
  113. package/packages/core/src/agent/delegation-runtime.ts +248 -0
  114. package/packages/core/src/agent/index.ts +17 -0
  115. package/packages/core/src/agent/llm-providers/hiveagents.ts +1 -1
  116. package/packages/core/src/agent/llm-providers/interface.ts +3 -3
  117. package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
  118. package/packages/core/src/agent/minimal-loadout.ts +46 -0
  119. package/packages/core/src/agent/playbook-selector.ts +1 -1
  120. package/packages/core/src/agent/prompt-builder.ts +4 -0
  121. package/packages/core/src/agent/proof-packet.ts +15 -1
  122. package/packages/core/src/agent/providers/index.ts +8 -3
  123. package/packages/core/src/agent/routing-intent.ts +22 -0
  124. package/packages/core/src/agent/run-store.ts +24 -3
  125. package/packages/core/src/agent/service.ts +2 -2
  126. package/packages/core/src/agent/skill-selector.ts +12 -31
  127. package/packages/core/src/agent/tool-selector.ts +36 -35
  128. package/packages/core/src/agent/tracer.ts +5 -1
  129. package/packages/core/src/artifacts/store.ts +162 -0
  130. package/packages/core/src/canvas/canvas-manager.ts +5 -234
  131. package/packages/core/src/canvas/emitter.ts +165 -69
  132. package/packages/core/src/canvas/index.ts +0 -2
  133. package/packages/core/src/channels/base.ts +3 -1
  134. package/packages/core/src/channels/webchat.ts +4 -8
  135. package/packages/core/src/config/loader.ts +0 -22
  136. package/packages/core/src/events/agent-bus.ts +0 -31
  137. package/packages/core/src/events/narration.ts +82 -0
  138. package/packages/core/src/gateway/channel-notify.ts +34 -5
  139. package/packages/core/src/gateway/delegation-groups.ts +245 -0
  140. package/packages/core/src/gateway/delegation-notify.ts +103 -0
  141. package/packages/core/src/gateway/durable-queue.ts +33 -2
  142. package/packages/core/src/gateway/helpers/index.ts +2 -2
  143. package/packages/core/src/gateway/helpers/narration.ts +12 -7
  144. package/packages/core/src/gateway/helpers/redact.ts +1 -1
  145. package/packages/core/src/gateway/initializer.ts +15 -13
  146. package/packages/core/src/gateway/job-executors.ts +232 -101
  147. package/packages/core/src/gateway/lane-queue.ts +1 -1
  148. package/packages/core/src/gateway/notification-inbox.ts +57 -0
  149. package/packages/core/src/gateway/resolver.ts +1 -23
  150. package/packages/core/src/gateway/routes/agents.ts +91 -1
  151. package/packages/core/src/gateway/routes/auth.ts +21 -42
  152. package/packages/core/src/gateway/routes/chat.ts +6 -6
  153. package/packages/core/src/gateway/routes/cron-api.ts +0 -4
  154. package/packages/core/src/gateway/routes/mcp.ts +0 -63
  155. package/packages/core/src/gateway/routes/meeting.ts +245 -0
  156. package/packages/core/src/gateway/routes/providers.ts +1 -0
  157. package/packages/core/src/gateway/routes/setup.ts +29 -24
  158. package/packages/core/src/gateway/routes/skills.ts +2 -2
  159. package/packages/core/src/gateway/routes/system.ts +23 -5
  160. package/packages/core/src/gateway/routes/users.ts +24 -1
  161. package/packages/core/src/gateway/server.ts +153 -117
  162. package/packages/core/src/gateway/session.ts +6 -4
  163. package/packages/core/src/gateway/slash-commands.ts +7 -6
  164. package/packages/core/src/gateway/webchat-turn.ts +34 -8
  165. package/packages/core/src/index.ts +3 -0
  166. package/packages/core/src/mcp/hot-reload.ts +14 -7
  167. package/packages/core/src/mcp/singleton.ts +0 -3
  168. package/packages/core/src/mcp/tool-sync.ts +2 -2
  169. package/packages/core/src/resilience/retry.ts +1 -1
  170. package/packages/core/src/scheduler/CronScheduler.ts +3 -1
  171. package/packages/core/src/scheduler/integration.ts +1 -1
  172. package/packages/core/src/storage/bootstrap.ts +25 -5
  173. package/packages/core/src/storage/collections.ts +201 -27
  174. package/packages/core/src/storage/onboarding.ts +147 -32
  175. package/packages/core/src/storage/reconcile.ts +2 -5
  176. package/packages/core/src/storage/seed.ts +196 -34
  177. package/packages/core/src/storage/usage.ts +0 -9
  178. package/packages/core/src/storage/user-email.ts +11 -0
  179. package/packages/core/src/tool-runtime/index.ts +69 -23
  180. package/packages/core/src/tool-runtime/worker-tools.ts +4 -2
  181. package/packages/core/src/{canvas/a2ui-tools.ts → tools/a2ui/index.ts} +17 -8
  182. package/packages/core/src/tools/agents/index.ts +392 -83
  183. package/packages/core/src/tools/core/index.ts +28 -10
  184. package/packages/core/src/tools/cron/index.ts +1 -6
  185. package/packages/core/src/tools/index.ts +17 -45
  186. package/packages/core/src/tools/types.ts +1 -1
  187. package/packages/core/src/tools/web/artifact-inspect.ts +23 -0
  188. package/packages/core/src/tools/web/browser-screenshot.ts +26 -5
  189. package/packages/core/src/tools/web/index.ts +3 -0
  190. package/packages/core/src/utils/logger.ts +58 -30
  191. package/packages/core/src/utils/toon.ts +0 -20
  192. package/packages/mcp/src/manager.ts +8 -7
  193. package/packages/mcp/src/transports/sse.ts +0 -4
  194. package/packages/mcp/src/transports/websocket.ts +0 -6
  195. package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_dashboard/SKILL.md +4 -4
  196. package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_form/SKILL.md +4 -4
  197. package/packages/skills/src/bundled/{canvas → a2ui}/a2ui_interactive/SKILL.md +5 -5
  198. package/packages/skills/src/bundled/agents/acceptance_verification/SKILL.md +26 -0
  199. package/packages/skills/src/bundled/agents/agent_spawner/SKILL.md +24 -18
  200. package/packages/skills/src/bundled/agents/task_orchestrator/SKILL.md +47 -148
  201. package/packages/skills/src/bundled/cli/cli_pipeline/SKILL.md +9 -10
  202. package/packages/skills/src/bundled/cli/cli_safe_exec/SKILL.md +1 -1
  203. package/packages/skills/src/bundled/cli/software_engineering/SKILL.md +23 -0
  204. package/packages/skills/src/bundled/cron_manager/SKILL.md +2 -2
  205. package/packages/skills/src/bundled/cron_reminder/SKILL.md +7 -7
  206. package/packages/skills/src/bundled/filesystem/file_read_and_summarize/SKILL.md +11 -10
  207. package/packages/skills/src/bundled/filesystem/file_writer/SKILL.md +29 -35
  208. package/packages/skills/src/bundled/filesystem/workspace_file_operator/SKILL.md +22 -0
  209. package/packages/skills/src/bundled/search_knowledge/capability_discovery/SKILL.md +5 -4
  210. package/packages/skills/src/bundled-data.generated.ts +690 -1255
  211. package/dist/ui/assets/AgentCreateForm-DzaIT-dA.js +0 -1
  212. package/dist/ui/assets/AgentDetailPage-DgqcJceY.js +0 -1
  213. package/dist/ui/assets/AgentNewPage-CNSpoOSA.js +0 -1
  214. package/dist/ui/assets/AgentsPage-BMUJzTD6.js +0 -10
  215. package/dist/ui/assets/ApiClientPage-Cum_a_3j.js +0 -3
  216. package/dist/ui/assets/CanvasPage-o6oCP6uq.js +0 -33
  217. package/dist/ui/assets/ChannelsPage-WrB0zwLq.js +0 -8
  218. package/dist/ui/assets/DashboardPage-BCd6kNw0.js +0 -6
  219. package/dist/ui/assets/MeetingPage-BULIAWzq.js +0 -1
  220. package/dist/ui/assets/ModelSelector-BMYOChYb.js +0 -1
  221. package/dist/ui/assets/ProvidersPage-BVN5UZrI.js +0 -1
  222. package/dist/ui/assets/SettingsPage-CYmpFfDn.js +0 -9
  223. package/dist/ui/assets/SetupPage-Dnmb1Lbv.js +0 -1
  224. package/dist/ui/assets/WebChatPage-DmmdFhIC.js +0 -16
  225. package/dist/ui/assets/accordion-CnLzKNHK.js +0 -1
  226. package/dist/ui/assets/alert-B9J6KHmt.js +0 -1
  227. package/dist/ui/assets/alert-dialog-KcYQWcJ6.js +0 -1
  228. package/dist/ui/assets/arrow-left-CBcbX5EZ.js +0 -1
  229. package/dist/ui/assets/badge-88dRb4M8.js +0 -1
  230. package/dist/ui/assets/bell-8BqRYmzf.js +0 -1
  231. package/dist/ui/assets/chevron-down-DIosfU_U.js +0 -1
  232. package/dist/ui/assets/chevron-left-D4U-5A27.js +0 -1
  233. package/dist/ui/assets/chevron-right-CR4Skrf3.js +0 -1
  234. package/dist/ui/assets/chevron-up-CI-W21Fy.js +0 -1
  235. package/dist/ui/assets/circle-check-6Ard1-2z.js +0 -1
  236. package/dist/ui/assets/dropdown-menu-DDiaHg5y.js +0 -1
  237. package/dist/ui/assets/es-4I-joeZz.js +0 -1
  238. package/dist/ui/assets/folder-open-DJBLDFjv.js +0 -1
  239. package/dist/ui/assets/format-DsLPBxvt.js +0 -1
  240. package/dist/ui/assets/gauge-B8Tj43rC.js +0 -1
  241. package/dist/ui/assets/hexagon-6L79pgVK.js +0 -1
  242. package/dist/ui/assets/index-BmwTAwOF.css +0 -2
  243. package/dist/ui/assets/index-Cyw7L0Li.js +0 -116
  244. package/dist/ui/assets/key-DyKOoQh5.js +0 -1
  245. package/dist/ui/assets/label-B_15zZlR.js +0 -1
  246. package/dist/ui/assets/loader-circle-BmBOgYze.js +0 -1
  247. package/dist/ui/assets/lock-BS6OLXPv.js +0 -1
  248. package/dist/ui/assets/play-zJpWuhrr.js +0 -1
  249. package/dist/ui/assets/plus-BZQX26Dr.js +0 -1
  250. package/dist/ui/assets/progress-D5c-Eilm.js +0 -1
  251. package/dist/ui/assets/scroll-area-CihOx0cb.js +0 -1
  252. package/dist/ui/assets/search-DzDptO9s.js +0 -1
  253. package/dist/ui/assets/select-BQCOjM2j.js +0 -1
  254. package/dist/ui/assets/slider-bcUiUfx0.js +0 -14
  255. package/dist/ui/assets/switch-BR30E4ej.js +0 -1
  256. package/dist/ui/assets/table-B3aGEaVp.js +0 -1
  257. package/dist/ui/assets/tabs-LQidMKRS.js +0 -1
  258. package/dist/ui/assets/terminal--7G943As.js +0 -1
  259. package/dist/ui/assets/useProviders-C1xVKLxB.js +0 -1
  260. package/dist/ui/assets/utils-3pnRFmFe.js +0 -1
  261. package/dist/ui/assets/vendor-charts-Bu2lyBKP.js +0 -65
  262. package/dist/ui/assets/vendor-radix-D6rA7xKY.js +0 -63
  263. package/dist/ui/assets/vendor-react-BU5iQU4f.js +0 -1
  264. package/dist/ui/assets/volume-2-BekVQl6P.js +0 -1
  265. package/packages/core/src/agent/context-guard.ts +0 -91
  266. package/packages/core/src/agent/hooks.ts +0 -166
  267. package/packages/core/src/agent/providers.ts +0 -1
  268. package/packages/core/src/auth/auth.ts +0 -111
  269. package/packages/core/src/auth/index.ts +0 -1
  270. package/packages/core/src/canvas/canvas-tools.ts +0 -448
  271. package/packages/core/src/gateway/router.ts +0 -126
  272. package/packages/core/src/scheduler/dag/AgentExecutor.ts +0 -53
  273. package/packages/core/src/scheduler/dag/DAGScheduler.ts +0 -250
  274. package/packages/core/src/scheduler/dag/EventBridge.ts +0 -122
  275. package/packages/core/src/scheduler/dag/TaskGraph.ts +0 -192
  276. package/packages/core/src/scheduler/dag/TaskNode.ts +0 -97
  277. package/packages/core/src/scheduler/dag/TaskResult.ts +0 -22
  278. package/packages/core/src/scheduler/dag/errors.ts +0 -37
  279. package/packages/core/src/scheduler/dag/index.ts +0 -26
  280. package/packages/core/src/scheduler/dag/presets/ResearchPreset.ts +0 -97
  281. package/packages/core/src/scheduler/dag/strategies/ParallelStrategy.ts +0 -21
  282. package/packages/core/src/scheduler/dag/strategies/PriorityStrategy.ts +0 -46
  283. package/packages/core/src/scheduler/index.ts +0 -22
  284. package/packages/core/src/scheduler/task-driver.ts +0 -216
  285. package/packages/core/src/tools/canvas/index.ts +0 -420
  286. package/packages/core/src/tools/meeting/index.ts +0 -336
  287. package/packages/core/src/tools/projects/index.ts +0 -348
  288. package/packages/core/src/tools/voice/index.ts +0 -104
  289. package/packages/core/src/utils/index.ts +0 -5
  290. package/packages/skills/src/bundled/agents/code_delegator/SKILL.md +0 -156
  291. package/packages/skills/src/bundled/canvas/canvas_dashboard/SKILL.md +0 -146
  292. package/packages/skills/src/bundled/canvas/canvas_interact/SKILL.md +0 -148
  293. package/packages/skills/src/bundled/canvas/canvas_report/SKILL.md +0 -146
  294. package/packages/skills/src/bundled/meeting/meeting_transcription/SKILL.md +0 -213
  295. package/packages/skills/src/bundled/voice/voice_assistant/SKILL.md +0 -174
  296. package/packages/skills/src/bundled/voice/voice_input/SKILL.md +0 -146
  297. package/packages/skills/src/bundled/voice/voice_output/SKILL.md +0 -151
@@ -26,45 +26,47 @@ import type { AgentDoc, ModelDoc } from "../storage/collections"
26
26
  import { logger } from "../utils/logger"
27
27
  import type { LLMMessage, LLMToolDef, ContentPart } from "./llm-client"
28
28
  import type { MCPClientManager } from "@johpaz/hive-agents-mcp"
29
- import { syncToolCatalogToFTS, mcpToolFullName } from "./tool-selector"
30
- import { syncSkillsToFTS, getMinimalSkills, selectSkills, type SkillDescriptor } from "./skill-selector"
31
- import { syncPlaybookToFTS } from "./playbook-selector"
29
+ import { syncToolCatalogToIndex, mcpToolFullName } from "./tool-selector"
30
+ import { syncSkillsToIndex, getMinimalSkills, selectSkills, getSkillByName, type SkillDescriptor } from "./skill-selector"
31
+ import { syncPlaybookToIndex, selectPlaybookRules } from "./playbook-selector"
32
32
  import { getRecentMessages, getSummary, getScratchpad, toAPIMessages } from "./conversation-store"
33
33
  import { formatContext, estimateTokens } from "../utils/toon"
34
34
  import { buildSystemPromptWithProjects } from "./prompt-builder"
35
35
  import { createAllTools } from "../tools/index.ts"
36
36
  import { resolveUserId } from "../storage/onboarding"
37
37
  import { getMCPManager as getSingletonMCPManager } from "../mcp/singleton"
38
- import { syncMCPToolsToDB, syncMCPToolsToFTS } from "../mcp/tool-sync"
38
+ import { syncMCPToolsToDB, syncMCPToolsToIndex } from "../mcp/tool-sync"
39
39
  import { getUserDate, getUserTime } from "../utils/date"
40
40
  import { loadConfig } from "../config/loader"
41
41
  import { getHiveDb } from "../storage/hivedb"
42
+ import { listCatalogAgents, renderAgentRoutingCatalog } from "./catalog-selector"
43
+ import { expandToolAllowlist } from "./delegation-runtime"
44
+ import { MINIMAL_TOOLS } from "./minimal-loadout"
42
45
 
43
46
  const log = logger.child("context-compiler")
44
47
 
45
48
  // Configuration constants
46
- const KEEP_LAST_N_MESSAGES = 30 // Always keep last N messages (Strategy: SELECT) — only user+assistant text, no tool results
49
+ const KEEP_LAST_N_MESSAGES = 15 // Always keep last N messages (Strategy: SELECT) — only user+assistant text, no tool results
47
50
  const DEFAULT_CONTEXT_WINDOW = 250000 // Default context window when model is unknown
48
- const COMPACT_RATIO = 0.80 // Compact when estimated input exceeds 70% of context window
51
+ const COMPACT_RATIO = 0.80 // Reserve budget: truncate system prompt when it would exceed 80% of context window
49
52
  const MAX_SYSTEM_PROMPT_CHARS_CAP = 128000 // Hard cap for pathological prompts; normal budget is model-aware
53
+ const MCP_LAZY_CONNECT_TIMEOUT_MS = 8000 // Bound for on-demand connect of a dormant MCP server
54
+ const SUMMARY_MAX_CHARS = 4000 // Cap the compacted summary so it can't itself blow the system-prompt budget
50
55
 
51
- // MINIMAL TOOL SET — fixed always-available tools
52
- // The agent discovers the rest via search_knowledge
53
- const MINIMAL_TOOLS = new Set([
54
- "save_note",
55
- "notify",
56
- "report_progress",
57
- "search_knowledge",
58
- ])
59
-
60
- // MINIMAL SKILL SET — fixed always-available skills
61
- // These skills are ALWAYS in context - the agent uses them to discover everything else
62
- const MINIMAL_SKILL_NAMES = [
63
- "capability_discovery", // Core: how to find tools, skills, MCP, playbook via search_knowledge
64
- "memory_manager", // Persistent notes that survive context compression
65
- "canvas_report", // Display results to users with charts, tables, cards
66
- "task_orchestrator", // Agent coordination via notify
67
- ]
56
+
57
+
58
+ /** Bounds a dormant MCP server's on-demand wake so one dead server can't stall a whole turn. */
59
+ async function withMcpConnectTimeout(op: () => Promise<void>, timeoutMs: number): Promise<void> {
60
+ let timer: ReturnType<typeof setTimeout>
61
+ const timeout = new Promise<never>((_, reject) => {
62
+ timer = setTimeout(() => reject(new Error(`MCP connect timed out after ${timeoutMs}ms`)), timeoutMs)
63
+ })
64
+ try {
65
+ await Promise.race([op(), timeout])
66
+ } finally {
67
+ clearTimeout(timer!)
68
+ }
69
+ }
68
70
 
69
71
  // ─── Types ─────────────────────────────────────────────────────────────────
70
72
 
@@ -80,6 +82,8 @@ export interface ContextTool {
80
82
 
81
83
  export interface CompiledContext {
82
84
  systemPrompt: string
85
+ /** The `# RESUMEN DE LA CONVERSACIÓN` block already folded into `systemPrompt` — exposed so a caller-supplied `systemPromptOverride` can compose it in instead of discarding it (see agent-loop.ts). "" when compaction hasn't fired. */
86
+ conversationSummarySection: string
83
87
  messages: LLMMessage[]
84
88
  tools: LLMToolDef[]
85
89
  allTools: ContextTool[]
@@ -131,7 +135,11 @@ function fromAgentDoc(doc: AgentDoc) {
131
135
  provider_id: fromIndexable(doc.provider_id),
132
136
  model_id: fromIndexable(doc.model_id),
133
137
  tools_json: doc.tools_json,
138
+ tool_allowlist_json: doc.tool_allowlist_json,
134
139
  skills_json: doc.skills_json,
140
+ active_mcp_json: doc.active_mcp_json,
141
+ mcp_server_ids_json: doc.mcp_server_ids_json,
142
+ source: doc.source,
135
143
  max_iterations: doc.max_iterations,
136
144
  workspace: doc.workspace,
137
145
  }
@@ -194,6 +202,11 @@ export async function compileContext(opts: {
194
202
  }
195
203
 
196
204
  const isWorker = agent.role === 'worker' || !!isolated
205
+ const canDiscoverAllMcp = agent.role === "coordinator" && !isolated
206
+ // A catalog-seeded agent (agent-catalog.ts) has its loadout fully
207
+ // curated (tool_allowlist_json/skills_json/mcp scope) — plain agent_create
208
+ // workers and the coordinator get the open/minimal defaults below instead.
209
+ const isCatalogAgent = agent.source === "catalog"
197
210
  log.info(`[context-compiler] [STEP-1] ✅ Compiling for ${isWorker ? 'worker' : 'coordinator'} agent=${agent.name}`)
198
211
 
199
212
  // Load model's context window for compaction decisions
@@ -217,22 +230,49 @@ export async function compileContext(opts: {
217
230
  throw err
218
231
  }
219
232
 
220
- // [STEP-3c] Load MCP tools (executors only — FTS sync happens here too)
233
+ // [STEP-3c] Load MCP tools (executors only — index sync happens here too)
221
234
  log.info(`[context-compiler] [STEP-3c] Loading MCP tools...`)
222
235
  const mcpToolExecutors: ContextTool[] = []
223
236
 
224
237
  if (effectiveMcpManager) {
225
238
  try {
226
239
  const mcpServersCol = await col<import("../storage/collections").McpServerDoc>("mcpServers")
227
- const dbServers = (await mcpServersCol.scan({})).map(e => e.doc).filter(s => s.enabled)
240
+ const assignedMcpIds = new Set<string>([
241
+ ...(agent.mcp_server_ids_json ? JSON.parse(agent.mcp_server_ids_json) : []),
242
+ ...(agent.active_mcp_json ? JSON.parse(agent.active_mcp_json) : []),
243
+ ])
244
+ const dbServers = (await mcpServersCol.scan({}))
245
+ .map(e => e.doc)
246
+ .filter(s => s.enabled && (canDiscoverAllMcp || assignedMcpIds.has(s.id)))
228
247
 
229
248
  for (const server of dbServers) {
230
249
  // Try ID first (normalized), then name
250
+ let resolvedServerKey = server.id
231
251
  let serverTools = effectiveMcpManager.getServerTools(server.id)
232
252
  if (!serverTools || serverTools.length === 0) {
253
+ resolvedServerKey = server.name
233
254
  serverTools = effectiveMcpManager.getServerTools(server.name)
234
255
  }
235
256
 
257
+ // Lazy wake: the server is registered but dormant (no agent has leased
258
+ // it yet). Connect on demand so the coordinator isn't permanently cut off
259
+ // from tools nothing else ever wakes.
260
+ if (!serverTools || serverTools.length === 0) {
261
+ for (const key of [server.id, server.name]) {
262
+ try {
263
+ await withMcpConnectTimeout(() => effectiveMcpManager!.connectServer(key), MCP_LAZY_CONNECT_TIMEOUT_MS)
264
+ const woken = effectiveMcpManager.getServerTools(key)
265
+ if (woken && woken.length > 0) {
266
+ resolvedServerKey = key
267
+ serverTools = woken
268
+ break
269
+ }
270
+ } catch (err) {
271
+ log.warn(`[context-compiler] [STEP-3c] Lazy connect failed for ${server.name} (${key}): ${(err as Error).message}`)
272
+ }
273
+ }
274
+ }
275
+
236
276
  if (serverTools && serverTools.length > 0) {
237
277
  log.info(`[context-compiler] [STEP-3c] Server ${server.name}: ${serverTools.length} tools`)
238
278
 
@@ -254,7 +294,7 @@ export async function compileContext(opts: {
254
294
  execute: async (params: Record<string, unknown>) => {
255
295
  // Return raw JS value — agent-loop will TOON-encode via formatToolResult.
256
296
  // Never pre-stringify here: formatToolResult(string) double-encodes.
257
- return await effectiveMcpManager.callTool(server.id, mcpTool.name, params)
297
+ return await effectiveMcpManager.callTool(resolvedServerKey, mcpTool.name, params)
258
298
  },
259
299
  })
260
300
 
@@ -278,7 +318,7 @@ export async function compileContext(opts: {
278
318
  await syncMCPToolsToDB(server.id || server.name, server.name, serverTools)
279
319
  }
280
320
  }
281
- await syncMCPToolsToFTS();
321
+ await syncMCPToolsToIndex();
282
322
  log.info(`[context-compiler] [STEP-3c] ✅ Persisted MCP tools to DB + HiveDB index`)
283
323
  } catch (syncErr) {
284
324
  log.warn(`[context-compiler] [STEP-3c] ⚠️ Failed to persist MCP tools to DB: ${(syncErr as Error).message}`)
@@ -305,11 +345,25 @@ export async function compileContext(opts: {
305
345
  timeoutMs: t.timeoutMs,
306
346
  }))
307
347
 
308
- const allTools = [...nativeTools, ...mcpToolExecutors]
348
+ let allTools = [...nativeTools, ...mcpToolExecutors]
309
349
 
310
350
  // Only native minimal tools in LLM context
311
351
  // MCP tools are discovered dynamically via search_knowledge(type="mcp")
312
- const filteredNativeTools: ContextTool[] = nativeTools.filter(t => MINIMAL_TOOLS.has(t.name))
352
+ let filteredNativeTools: ContextTool[] = nativeTools.filter(t => MINIMAL_TOOLS.has(t.name))
353
+ if (isCatalogAgent) {
354
+ const allowedNames = new Set<string>(
355
+ agent.tool_allowlist_json
356
+ ? expandToolAllowlist(
357
+ JSON.parse(agent.tool_allowlist_json),
358
+ nativeTools.map((tool) => tool.name),
359
+ )
360
+ : agent.tools_json
361
+ ? JSON.parse(agent.tools_json)
362
+ : [],
363
+ )
364
+ filteredNativeTools = nativeTools.filter((tool) => allowedNames.has(tool.name))
365
+ allTools = [...filteredNativeTools, ...mcpToolExecutors]
366
+ }
313
367
 
314
368
  const nativeToolsForLLM: LLMToolDef[] = filteredNativeTools.map(t => ({
315
369
  type: "function" as const,
@@ -320,10 +374,31 @@ export async function compileContext(opts: {
320
374
  },
321
375
  }))
322
376
 
323
- const toolsForLLM: LLMToolDef[] = nativeToolsForLLM
377
+ let toolsForLLM: LLMToolDef[] = nativeToolsForLLM
378
+ // Workers receive MCP tools directly only when prepareDelegation has
379
+ // activated a persistent assignment (or the verifier's internal readback
380
+ // scope). The coordinator keeps every enabled MCP executor discoverable,
381
+ // but out of its initial prompt.
382
+ if (!canDiscoverAllMcp && mcpToolExecutors.length > 0) {
383
+ toolsForLLM = [
384
+ ...toolsForLLM,
385
+ ...mcpToolExecutors.map((tool) => ({
386
+ type: "function" as const,
387
+ function: {
388
+ name: tool.name,
389
+ description: tool.description,
390
+ parameters: tool.parameters,
391
+ },
392
+ })),
393
+ ]
394
+ }
324
395
 
325
396
  log.info(`[context-compiler] [STEP-4] Minimal native tool set: ${filteredNativeTools.length} tools`)
326
- log.info(`[context-compiler] [STEP-4b] MCP tools available via search_knowledge: ${mcpToolExecutors.length} (not injected)`)
397
+ log.info(
398
+ canDiscoverAllMcp
399
+ ? `[context-compiler] [STEP-4b] MCP tools discoverable by coordinator: ${mcpToolExecutors.length}`
400
+ : `[context-compiler] [STEP-4b] MCP tools assigned directly to worker: ${mcpToolExecutors.length}`,
401
+ )
327
402
  log.info(`[context-compiler] [STEP-8] ✅ Combined tools: ${allTools.length} total executors, ${toolsForLLM.length} in LLM context`)
328
403
 
329
404
  // [STEP-8b] STRATEGY 2: SELECT — Skill Loadout (minimal + discovered)
@@ -347,6 +422,13 @@ export async function compileContext(opts: {
347
422
  discoveredSkills = await selectSkills(textMessage)
348
423
  log.info(`[context-compiler] [STEP-8b] ✅ Discovered ${discoveredSkills.length} additional skills via HiveDB`)
349
424
  }
425
+ if (isCatalogAgent && agent.skills_json) {
426
+ for (const skillId of JSON.parse(agent.skills_json) as string[]) {
427
+ const forced = await getSkillByName(skillId)
428
+ if (forced) discoveredSkills.push(forced)
429
+ }
430
+ log.info(`[context-compiler] [STEP-8b] ✅ Loaded ${discoveredSkills.length} catalog agent skills`)
431
+ }
350
432
  } catch (err) {
351
433
  log.warn(`[context-compiler] [STEP-8b] ⚠️ Skill loadout failed: ${(err as Error).message}`)
352
434
  }
@@ -383,24 +465,35 @@ export async function compileContext(opts: {
383
465
  throw err
384
466
  }
385
467
 
386
- const totalTokens = recentMessages.reduce((sum, m) => sum + estimateTokens(m.content), 0)
468
+ // A summary applies when it covers messages that fell out of the current
469
+ // window — i.e. the window's earliest message is strictly after the last
470
+ // message the summary covers. (Comparing window tokens against a
471
+ // context-window-sized threshold, as before, almost never fires: the
472
+ // window is capped at KEEP_LAST_N_MESSAGES messages, which rarely
473
+ // approaches 80% of the context window on its own — so the summary was
474
+ // computed, stored, and the user notified, but never actually reached the
475
+ // model.)
476
+ const summaryApplies = !!(
477
+ summary && summary.last_message_id > 0 &&
478
+ (recentMessages.length === 0 || recentMessages[0].id > summary.last_message_id)
479
+ )
387
480
 
388
- let messages: LLMMessage[]
481
+ const conversationSummarySection = summaryApplies
482
+ ? `\n\n# RESUMEN DE LA CONVERSACIÓN (turnos anteriores, compactados)\n${summary!.summary.slice(0, SUMMARY_MAX_CHARS)}\n`
483
+ : ""
389
484
 
390
- const compactThreshold = Math.floor(modelContextWindow * COMPACT_RATIO)
391
- const compactionFired = !!(summary && totalTokens > compactThreshold)
392
- if (compactionFired) {
393
- // Use summary + recent messages (Strategy: COMPRESS)
394
- messages = [
395
- { role: "system", content: `[Conversation Summary]: ${summary.summary}` },
396
- ...toAPIMessages(recentMessages),
397
- ]
398
- log.info(`[context-compiler] [STEP-9c] Using summary (${summary.messages_covered} messages compressed)`)
399
- } else {
400
- // Conversation is short enough, use all recent messages
401
- messages = toAPIMessages(recentMessages)
485
+ if (summaryApplies) {
486
+ log.info(`[context-compiler] [STEP-9c] Summary applies (${summary!.messages_covered} messages compressed) — folded into system prompt`)
402
487
  }
403
488
 
489
+ // Never a second "system" turn here — every provider (Gemini, Anthropic,
490
+ // OpenAI-compat) hoists ALL role:"system" messages into a single top-level
491
+ // system instruction, so a second one either gets silently merged (fine)
492
+ // or — on a context-overflow retry that keeps only the LAST system message
493
+ // (openai-compat-base.ts) — silently replaces the real prompt. The summary
494
+ // lives in `systemPrompt` instead (see conversationSummarySection below).
495
+ const messages: LLMMessage[] = toAPIMessages(recentMessages)
496
+
404
497
  // [STEP-10] STRATEGY 4: ISOLATE — Build context based on agent role
405
498
  log.info(`[context-compiler] [STEP-10] Building system prompt...`)
406
499
  let systemPrompt: string
@@ -423,6 +516,34 @@ export async function compileContext(opts: {
423
516
  systemPrompt += `\n\n# ENTORNO ACTUAL\n**Fecha**: ${fecha}\n**Hora**: ${hora}\n**Zona horaria**: ${userTimezone}${workspaceLine}\n`
424
517
  log.info(`[context-compiler] [STEP-10b] ✅ Injected current date/time: ${fecha} ${hora} (${userTimezone})`)
425
518
 
519
+ // Placed early (right after ENTORNO ACTUAL), not appended at the end: the
520
+ // truncation guard below cuts the system prompt's TAIL when it's over
521
+ // budget, so a summary appended last would be the first thing silently
522
+ // dropped on an oversized prompt.
523
+ systemPrompt += conversationSummarySection
524
+
525
+ // Only the live roster goes here — how to delegate, fan-out/fan-in and the
526
+ // execution-truth rules are static doctrine and live in the coordinator's
527
+ // stored prompt (storage/onboarding.ts), not duplicated per turn.
528
+ if (!isWorker) {
529
+ const routingCatalog = renderAgentRoutingCatalog(await listCatalogAgents())
530
+ systemPrompt += `\n\n# COLMENA DE AGENTES\nWorkers disponibles ahora mismo (globales del sistema, ya existen):\n\n${routingCatalog}\n`
531
+ }
532
+
533
+ const playbookInput = taskContext || userMessage
534
+ const playbookText = typeof playbookInput === "string"
535
+ ? playbookInput
536
+ : Array.isArray(playbookInput)
537
+ ? playbookInput.filter((part) => part.type === "text").map((part) => (part as any).text).join("\n")
538
+ : String(playbookInput)
539
+ const playbookRules = (await selectPlaybookRules(playbookText)).filter((rule) => {
540
+ if (!rule.applicable_to || !rule.applicable_to.includes("agent:")) return true
541
+ return isCatalogAgent ? rule.applicable_to.includes(`agent:${agent.id}`) : false
542
+ })
543
+ if (playbookRules.length > 0) {
544
+ systemPrompt += `\n\n# PLAYBOOK APRENDIDO\n${playbookRules.map((rule) => `- ${rule.rule}`).join("\n")}\n`
545
+ }
546
+
426
547
  // Inject scratchpad (Strategy: WRITE) — usando TOON para ahorro de tokens
427
548
  if (scratchpadNotes.length > 0) {
428
549
  const scratchpadData: Record<string, string> = {}
@@ -434,11 +555,11 @@ export async function compileContext(opts: {
434
555
  systemPrompt += `\n\n# SCRATCHPAD (Persistent Notes)\n${scratchpadContent}\n`
435
556
  }
436
557
 
437
- // G9: causal context window (buildAgentContext) — only when compaction has
438
- // already fired this turn (a real DB round-trip, not a per-turn cost) and
558
+ // G9: causal context window (buildAgentContext) — only when the summary
559
+ // applies this turn (a real DB round-trip, not a per-turn cost) and
439
560
  // there's a causal stream to build it from. episodicSimilarity is omitted:
440
561
  // it requires embeddings hive doesn't generate anywhere yet.
441
- if (compactionFired && opts.causalStreamId && loadConfig().causalLog?.enabled) {
562
+ if (summaryApplies && opts.causalStreamId && loadConfig().causalLog?.enabled) {
442
563
  try {
443
564
  const causalDb = await getHiveDb()
444
565
  const objectiveSource = taskContext || userMessage
@@ -470,26 +591,22 @@ export async function compileContext(opts: {
470
591
  }
471
592
  }
472
593
 
473
- // Dynamic tool discovery instruction (coordinator only)
474
- // Note: MCP tools are already available directly, no search needed
594
+ // Coordinator only. Just the live loadout — how to use it is doctrine and
595
+ // lives in the stored prompt + the capability_discovery skill.
475
596
  if (!isWorker) {
476
- // Build minimal tools documentation from filtered native tools
477
597
  const minimalToolsDocs = filteredNativeTools
478
598
  .filter(t => MINIMAL_TOOLS.has(t.name))
479
599
  .map(t => `- **${t.name}**: ${t.description || "Herramienta nativa"}`)
480
600
  .join("\n")
481
601
 
482
- systemPrompt += `\n\n# HERRAMIENTAS SIEMPRE DISPONIBLES\n` +
483
- `${minimalToolsDocs}\n\n` +
484
- `## Delegación a workers\n` +
485
- `Los workers arrancan con estas mismas 4 herramientas mínimas.\n` +
486
- `**Antes de delegar**, usá \`search_knowledge(type="tools", query="<tarea>")\` para identificar qué tools necesita el worker e incluirlas en la instrucción de \`task_delegate\`.\n`
602
+ systemPrompt += `\n\n# HERRAMIENTAS SIEMPRE DISPONIBLES\n${minimalToolsDocs}\n`
487
603
 
488
604
 
489
605
  // Inject available skills (minimal + discovered)
490
606
  if (allSkills.length > 0) {
491
607
  // Minimal skills: inject full body (always-loaded instructions)
492
- const minimalWithBody = allSkills.filter(s => MINIMAL_SKILL_NAMES.includes(s.name) && s.body)
608
+ const minimalNames = new Set(minimalSkills.map(s => s.name))
609
+ const minimalWithBody = allSkills.filter(s => minimalNames.has(s.name) && s.body)
493
610
  if (minimalWithBody.length > 0) {
494
611
  let minimalSection = `\n\n# SKILLS SIEMPRE ACTIVAS\n`
495
612
  for (const skill of minimalWithBody) {
@@ -499,7 +616,7 @@ export async function compileContext(opts: {
499
616
  }
500
617
 
501
618
  // Discovered skills: list only (body arrives via agent-loop when tools are injected)
502
- const discoveredOnly = allSkills.filter(s => !MINIMAL_SKILL_NAMES.includes(s.name))
619
+ const discoveredOnly = allSkills.filter(s => !minimalNames.has(s.name))
503
620
  if (discoveredOnly.length > 0) {
504
621
  let discoveredSection = `\n\n# SKILLS DESCUBIERTAS (relevantes para esta tarea)\n`
505
622
  for (const skill of discoveredOnly) {
@@ -515,13 +632,15 @@ export async function compileContext(opts: {
515
632
  }
516
633
 
517
634
  // For isolated workers, add task context + tool discovery instruction
518
- if (isWorker && opts.taskContext) {
635
+ if (isWorker && opts.taskContext && !isCatalogAgent) {
519
636
  systemPrompt += `\n\n# HERRAMIENTAS DISPONIBLES\n` +
520
637
  `Arrancas con herramientas básicas. Si tu tarea requiere herramientas adicionales (web_search, fs_read, browser_navigate, etc.):\n` +
521
638
  `1. Usá \`search_knowledge(type="tools", query="<herramienta o tarea>")\` para encontrarlas.\n` +
522
639
  `2. Las herramientas que encuentres estarán disponibles para usar inmediatamente.\n` +
523
640
  `Si el coordinador te indicó herramientas específicas, buscalas primero con search_knowledge antes de ejecutar tu tarea.\n` +
524
641
  `\n# CURRENT TASK\n${opts.taskContext}\n\nFocus ONLY on this task. Do not deviate.`
642
+ } else if (isWorker && opts.taskContext) {
643
+ systemPrompt += `\n\n# CURRENT TASK\n${opts.taskContext}\n\nFocus ONLY on this task and return the required structured delivery.`
525
644
  }
526
645
 
527
646
  // Truncate system prompt only when it exceeds a model-aware budget.
@@ -552,6 +671,7 @@ export async function compileContext(opts: {
552
671
 
553
672
  return {
554
673
  systemPrompt,
674
+ conversationSummarySection,
555
675
  messages,
556
676
  tools: toolsForLLM,
557
677
  allTools,
@@ -561,7 +681,7 @@ export async function compileContext(opts: {
561
681
 
562
682
  // Re-export sync functions for gateway/initializer
563
683
  export {
564
- syncToolCatalogToFTS as syncToolsToFTS,
565
- syncSkillsToFTS,
566
- syncPlaybookToFTS,
684
+ syncToolCatalogToIndex as syncToolsToIndex,
685
+ syncSkillsToIndex,
686
+ syncPlaybookToIndex,
567
687
  }
@@ -10,7 +10,7 @@ import { getHiveDb } from "../storage/hivedb"
10
10
  import { logger } from "../utils/logger"
11
11
  import type { LLMMessage, ContentPart } from "./llm-client"
12
12
  import { estimateTokens } from "../utils/toon"
13
- import type { ConversationDoc, SummaryDoc } from "../storage/collections"
13
+ import type { ConversationDoc, SummaryDoc, MessageSource } from "../storage/collections"
14
14
 
15
15
  const log = logger.child("conv-store")
16
16
 
@@ -21,7 +21,9 @@ export interface StoredMessage {
21
21
  id: number
22
22
  thread_id: string
23
23
  channel: string
24
- role: "user" | "assistant" | "tool" | "system"
24
+ role: "user" | "assistant" | "tool"
25
+ /** Provenance of this turn. Never null — legacy rows are normalized to "legacy_internal" on read. */
26
+ source: MessageSource
25
27
  content: string
26
28
  tool_calls_json: string | null
27
29
  tool_call_id: string | null
@@ -31,17 +33,48 @@ export interface StoredMessage {
31
33
  created_at: number
32
34
  }
33
35
 
36
+ // ─── Internal events (delegation fan-in, etc.) ────────────────────────────────
37
+ //
38
+ // These are system-authored turns (async delegation outcomes) that must reach
39
+ // the model as input but must never be persisted with role:"system" — doing so
40
+ // causes every LLM provider to hoist them permanently into the system
41
+ // instruction on every subsequent turn (see gemini.ts/anthropic.ts, which
42
+ // concatenate ALL role:"system" messages into systemInstruction/system). They
43
+ // are persisted as role:"user" + a source tag instead, and wrapped with a
44
+ // framing marker only at serialization time (toAPIMessages), so stored content
45
+ // stays clean and the wording can evolve without a migration.
46
+
47
+ export const INTERNAL_SOURCES: ReadonlySet<string> =
48
+ new Set(["task_complete", "delegation_summary", "legacy_internal"])
49
+
50
+ export function isInternalSource(source: string | null | undefined): boolean {
51
+ return !!source && INTERNAL_SOURCES.has(source)
52
+ }
53
+
54
+ export function formatInternalEvent(source: string, content: string): string {
55
+ return `<hive:internal_event source="${source}">\n` +
56
+ `Evento interno del sistema — NO es un mensaje del usuario. No lo cites literalmente, no expongas IDs internos (task_id, worker_id, verification_id) ni JSON crudo. Respondé al usuario de forma natural y breve.\n\n` +
57
+ `${content}\n` +
58
+ `</hive:internal_event>`
59
+ }
60
+
34
61
  function storageId(threadId: string, seq: number): string {
35
62
  return `${threadId}:${String(seq).padStart(15, "0")}`
36
63
  }
37
64
 
38
65
  function toStoredMessage(id: string, doc: ConversationDoc): StoredMessage {
39
66
  const seq = parseInt(id.slice(id.lastIndexOf(":") + 1), 10)
67
+ // Legacy rows (written before `source` existed) used role:"system" as the
68
+ // sole marker for internal events. Normalize them here so every downstream
69
+ // reader (getRecentMessages, compaction, context-compiler) sees a single
70
+ // consistent shape and never has to special-case role:"system" again.
71
+ const legacyInternal = doc.role === "system"
40
72
  return {
41
73
  id: seq,
42
74
  thread_id: doc.thread_id,
43
75
  channel: doc.channel,
44
- role: doc.role,
76
+ role: legacyInternal ? "user" : (doc.role as StoredMessage["role"]),
77
+ source: doc.source ?? (legacyInternal ? "legacy_internal" : "message"),
45
78
  content: doc.content,
46
79
  tool_calls_json: doc.tool_calls_json,
47
80
  tool_call_id: doc.tool_call_id,
@@ -54,6 +87,16 @@ function toStoredMessage(id: string, doc: ConversationDoc): StoredMessage {
54
87
 
55
88
  // ─── Message operations ───────────────────────────────────────────────────────
56
89
 
90
+ const recentMessageTimestamps: number[] = []
91
+
92
+ export function getRecentMessageCount(windowMs = 5 * 60_000): number {
93
+ const cutoff = Date.now() - windowMs
94
+ while (recentMessageTimestamps.length && recentMessageTimestamps[0] < cutoff) {
95
+ recentMessageTimestamps.shift()
96
+ }
97
+ return recentMessageTimestamps.length
98
+ }
99
+
57
100
  export async function addMessage(
58
101
  threadId: string,
59
102
  role: StoredMessage["role"],
@@ -63,6 +106,7 @@ export async function addMessage(
63
106
  tool_calls?: LLMMessage["tool_calls"]
64
107
  tool_call_id?: string
65
108
  reasoning_content?: string
109
+ source?: MessageSource
66
110
  }
67
111
  ): Promise<number> {
68
112
  // Handle multimodal content by extracting text for the content column
@@ -90,6 +134,7 @@ export async function addMessage(
90
134
  tool_calls_json,
91
135
  tool_call_id: opts?.tool_call_id ?? null,
92
136
  reasoning_content: opts?.reasoning_content ?? null,
137
+ source: opts?.source ?? "message",
93
138
  // Estimate tokens: content + tool_calls JSON
94
139
  token_count: Math.max(1, estimateTokens(textContent) + estimateTokens(tool_calls_json ?? "")),
95
140
  created_at: now,
@@ -99,6 +144,7 @@ export async function addMessage(
99
144
  // Fire-and-forget — never block message persistence on the activity chart rollup.
100
145
  const hour = new Date(now).toISOString().slice(0, 13)
101
146
  bumpRollup("activityRollups", hour, { messageCount: 1 }).catch(() => {})
147
+ recentMessageTimestamps.push(now)
102
148
 
103
149
  return seq
104
150
  }
@@ -188,6 +234,13 @@ export function toAPIMessages(rows: StoredMessage[]): LLMMessage[] {
188
234
  if (r.content_multimodal) {
189
235
  try { content = JSON.parse(r.content_multimodal) } catch { /* ignore */ }
190
236
  }
237
+ // Internal events (delegation fan-in) are wrapped at serialization time —
238
+ // never at authoring time — so stored content stays clean and legacy rows
239
+ // (normalized to source:"legacy_internal" in toStoredMessage) get wrapped
240
+ // for free. Internal events are never multimodal in practice.
241
+ if (isInternalSource(r.source) && typeof content === "string") {
242
+ content = formatInternalEvent(r.source, content)
243
+ }
191
244
  const msg: LLMMessage = { role: r.role, content }
192
245
  // Note: tool_calls and tool_call_id are NOT reconstructed from DB.
193
246
  // Tool results are kept in-memory during iteration but not persisted,