@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
@@ -21,8 +21,9 @@ import {
21
21
  getHistory,
22
22
  getSummary,
23
23
  saveSummary,
24
- toAPIMessages,
25
24
  getMessageCount,
25
+ isInternalSource,
26
+ type StoredMessage,
26
27
  } from "./conversation-store"
27
28
  import { estimateTokens } from "../utils/toon"
28
29
  import { callLLM, resolveProviderConfig, getDefaultLLM, type ContentPart } from "./llm-client"
@@ -58,7 +59,10 @@ export async function maybeCompact(
58
59
  const modelId = fromIndexable(coordinators[0]?.doc.model_id ?? null)
59
60
  if (modelId) {
60
61
  const modelsCol = await col<ModelDoc>("models")
61
- const modelEntry = await modelsCol.get(modelId.replace(/^[^/]+\//, ''))
62
+ // El id se busca completo: recortar el primer segmento rompía cualquier
63
+ // modelo cuyo nombre lleve barra (meta/llama-3.3-70b-instruct buscaba
64
+ // "llama-3.3-70b-instruct", no encontraba nada y caía al default).
65
+ const modelEntry = await modelsCol.get(modelId)
62
66
  if (modelEntry?.doc.context_window) {
63
67
  effectiveThreshold = Math.floor(modelEntry.doc.context_window * 0.25)
64
68
  }
@@ -80,22 +84,48 @@ export async function maybeCompact(
80
84
  }
81
85
  }
82
86
 
87
+ /**
88
+ * Find a clean cut point: the "keep" side must begin with a user turn so we
89
+ * never leave orphaned tool messages at the start of the visible window.
90
+ * Internal events (delegation fan-in) are persisted as role:"user", so they
91
+ * are valid boundaries here same as human turns.
92
+ * Returns 0 when no clean boundary exists (caller should skip compaction).
93
+ */
94
+ export function findCompactionCutIndex(rows: StoredMessage[], keepLastN = KEEP_LAST_N_MESSAGES): number {
95
+ let cutIndex = rows.length - keepLastN
96
+ while (cutIndex > 0 && rows[cutIndex]?.role !== "user") {
97
+ cutIndex--
98
+ }
99
+ return cutIndex
100
+ }
101
+
102
+ /**
103
+ * Render a transcript for the summarizer LLM. Internal events (delegation
104
+ * fan-in notices) are labeled distinctly — they are persisted as
105
+ * role:"user" so the LLM treats them as input, but labeling them [USER] here
106
+ * would make the summarizer attribute system-generated task outcomes to the
107
+ * human, baking that misattribution into the durable summary.
108
+ */
109
+ export function renderTranscript(rows: StoredMessage[], maxMsgChars = MAX_MSG_CHARS): string {
110
+ return rows
111
+ .map((r) => {
112
+ const label = isInternalSource(r.source) ? "EVENTO INTERNO" : r.role.toUpperCase()
113
+ return `[${label}]: ${r.content.substring(0, maxMsgChars)}`
114
+ })
115
+ .join("\n\n")
116
+ }
117
+
83
118
  /**
84
119
  * Compress a thread's history into a summary.
85
120
  */
86
- export async function compactThread(
121
+ async function compactThread(
87
122
  threadId: string,
88
123
  notify?: { channel: string; userId: string }
89
124
  ): Promise<void> {
90
125
  const allMessages = await getHistory(threadId)
91
126
  if (allMessages.length <= KEEP_LAST_N_MESSAGES) return
92
127
 
93
- // Find a clean cut point: the "keep" side must begin with a user turn so
94
- // we never leave orphaned tool messages at the start of the visible window.
95
- let cutIndex = allMessages.length - KEEP_LAST_N_MESSAGES
96
- while (cutIndex > 0 && allMessages[cutIndex]?.role !== "user") {
97
- cutIndex--
98
- }
128
+ const cutIndex = findCompactionCutIndex(allMessages)
99
129
  if (cutIndex <= 0) {
100
130
  log.info(`[compaction] No clean user-turn boundary found — skipping`)
101
131
  return
@@ -111,17 +141,7 @@ export async function compactThread(
111
141
 
112
142
  // Cap transcript to avoid overflowing small model contexts
113
143
  const capped = toSummarize.slice(-MAX_TRANSCRIPT_MSGS)
114
- const apiMessages = toAPIMessages(capped)
115
- const transcript = apiMessages
116
- .map((m) => {
117
- const text = typeof m.content === "string"
118
- ? m.content
119
- : Array.isArray(m.content)
120
- ? m.content.filter(p => p.type === "text").map(p => (p as any).text).join("\n")
121
- : ""
122
- return `[${m.role.toUpperCase()}]: ${text.substring(0, MAX_MSG_CHARS)}`
123
- })
124
- .join("\n\n")
144
+ const transcript = renderTranscript(capped)
125
145
 
126
146
  const defaultLLM = await getDefaultLLM()
127
147
  if (!defaultLLM) throw new Error("No active LLM providers/models configured in the database")
@@ -144,6 +164,18 @@ export async function compactThread(
144
164
  ],
145
165
  })
146
166
 
167
+ // A failed provider call still returns a populated `content` (the error text),
168
+ // so this has to gate on stop_reason — otherwise the summary that permanently
169
+ // replaces N messages of history becomes "[LLM Error] ...". Skipping leaves the
170
+ // thread uncompacted, which is recoverable; saving is not.
171
+ if (summaryResponse.stop_reason === "error") {
172
+ log.warn(
173
+ `[compaction] Summarizer call failed (${summaryResponse.error?.message ?? "unknown error"}) — `
174
+ + `keeping thread ${threadId} uncompacted rather than saving the error as its summary`
175
+ )
176
+ return
177
+ }
178
+
147
179
  const summary = summaryResponse.content.trim()
148
180
  if (!summary) return
149
181
 
@@ -210,25 +242,3 @@ export function clearOldToolResults<T extends { role: string; content: string |
210
242
  })
211
243
  }
212
244
 
213
- /**
214
- * Summarize a tool result to a single line
215
- * Used for very old tool results (> 10 turns)
216
- */
217
- export function summarizeToolResult(content: string, toolName?: string): string {
218
- // Try to extract success/failure status
219
- const isError = content.includes('error') || content.includes('failed') || content.startsWith('[Tool Error]')
220
- const isSuccess = content.includes('ok') || content.includes('success') || content.includes('true')
221
-
222
- // Try to extract key result field from JSON/TOON
223
- let keyInfo = ""
224
- try {
225
- // Simple extraction of first key value
226
- const firstLine = content.split('\n')[0].substring(0, 80)
227
- keyInfo = firstLine
228
- } catch {
229
- keyInfo = content.substring(0, 80)
230
- }
231
-
232
- const status = isError ? "failed" : isSuccess ? "success" : "completed"
233
- return `[${toolName || 'Tool'} ${status}: ${keyInfo}...]`
234
- }
@@ -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
@@ -201,7 +214,9 @@ export async function compileContext(opts: {
201
214
  if (agent.model_id) {
202
215
  try {
203
216
  const modelsCol = await col<ModelDoc>("models")
204
- const modelEntry = await modelsCol.get(agent.model_id.replace(/^[^/]+\//, ''))
217
+ // Id completo: el recorte del primer segmento fallaba para todo modelo
218
+ // con barra en el nombre y dejaba el context window en el default.
219
+ const modelEntry = await modelsCol.get(agent.model_id)
205
220
  if (modelEntry?.doc.context_window) modelContextWindow = modelEntry.doc.context_window
206
221
  } catch { /* use default */ }
207
222
  }
@@ -217,22 +232,49 @@ export async function compileContext(opts: {
217
232
  throw err
218
233
  }
219
234
 
220
- // [STEP-3c] Load MCP tools (executors only — FTS sync happens here too)
235
+ // [STEP-3c] Load MCP tools (executors only — index sync happens here too)
221
236
  log.info(`[context-compiler] [STEP-3c] Loading MCP tools...`)
222
237
  const mcpToolExecutors: ContextTool[] = []
223
238
 
224
239
  if (effectiveMcpManager) {
225
240
  try {
226
241
  const mcpServersCol = await col<import("../storage/collections").McpServerDoc>("mcpServers")
227
- const dbServers = (await mcpServersCol.scan({})).map(e => e.doc).filter(s => s.enabled)
242
+ const assignedMcpIds = new Set<string>([
243
+ ...(agent.mcp_server_ids_json ? JSON.parse(agent.mcp_server_ids_json) : []),
244
+ ...(agent.active_mcp_json ? JSON.parse(agent.active_mcp_json) : []),
245
+ ])
246
+ const dbServers = (await mcpServersCol.scan({}))
247
+ .map(e => e.doc)
248
+ .filter(s => s.enabled && (canDiscoverAllMcp || assignedMcpIds.has(s.id)))
228
249
 
229
250
  for (const server of dbServers) {
230
251
  // Try ID first (normalized), then name
252
+ let resolvedServerKey = server.id
231
253
  let serverTools = effectiveMcpManager.getServerTools(server.id)
232
254
  if (!serverTools || serverTools.length === 0) {
255
+ resolvedServerKey = server.name
233
256
  serverTools = effectiveMcpManager.getServerTools(server.name)
234
257
  }
235
258
 
259
+ // Lazy wake: the server is registered but dormant (no agent has leased
260
+ // it yet). Connect on demand so the coordinator isn't permanently cut off
261
+ // from tools nothing else ever wakes.
262
+ if (!serverTools || serverTools.length === 0) {
263
+ for (const key of [server.id, server.name]) {
264
+ try {
265
+ await withMcpConnectTimeout(() => effectiveMcpManager!.connectServer(key), MCP_LAZY_CONNECT_TIMEOUT_MS)
266
+ const woken = effectiveMcpManager.getServerTools(key)
267
+ if (woken && woken.length > 0) {
268
+ resolvedServerKey = key
269
+ serverTools = woken
270
+ break
271
+ }
272
+ } catch (err) {
273
+ log.warn(`[context-compiler] [STEP-3c] Lazy connect failed for ${server.name} (${key}): ${(err as Error).message}`)
274
+ }
275
+ }
276
+ }
277
+
236
278
  if (serverTools && serverTools.length > 0) {
237
279
  log.info(`[context-compiler] [STEP-3c] Server ${server.name}: ${serverTools.length} tools`)
238
280
 
@@ -254,7 +296,7 @@ export async function compileContext(opts: {
254
296
  execute: async (params: Record<string, unknown>) => {
255
297
  // Return raw JS value — agent-loop will TOON-encode via formatToolResult.
256
298
  // Never pre-stringify here: formatToolResult(string) double-encodes.
257
- return await effectiveMcpManager.callTool(server.id, mcpTool.name, params)
299
+ return await effectiveMcpManager.callTool(resolvedServerKey, mcpTool.name, params)
258
300
  },
259
301
  })
260
302
 
@@ -278,7 +320,7 @@ export async function compileContext(opts: {
278
320
  await syncMCPToolsToDB(server.id || server.name, server.name, serverTools)
279
321
  }
280
322
  }
281
- await syncMCPToolsToFTS();
323
+ await syncMCPToolsToIndex();
282
324
  log.info(`[context-compiler] [STEP-3c] ✅ Persisted MCP tools to DB + HiveDB index`)
283
325
  } catch (syncErr) {
284
326
  log.warn(`[context-compiler] [STEP-3c] ⚠️ Failed to persist MCP tools to DB: ${(syncErr as Error).message}`)
@@ -305,11 +347,25 @@ export async function compileContext(opts: {
305
347
  timeoutMs: t.timeoutMs,
306
348
  }))
307
349
 
308
- const allTools = [...nativeTools, ...mcpToolExecutors]
350
+ let allTools = [...nativeTools, ...mcpToolExecutors]
309
351
 
310
352
  // Only native minimal tools in LLM context
311
353
  // MCP tools are discovered dynamically via search_knowledge(type="mcp")
312
- const filteredNativeTools: ContextTool[] = nativeTools.filter(t => MINIMAL_TOOLS.has(t.name))
354
+ let filteredNativeTools: ContextTool[] = nativeTools.filter(t => MINIMAL_TOOLS.has(t.name))
355
+ if (isCatalogAgent) {
356
+ const allowedNames = new Set<string>(
357
+ agent.tool_allowlist_json
358
+ ? expandToolAllowlist(
359
+ JSON.parse(agent.tool_allowlist_json),
360
+ nativeTools.map((tool) => tool.name),
361
+ )
362
+ : agent.tools_json
363
+ ? JSON.parse(agent.tools_json)
364
+ : [],
365
+ )
366
+ filteredNativeTools = nativeTools.filter((tool) => allowedNames.has(tool.name))
367
+ allTools = [...filteredNativeTools, ...mcpToolExecutors]
368
+ }
313
369
 
314
370
  const nativeToolsForLLM: LLMToolDef[] = filteredNativeTools.map(t => ({
315
371
  type: "function" as const,
@@ -320,10 +376,31 @@ export async function compileContext(opts: {
320
376
  },
321
377
  }))
322
378
 
323
- const toolsForLLM: LLMToolDef[] = nativeToolsForLLM
379
+ let toolsForLLM: LLMToolDef[] = nativeToolsForLLM
380
+ // Workers receive MCP tools directly only when prepareDelegation has
381
+ // activated a persistent assignment (or the verifier's internal readback
382
+ // scope). The coordinator keeps every enabled MCP executor discoverable,
383
+ // but out of its initial prompt.
384
+ if (!canDiscoverAllMcp && mcpToolExecutors.length > 0) {
385
+ toolsForLLM = [
386
+ ...toolsForLLM,
387
+ ...mcpToolExecutors.map((tool) => ({
388
+ type: "function" as const,
389
+ function: {
390
+ name: tool.name,
391
+ description: tool.description,
392
+ parameters: tool.parameters,
393
+ },
394
+ })),
395
+ ]
396
+ }
324
397
 
325
398
  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)`)
399
+ log.info(
400
+ canDiscoverAllMcp
401
+ ? `[context-compiler] [STEP-4b] MCP tools discoverable by coordinator: ${mcpToolExecutors.length}`
402
+ : `[context-compiler] [STEP-4b] MCP tools assigned directly to worker: ${mcpToolExecutors.length}`,
403
+ )
327
404
  log.info(`[context-compiler] [STEP-8] ✅ Combined tools: ${allTools.length} total executors, ${toolsForLLM.length} in LLM context`)
328
405
 
329
406
  // [STEP-8b] STRATEGY 2: SELECT — Skill Loadout (minimal + discovered)
@@ -347,6 +424,13 @@ export async function compileContext(opts: {
347
424
  discoveredSkills = await selectSkills(textMessage)
348
425
  log.info(`[context-compiler] [STEP-8b] ✅ Discovered ${discoveredSkills.length} additional skills via HiveDB`)
349
426
  }
427
+ if (isCatalogAgent && agent.skills_json) {
428
+ for (const skillId of JSON.parse(agent.skills_json) as string[]) {
429
+ const forced = await getSkillByName(skillId)
430
+ if (forced) discoveredSkills.push(forced)
431
+ }
432
+ log.info(`[context-compiler] [STEP-8b] ✅ Loaded ${discoveredSkills.length} catalog agent skills`)
433
+ }
350
434
  } catch (err) {
351
435
  log.warn(`[context-compiler] [STEP-8b] ⚠️ Skill loadout failed: ${(err as Error).message}`)
352
436
  }
@@ -383,24 +467,35 @@ export async function compileContext(opts: {
383
467
  throw err
384
468
  }
385
469
 
386
- const totalTokens = recentMessages.reduce((sum, m) => sum + estimateTokens(m.content), 0)
470
+ // A summary applies when it covers messages that fell out of the current
471
+ // window — i.e. the window's earliest message is strictly after the last
472
+ // message the summary covers. (Comparing window tokens against a
473
+ // context-window-sized threshold, as before, almost never fires: the
474
+ // window is capped at KEEP_LAST_N_MESSAGES messages, which rarely
475
+ // approaches 80% of the context window on its own — so the summary was
476
+ // computed, stored, and the user notified, but never actually reached the
477
+ // model.)
478
+ const summaryApplies = !!(
479
+ summary && summary.last_message_id > 0 &&
480
+ (recentMessages.length === 0 || recentMessages[0].id > summary.last_message_id)
481
+ )
387
482
 
388
- let messages: LLMMessage[]
483
+ const conversationSummarySection = summaryApplies
484
+ ? `\n\n# RESUMEN DE LA CONVERSACIÓN (turnos anteriores, compactados)\n${summary!.summary.slice(0, SUMMARY_MAX_CHARS)}\n`
485
+ : ""
389
486
 
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)
487
+ if (summaryApplies) {
488
+ log.info(`[context-compiler] [STEP-9c] Summary applies (${summary!.messages_covered} messages compressed) — folded into system prompt`)
402
489
  }
403
490
 
491
+ // Never a second "system" turn here — every provider (Gemini, Anthropic,
492
+ // OpenAI-compat) hoists ALL role:"system" messages into a single top-level
493
+ // system instruction, so a second one either gets silently merged (fine)
494
+ // or — on a context-overflow retry that keeps only the LAST system message
495
+ // (openai-compat-base.ts) — silently replaces the real prompt. The summary
496
+ // lives in `systemPrompt` instead (see conversationSummarySection below).
497
+ const messages: LLMMessage[] = toAPIMessages(recentMessages)
498
+
404
499
  // [STEP-10] STRATEGY 4: ISOLATE — Build context based on agent role
405
500
  log.info(`[context-compiler] [STEP-10] Building system prompt...`)
406
501
  let systemPrompt: string
@@ -423,6 +518,34 @@ export async function compileContext(opts: {
423
518
  systemPrompt += `\n\n# ENTORNO ACTUAL\n**Fecha**: ${fecha}\n**Hora**: ${hora}\n**Zona horaria**: ${userTimezone}${workspaceLine}\n`
424
519
  log.info(`[context-compiler] [STEP-10b] ✅ Injected current date/time: ${fecha} ${hora} (${userTimezone})`)
425
520
 
521
+ // Placed early (right after ENTORNO ACTUAL), not appended at the end: the
522
+ // truncation guard below cuts the system prompt's TAIL when it's over
523
+ // budget, so a summary appended last would be the first thing silently
524
+ // dropped on an oversized prompt.
525
+ systemPrompt += conversationSummarySection
526
+
527
+ // Only the live roster goes here — how to delegate, fan-out/fan-in and the
528
+ // execution-truth rules are static doctrine and live in the coordinator's
529
+ // stored prompt (storage/onboarding.ts), not duplicated per turn.
530
+ if (!isWorker) {
531
+ const routingCatalog = renderAgentRoutingCatalog(await listCatalogAgents())
532
+ systemPrompt += `\n\n# COLMENA DE AGENTES\nWorkers disponibles ahora mismo (globales del sistema, ya existen):\n\n${routingCatalog}\n`
533
+ }
534
+
535
+ const playbookInput = taskContext || userMessage
536
+ const playbookText = typeof playbookInput === "string"
537
+ ? playbookInput
538
+ : Array.isArray(playbookInput)
539
+ ? playbookInput.filter((part) => part.type === "text").map((part) => (part as any).text).join("\n")
540
+ : String(playbookInput)
541
+ const playbookRules = (await selectPlaybookRules(playbookText)).filter((rule) => {
542
+ if (!rule.applicable_to || !rule.applicable_to.includes("agent:")) return true
543
+ return isCatalogAgent ? rule.applicable_to.includes(`agent:${agent.id}`) : false
544
+ })
545
+ if (playbookRules.length > 0) {
546
+ systemPrompt += `\n\n# PLAYBOOK APRENDIDO\n${playbookRules.map((rule) => `- ${rule.rule}`).join("\n")}\n`
547
+ }
548
+
426
549
  // Inject scratchpad (Strategy: WRITE) — usando TOON para ahorro de tokens
427
550
  if (scratchpadNotes.length > 0) {
428
551
  const scratchpadData: Record<string, string> = {}
@@ -434,11 +557,11 @@ export async function compileContext(opts: {
434
557
  systemPrompt += `\n\n# SCRATCHPAD (Persistent Notes)\n${scratchpadContent}\n`
435
558
  }
436
559
 
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
560
+ // G9: causal context window (buildAgentContext) — only when the summary
561
+ // applies this turn (a real DB round-trip, not a per-turn cost) and
439
562
  // there's a causal stream to build it from. episodicSimilarity is omitted:
440
563
  // it requires embeddings hive doesn't generate anywhere yet.
441
- if (compactionFired && opts.causalStreamId && loadConfig().causalLog?.enabled) {
564
+ if (summaryApplies && opts.causalStreamId && loadConfig().causalLog?.enabled) {
442
565
  try {
443
566
  const causalDb = await getHiveDb()
444
567
  const objectiveSource = taskContext || userMessage
@@ -470,26 +593,22 @@ export async function compileContext(opts: {
470
593
  }
471
594
  }
472
595
 
473
- // Dynamic tool discovery instruction (coordinator only)
474
- // Note: MCP tools are already available directly, no search needed
596
+ // Coordinator only. Just the live loadout — how to use it is doctrine and
597
+ // lives in the stored prompt + the capability_discovery skill.
475
598
  if (!isWorker) {
476
- // Build minimal tools documentation from filtered native tools
477
599
  const minimalToolsDocs = filteredNativeTools
478
600
  .filter(t => MINIMAL_TOOLS.has(t.name))
479
601
  .map(t => `- **${t.name}**: ${t.description || "Herramienta nativa"}`)
480
602
  .join("\n")
481
603
 
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`
604
+ systemPrompt += `\n\n# HERRAMIENTAS SIEMPRE DISPONIBLES\n${minimalToolsDocs}\n`
487
605
 
488
606
 
489
607
  // Inject available skills (minimal + discovered)
490
608
  if (allSkills.length > 0) {
491
609
  // Minimal skills: inject full body (always-loaded instructions)
492
- const minimalWithBody = allSkills.filter(s => MINIMAL_SKILL_NAMES.includes(s.name) && s.body)
610
+ const minimalNames = new Set(minimalSkills.map(s => s.name))
611
+ const minimalWithBody = allSkills.filter(s => minimalNames.has(s.name) && s.body)
493
612
  if (minimalWithBody.length > 0) {
494
613
  let minimalSection = `\n\n# SKILLS SIEMPRE ACTIVAS\n`
495
614
  for (const skill of minimalWithBody) {
@@ -499,7 +618,7 @@ export async function compileContext(opts: {
499
618
  }
500
619
 
501
620
  // 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))
621
+ const discoveredOnly = allSkills.filter(s => !minimalNames.has(s.name))
503
622
  if (discoveredOnly.length > 0) {
504
623
  let discoveredSection = `\n\n# SKILLS DESCUBIERTAS (relevantes para esta tarea)\n`
505
624
  for (const skill of discoveredOnly) {
@@ -515,13 +634,15 @@ export async function compileContext(opts: {
515
634
  }
516
635
 
517
636
  // For isolated workers, add task context + tool discovery instruction
518
- if (isWorker && opts.taskContext) {
637
+ if (isWorker && opts.taskContext && !isCatalogAgent) {
519
638
  systemPrompt += `\n\n# HERRAMIENTAS DISPONIBLES\n` +
520
639
  `Arrancas con herramientas básicas. Si tu tarea requiere herramientas adicionales (web_search, fs_read, browser_navigate, etc.):\n` +
521
640
  `1. Usá \`search_knowledge(type="tools", query="<herramienta o tarea>")\` para encontrarlas.\n` +
522
641
  `2. Las herramientas que encuentres estarán disponibles para usar inmediatamente.\n` +
523
642
  `Si el coordinador te indicó herramientas específicas, buscalas primero con search_knowledge antes de ejecutar tu tarea.\n` +
524
643
  `\n# CURRENT TASK\n${opts.taskContext}\n\nFocus ONLY on this task. Do not deviate.`
644
+ } else if (isWorker && opts.taskContext) {
645
+ systemPrompt += `\n\n# CURRENT TASK\n${opts.taskContext}\n\nFocus ONLY on this task and return the required structured delivery.`
525
646
  }
526
647
 
527
648
  // Truncate system prompt only when it exceeds a model-aware budget.
@@ -552,6 +673,7 @@ export async function compileContext(opts: {
552
673
 
553
674
  return {
554
675
  systemPrompt,
676
+ conversationSummarySection,
555
677
  messages,
556
678
  tools: toolsForLLM,
557
679
  allTools,
@@ -561,7 +683,7 @@ export async function compileContext(opts: {
561
683
 
562
684
  // Re-export sync functions for gateway/initializer
563
685
  export {
564
- syncToolCatalogToFTS as syncToolsToFTS,
565
- syncSkillsToFTS,
566
- syncPlaybookToFTS,
686
+ syncToolCatalogToIndex as syncToolsToIndex,
687
+ syncSkillsToIndex,
688
+ syncPlaybookToIndex,
567
689
  }