@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
@@ -1,14 +1,21 @@
1
1
  /**
2
- * Agents Tools - 14 tools
3
- *
2
+ * Agents Tools - 15 tools
3
+ *
4
4
  * @category agents
5
5
  */
6
6
 
7
7
  import type { Tool } from "../types.ts";
8
8
  import { col, toIndexable, fromIndexable, BROADCAST } from "../../storage/hive.ts";
9
- import type { MemoryDoc, AgentDoc, ProviderDoc, ModelDoc, TaskDoc, AgentBusMessageDoc } from "../../storage/collections.ts";
9
+ import type { MemoryDoc, AgentDoc, ProviderDoc, ModelDoc, McpServerDoc, TaskDoc, AgentBusMessageDoc, AgentAcceptanceCriterion } from "../../storage/collections.ts";
10
+ import type { AcceptanceCriterion } from "../../agent/run-store.ts";
11
+ import type { PreparedDelegation } from "../../agent/delegation-runtime.ts";
10
12
  import { logger } from "../../utils/logger.ts";
11
13
  import { agentBus } from "../../events/agent-bus.ts";
14
+ import {
15
+ emitDelegationStarted,
16
+ emitDelegationFinished,
17
+ emitWorkEvent,
18
+ } from "../../canvas/emitter.ts";
12
19
 
13
20
  const log = logger.child("agents");
14
21
 
@@ -184,7 +191,7 @@ export const memoryDeleteTool: Tool = {
184
191
 
185
192
  export const agentCreateTool: Tool = {
186
193
  name: "agent_create",
187
- description: "Crear un nuevo agente worker especializado. Requiere consultar get_available_models primero para seleccionar provider/model óptimos. Sinónimos: crear agente, nuevo worker, nuevo trabajador",
194
+ description: "Crear un nuevo agente worker especializado. Requiere consultar get_available_models; para un especialista MCP confirmado por el usuario, acepta mcp_server_id. Sinónimos: crear agente, nuevo worker, nuevo trabajador",
188
195
  parameters: {
189
196
  type: "object",
190
197
  properties: {
@@ -194,6 +201,10 @@ export const agentCreateTool: Tool = {
194
201
  tools_json: { type: "array", description: "Lista de IDs de herramientas", items: { type: "string" } },
195
202
  providerId: { type: "string", description: "ID del provider (openai, anthropic, ollama, etc.) - Obtener de get_available_models" },
196
203
  modelId: { type: "string", description: "ID del modelo (gpt-4o, claude-sonnet, etc.) - Obtener de get_available_models" },
204
+ mcp_server_id: {
205
+ type: "string",
206
+ description: "Servidor MCP persistente para un especialista. Requiere confirmación previa del usuario y asigna todas las tools actuales y futuras de ese servidor.",
207
+ },
197
208
  tone: { type: "string", description: "Tono del agente (friendly, professional, direct, etc.)" },
198
209
  max_iterations: { type: "number", description: "Límite de iteraciones del agente (default: 10)" },
199
210
  },
@@ -208,6 +219,7 @@ export const agentCreateTool: Tool = {
208
219
  const toolsJson = params.tools_json ? JSON.stringify(params.tools_json) : null;
209
220
  const providerId = params.providerId as string;
210
221
  const modelId = params.modelId as string;
222
+ const mcpServerId = params.mcp_server_id as string | undefined;
211
223
  const tone = (params.tone as string) ?? "friendly";
212
224
  const maxIterations = (params.max_iterations as number) ?? 10;
213
225
  const parentWorkspace = config?.configurable?.workspace ?? null;
@@ -265,6 +277,42 @@ export const agentCreateTool: Tool = {
265
277
  };
266
278
  }
267
279
 
280
+ if (mcpServerId) {
281
+ if (!userId) {
282
+ return { ok: false, error: "No se puede asignar un servidor MCP sin contexto de usuario." };
283
+ }
284
+ const serverEntry = await (await col<McpServerDoc>("mcpServers")).get(mcpServerId);
285
+ if (!serverEntry?.doc.enabled) {
286
+ return { ok: false, error: `El servidor MCP '${mcpServerId}' no existe o está deshabilitado.` };
287
+ }
288
+ if (serverEntry.doc.user_id && serverEntry.doc.user_id !== userId) {
289
+ return { ok: false, error: `El servidor MCP '${mcpServerId}' pertenece a otro usuario.` };
290
+ }
291
+
292
+ const existingSpecialist = (await (await col<AgentDoc>("agents")).scan({}))
293
+ .map((entry) => entry.doc)
294
+ .find((agent) => {
295
+ if (agent.role !== "worker" || agent.user_id !== userId) return false;
296
+ try {
297
+ return agent.mcp_server_ids_json
298
+ ? (JSON.parse(agent.mcp_server_ids_json) as string[]).includes(mcpServerId)
299
+ : false;
300
+ } catch {
301
+ return false;
302
+ }
303
+ });
304
+ if (existingSpecialist) {
305
+ const action = existingSpecialist.enabled
306
+ ? "Reutilizalo con task_delegate."
307
+ : "Está deshabilitado; el usuario debe reactivarlo desde Agentes.";
308
+ return {
309
+ ok: false,
310
+ existingAgentId: existingSpecialist.id,
311
+ error: `Ya existe el especialista '${existingSpecialist.name}' para ese servidor. ${action}`,
312
+ };
313
+ }
314
+ }
315
+
268
316
  try {
269
317
  const agentId = crypto.randomUUID().replace(/-/g, "").slice(0, 16);
270
318
  const now = Date.now();
@@ -272,7 +320,7 @@ export const agentCreateTool: Tool = {
272
320
  const agentsCol = await col<AgentDoc>("agents");
273
321
  await agentsCol.put(agentId, {
274
322
  id: agentId,
275
- user_id: userId,
323
+ user_id: userId ?? "",
276
324
  name,
277
325
  description,
278
326
  system_prompt: systemPrompt,
@@ -284,12 +332,15 @@ export const agentCreateTool: Tool = {
284
332
  model_id: toIndexable(modelId),
285
333
  tools_json: toolsJson,
286
334
  skills_json: null,
335
+ active_mcp_json: null,
287
336
  parent_id: toIndexable(parentId),
288
337
  max_iterations: maxIterations,
289
338
  workspace: parentWorkspace,
290
339
  lastTraceAt: null,
291
340
  created_at: now,
292
341
  updated_at: now,
342
+ source: "user",
343
+ mcp_server_ids_json: mcpServerId ? JSON.stringify([mcpServerId]) : null,
293
344
  }, { expectedVersion: 0 });
294
345
 
295
346
  return {
@@ -298,6 +349,7 @@ export const agentCreateTool: Tool = {
298
349
  name,
299
350
  providerId,
300
351
  modelId,
352
+ mcpServerId: mcpServerId ?? null,
301
353
  workspace: parentWorkspace,
302
354
  message: "Agente creado exitosamente."
303
355
  };
@@ -311,46 +363,81 @@ export const agentCreateTool: Tool = {
311
363
 
312
364
  export const agentFindTool: Tool = {
313
365
  name: "agent_find",
314
- description: "Find existing running or idle worker agents. Spanish: buscar agente, encontrar worker, localizar agente",
366
+ description: "Discover available worker agents. Includes global system catalog agents plus private workers owned by the current user. This tool does not report task execution; use task_list/task_status for that. Spanish: buscar agente, encontrar worker, localizar agente",
315
367
  parameters: {
316
368
  type: "object",
317
369
  properties: {
318
370
  search: { type: "string", description: "Search term for agent name or description" },
319
- status: { type: "string", enum: ["idle", "active", "any"], description: "Filter by status" },
371
+ availability: { type: "string", enum: ["enabled", "disabled", "any"], description: "Filter by whether the worker can accept tasks" },
372
+ status: { type: "string", enum: ["idle", "active", "any"], description: "Deprecated compatibility alias. It does not represent task execution; use task_list." },
320
373
  },
321
374
  },
322
375
  execute: async (params: Record<string, unknown>, config?: any) => {
323
376
  const userId = config?.configurable?.user_id;
324
377
  const search = params.search as string | undefined;
325
- const status = params.status as string | undefined;
378
+ const legacyStatus = params.status as string | undefined;
379
+ const availability = (params.availability as string | undefined)
380
+ ?? (legacyStatus === "any" ? "any" : legacyStatus ? "enabled" : "any");
326
381
 
327
382
  try {
328
383
  const agentsCol = await col<AgentDoc>("agents");
384
+ const mcpServersCol = await col<McpServerDoc>("mcpServers");
385
+ const serverNames = new Map(
386
+ (await mcpServersCol.scan({})).map((entry) => [entry.doc.id, entry.doc.name]),
387
+ );
329
388
  let agents = (await agentsCol.scan({}))
330
389
  .map(e => e.doc)
331
- .filter(a => a.user_id === userId && a.role === "worker");
390
+ .filter(a =>
391
+ a.role === "worker"
392
+ && (a.source === "catalog" || (!!userId && a.user_id === userId))
393
+ );
332
394
 
333
395
  if (search) {
334
396
  const needle = search.toLowerCase();
335
- agents = agents.filter(a =>
336
- a.name.toLowerCase().includes(needle) || (a.description ?? "").toLowerCase().includes(needle)
337
- );
397
+ agents = agents.filter((a) => {
398
+ let assignedServerIds: string[] = [];
399
+ try {
400
+ assignedServerIds = a.mcp_server_ids_json ? JSON.parse(a.mcp_server_ids_json) : [];
401
+ } catch {
402
+ assignedServerIds = [];
403
+ }
404
+ return a.name.toLowerCase().includes(needle)
405
+ || (a.description ?? "").toLowerCase().includes(needle)
406
+ || assignedServerIds.some((id) =>
407
+ id.toLowerCase().includes(needle)
408
+ || (serverNames.get(id) ?? "").toLowerCase().includes(needle),
409
+ );
410
+ });
338
411
  }
339
412
 
340
- if (status && status !== "any") {
341
- agents = agents.filter(a => a.status === status);
413
+ if (availability !== "any") {
414
+ agents = agents.filter(a => availability === "enabled" ? a.enabled : !a.enabled);
342
415
  }
343
416
 
344
417
  return {
345
418
  ok: true,
346
419
  count: agents.length,
347
- agents: agents.map((a) => ({
348
- id: a.id,
349
- name: a.name,
350
- description: a.description,
351
- role: a.role,
352
- status: a.status,
353
- })),
420
+ execution_source: "Use task_list or task_status for real execution state.",
421
+ ...(legacyStatus ? { warning: "The status filter is deprecated and cannot prove whether a task is running." } : {}),
422
+ agents: agents.map((a) => {
423
+ let mcpServerIds: string[] = [];
424
+ try {
425
+ mcpServerIds = a.mcp_server_ids_json ? JSON.parse(a.mcp_server_ids_json) : [];
426
+ } catch {
427
+ mcpServerIds = [];
428
+ }
429
+ return {
430
+ id: a.id,
431
+ name: a.name,
432
+ description: a.description,
433
+ role: a.role,
434
+ source: a.source ?? "user",
435
+ enabled: a.enabled,
436
+ availability: a.enabled ? "enabled" : "disabled",
437
+ mcpServerIds,
438
+ mcpServers: mcpServerIds.map((id) => ({ id, name: serverNames.get(id) ?? id })),
439
+ };
440
+ }),
354
441
  };
355
442
  } catch (error) {
356
443
  return { ok: false, error: `Failed to find agents: ${(error as Error).message}` };
@@ -362,11 +449,11 @@ export const agentFindTool: Tool = {
362
449
 
363
450
  export const agentArchiveTool: Tool = {
364
451
  name: "agent_archive",
365
- description: "Archive or terminate a worker agent. Spanish: archivar agente, terminar worker, desactivar agente",
452
+ description: "Archive or terminate a worker you created. Catalog agents cannot be archived — only the user can disable those from the UI. Spanish: archivar agente, terminar worker",
366
453
  parameters: {
367
454
  type: "object",
368
455
  properties: {
369
- agentId: { type: "string", description: "ID of the agent to archive" },
456
+ agentId: { type: "string", description: "ID of the worker to archive (not a catalog agent)" },
370
457
  },
371
458
  required: ["agentId"],
372
459
  },
@@ -381,7 +468,16 @@ export const agentArchiveTool: Tool = {
381
468
  return { ok: false, error: `Agent not found: ${agentId}` };
382
469
  }
383
470
 
384
- await agentsCol.put(agentId, { ...existing.doc, enabled: false, updated_at: Date.now() }, { expectedVersion: existing.version });
471
+ // Catalog personas are shared capabilities of the whole hive — turning
472
+ // one off is the user's call, from the UI, never an agent's.
473
+ if (existing.doc.source === "catalog") {
474
+ return {
475
+ ok: false,
476
+ error: `'${existing.doc.name}' is a catalog agent and stays available. Only the user can disable it from the Agents UI.`,
477
+ };
478
+ }
479
+
480
+ await agentsCol.put(agentId, { ...existing.doc, enabled: false, status: "archived", updated_at: Date.now() }, { expectedVersion: existing.version });
385
481
 
386
482
  return { ok: true, agentId, message: "Agent archived." };
387
483
  } catch (error) {
@@ -394,38 +490,70 @@ export const agentArchiveTool: Tool = {
394
490
 
395
491
  export const taskDelegateTool: Tool = {
396
492
  name: "task_delegate",
397
- description: "Delegate a task to a worker agent. mode=sync (default) blocks until done; mode=async enqueues and returns immediately. Spanish: delegar tarea, asignar worker, ejecutar por agente, delegate_task",
493
+ description: "Delegate a bounded task to an existing worker_id (any `agents` row: catalog-seeded or agent_create-made). The delivery goes through deterministic acceptance checks (no LLM); you judge anything they don't cover in your closing turn, and use task_revise to send it back with feedback if it doesn't meet its criteria. mode=sync blocks the conversation until done; mode=async enqueues and frees the conversation immediately — the user is notified automatically in this same chat when the worker finishes. Prefer async unless you expect the result in a few seconds.",
398
494
  parameters: {
399
495
  type: "object",
400
496
  properties: {
401
- worker_id: { type: "string", description: "ID of the worker agent" },
497
+ worker_id: { type: "string", description: "Target agent ID — from agent_find or the catalog agent list in the system prompt." },
402
498
  task_description: { type: "string", description: "Clear, detailed instructions for the worker" },
403
- mode: { type: "string", enum: ["sync", "async"], description: "sync (default, blocking 2min timeout) or async (enqueued, non-blocking)" },
499
+ acceptance: {
500
+ type: "array",
501
+ description: "Verifiable acceptance criteria. The worker's default criteria are used when omitted.",
502
+ items: {
503
+ type: "object",
504
+ properties: {
505
+ id: { type: "string" },
506
+ description: { type: "string" },
507
+ checkTool: { type: "string" },
508
+ },
509
+ required: ["id", "description"],
510
+ },
511
+ },
512
+ mode: { type: "string", enum: ["sync", "async"], description: "sync (default, blocking, 2min timeout — only for very short delegations) or async (enqueued, frees the conversation instantly; outcome is relayed back to the user automatically). Prefer async for anything non-trivial." },
404
513
  },
405
- required: ["worker_id", "task_description"],
514
+ required: ["task_description"],
406
515
  },
407
516
  execute: async (params: Record<string, unknown>, config?: any) => {
408
- const workerId = params.worker_id as string;
517
+ const agentId = params.worker_id as string | undefined;
409
518
  const taskDescription = params.task_description as string;
410
519
  const mode = (params.mode as string) ?? "sync";
520
+ const turnId = config?.configurable?.turn_id as string | undefined;
411
521
 
412
- const agentsCol = await col<AgentDoc>("agents");
413
- const workerEntry = await agentsCol.get(workerId);
522
+ if (!agentId) return { ok: false, error: "Provide worker_id." };
414
523
 
415
- if (!workerEntry) {
416
- return { ok: false, error: `Worker not found: ${workerId}` };
524
+ const agentsCol = await col<AgentDoc>("agents");
525
+ const parentAgentId = config?.configurable?.agent_id ?? "";
526
+ if (!parentAgentId) {
527
+ return { ok: false, error: "Delegation caller identity is missing (config.configurable.agent_id). The coordinator may exist, but its ID was not propagated to task_delegate." };
417
528
  }
529
+ const parentEntry = await agentsCol.get(parentAgentId);
530
+ if (!parentEntry) return { ok: false, error: `Delegation caller agent not found: ${parentAgentId}` };
531
+ if (!parentEntry.doc.enabled) return { ok: false, error: `Delegation caller agent is disabled: ${parentAgentId}` };
532
+ const parent = parentEntry.doc;
533
+ const parentProviderId = fromIndexable(parent.provider_id);
534
+ const parentModelId = fromIndexable(parent.model_id);
535
+
536
+ const workerEntry = await agentsCol.get(agentId);
537
+ if (!workerEntry) return { ok: false, error: `Agent not found: ${agentId}` };
418
538
  const worker = workerEntry.doc;
419
- if (!worker.enabled) {
420
- return { ok: false, error: `Worker is disabled: ${worker.name}` };
421
- }
539
+ if (!worker.enabled) return { ok: false, error: `Agent is disabled: ${worker.name}` };
422
540
 
423
541
  const taskName = taskDescription.slice(0, 60);
542
+ const defaultAcceptance: AgentAcceptanceCriterion[] | null = worker.default_acceptance_json
543
+ ? JSON.parse(worker.default_acceptance_json)
544
+ : null;
545
+ const acceptance = ((params.acceptance as AcceptanceCriterion[] | undefined)
546
+ ?? defaultAcceptance?.map((criterion) => ({
547
+ id: criterion.id,
548
+ description: criterion.description,
549
+ checkTool: criterion.check_tool,
550
+ }))
551
+ ?? [{ id: "objective", description: taskDescription }]);
424
552
 
425
553
  // ── Async mode: create TaskDoc + enqueue worker_task in durable queue ──
426
554
  if (mode === "async") {
427
555
  try {
428
- const { nextId, toIndexable } = await import("../../storage/hive.ts");
556
+ const { nextId, toIndexable, updateDoc } = await import("../../storage/hive.ts");
429
557
  const { createRun } = await import("../../agent/run-store.ts");
430
558
  const { getDurableQueue } = await import("../../gateway/durable-queue.ts");
431
559
 
@@ -434,21 +562,19 @@ export const taskDelegateTool: Tool = {
434
562
  const tasksCol = await col<TaskDoc>("tasks");
435
563
  await tasksCol.put(taskId, {
436
564
  id: taskId,
437
- project_id: toIndexable(null),
438
- agent_id: toIndexable(workerId),
439
- parent_task_id: null,
565
+ agent_id: toIndexable(agentId),
440
566
  name: taskName,
441
567
  description: taskDescription,
442
568
  status: "pending",
443
569
  progress: 0,
444
- priority: 0,
445
- depends_on: null,
446
570
  result: null,
447
571
  error: null,
448
572
  metadata: null,
449
573
  job_id: null,
450
574
  run_id: null,
451
575
  thread_id: null,
576
+ delegation_group_id: turnId ?? null,
577
+ catalog_agent_id: toIndexable(worker.source === "catalog" ? agentId : null),
452
578
  started_at: null,
453
579
  attempts: 0,
454
580
  created_at: now,
@@ -456,14 +582,29 @@ export const taskDelegateTool: Tool = {
456
582
  completed_at: null,
457
583
  }, { expectedVersion: 0 });
458
584
 
585
+ if (turnId) {
586
+ const { registerDelegatedTask } = await import("../../gateway/delegation-groups.ts");
587
+ await registerDelegatedTask({
588
+ turnId,
589
+ taskId,
590
+ threadId: config?.configurable?.thread_id ?? "",
591
+ channel: config?.configurable?.channel,
592
+ userId: config?.configurable?.user_id,
593
+ sessionId: config?.configurable?.session_id,
594
+ coordinatorAgentId: parentAgentId,
595
+ });
596
+ }
597
+
459
598
  const run = await createRun({
460
- thread_id: `task-${taskId}-${workerId}`,
461
- agent_id: workerId,
599
+ thread_id: `task-${taskId}-${agentId}`,
600
+ agent_id: agentId,
462
601
  user_id: config?.configurable?.user_id ?? "",
463
602
  channel: config?.configurable?.channel ?? null,
464
603
  kind: "worker",
465
604
  max_iterations: worker.max_iterations || 10,
466
605
  resume_policy: "resume",
606
+ acceptance,
607
+ catalog_agent_id: worker.source === "catalog" ? agentId : undefined,
467
608
  });
468
609
 
469
610
  const queue = getDurableQueue();
@@ -472,101 +613,440 @@ export const taskDelegateTool: Tool = {
472
613
  type: "worker_task",
473
614
  run_id: run.id,
474
615
  payload: {
475
- workerId,
616
+ workerId: agentId,
476
617
  taskDescription,
477
618
  taskName,
478
619
  taskId,
620
+ acceptance,
621
+ parentAgentId,
622
+ parentProviderId,
623
+ parentModelId,
624
+ userId: config?.configurable?.user_id ?? "",
625
+ workspace: config?.configurable?.workspace ?? null,
626
+ // Delegating conversation's thread — lets delegation-notify.ts relay
627
+ // the outcome back to the user once this job reaches a terminal state.
628
+ originThreadId: config?.configurable?.thread_id ?? null,
629
+ originChannel: config?.configurable?.channel ?? null,
630
+ originSessionId: config?.configurable?.session_id ?? null,
631
+ turnId: turnId ?? null,
479
632
  },
480
633
  });
481
634
 
482
- await import("../../storage/hive.ts").then(({ updateDoc }) =>
483
- updateDoc<TaskDoc>("tasks", taskId, {
484
- job_id: job.id,
485
- run_id: run.id,
486
- thread_id: `task-${taskId}-${workerId}`,
487
- updated_at: Date.now(),
488
- } as Partial<TaskDoc>)
489
- );
490
-
491
- agentBus.notifyTaskStarted(workerId, worker.name, 0, taskName, "");
635
+ await updateDoc<TaskDoc>("tasks", taskId, {
636
+ job_id: job.id,
637
+ run_id: run.id,
638
+ thread_id: `task-${taskId}-${agentId}`,
639
+ updated_at: Date.now(),
640
+ } as Partial<TaskDoc>);
641
+
642
+ agentBus.notifyTaskStarted(agentId, worker.name, 0, taskName, "");
643
+ if (turnId) {
644
+ const { publishNarration } = await import("../../events/narration.ts");
645
+ await publishNarration({
646
+ turnId,
647
+ threadId: config?.configurable?.thread_id ?? "",
648
+ channel: config?.configurable?.channel,
649
+ userId: config?.configurable?.user_id,
650
+ sessionId: config?.configurable?.session_id,
651
+ agentId,
652
+ agentName: worker.name,
653
+ kind: "delegated",
654
+ status: "queued",
655
+ label: `Delegué “${taskName}” a ${worker.name}`,
656
+ dedupeKey: `delegated:${taskId}`,
657
+ });
658
+ }
492
659
 
493
660
  return {
494
661
  ok: true,
495
662
  task_id: taskId,
496
663
  job_id: job.id,
497
664
  run_id: run.id,
498
- worker_id: workerId,
665
+ worker_id: agentId,
499
666
  worker_name: worker.name,
500
667
  status: "queued",
501
- message: `Task enqueued (async). Use task_status with task_id="${taskId}" to check progress.`,
668
+ message: `Task enqueued (async). Use task_list for the queue or task_status with task_id="${taskId}" for this task.`,
502
669
  };
503
670
  } catch (err) {
504
671
  return { ok: false, error: `Async delegation failed: ${(err as Error).message}` };
505
672
  }
506
673
  }
507
674
 
508
- // ── Sync mode: blocking execution with 2min timeout (existing behavior) ──
509
- agentBus.notifyTaskStarted(workerId, worker.name, 0, taskName, "");
675
+ // ── Sync mode: blocking execution with 2min timeout ──
676
+ const { prepareDelegation } = await import("../../agent/delegation-runtime.ts");
677
+ const { getMCPManager } = await import("../../mcp/singleton.ts");
678
+ const mcpManager = getMCPManager();
510
679
 
511
- log.info(`[task_delegate] Delegating (sync) to ${worker.name} (${workerId})`);
680
+ let prepared: PreparedDelegation;
681
+ try {
682
+ prepared = await prepareDelegation(agentId, {
683
+ workspace: config?.configurable?.workspace ?? null,
684
+ parentProviderId,
685
+ parentModelId,
686
+ mcpManager,
687
+ });
688
+ } catch (err) {
689
+ return { ok: false, error: (err as Error).message };
690
+ }
691
+
692
+ agentBus.notifyTaskStarted(agentId, worker.name, 0, taskName, "");
693
+ log.info(`[task_delegate] Delegating (sync) to ${worker.name} (${agentId})`);
694
+ const syncDelegationRef = `sync-${Date.now()}-${agentId}`;
695
+ emitDelegationStarted({ workerId: agentId, parentAgentId, taskRef: syncDelegationRef, taskName });
512
696
 
513
697
  try {
514
- const { runAgentIsolated } = await import("../../agent/agent-loop.ts");
698
+ const { runAgentIsolated, withTimeout } = await import("../../agent/agent-loop.ts");
515
699
 
516
- const threadId = `task-${Date.now()}-${workerId}`;
700
+ const threadId = `task-${Date.now()}-${agentId}`;
517
701
  const SYNC_TIMEOUT_MS = 2 * 60 * 1000;
518
702
 
519
- const { withTimeout } = await import("../../agent/agent-loop.ts");
703
+ // Real cancellation (e.g. the user's "stop" button): the job's AbortSignal
704
+ // reaches us via config.signal (tool-runtime/index.ts's executeToolBatch),
705
+ // and runAgentIsolated/runAgent already honor it mid-run. withTimeout stays
706
+ // as a hard ceiling in case the signal path doesn't stop things in time.
707
+ const signal = config?.signal as AbortSignal | undefined;
520
708
  const result = await withTimeout(
521
709
  () => runAgentIsolated({
522
- agentId: workerId,
710
+ agentId,
523
711
  taskDescription,
524
712
  threadId,
713
+ mcpManager,
714
+ signal,
525
715
  }),
526
716
  SYNC_TIMEOUT_MS,
527
717
  );
528
718
 
529
- agentBus.notifyTaskCompleted(workerId, worker.name, 0, taskName, "", result);
530
-
719
+ agentBus.notifyTaskCompleted(agentId, worker.name, 0, taskName, "", result);
720
+
721
+ // Deterministic acceptance checks now always run, closing the old gap
722
+ // where a plain worker_id delegation (agent_create) skipped them
723
+ // entirely in sync mode. No LLM call: the calling agent (usually the
724
+ // coordinator) judges the delivery itself in this same tool response.
725
+ const { runAcceptanceChecks, recordAgentOutcome } = await import("../../agent/acceptance-checks.ts");
726
+ const checks = await runAcceptanceChecks({
727
+ objective: taskDescription,
728
+ acceptance,
729
+ delivery: result,
730
+ evidence: [result],
731
+ });
732
+ if (checks.status === "failed") {
733
+ await recordAgentOutcome(agentId, "harmful");
734
+ emitWorkEvent({
735
+ phase: "review_failed",
736
+ taskRef: syncDelegationRef,
737
+ taskName,
738
+ actorId: parentAgentId || agentId,
739
+ targetId: agentId,
740
+ detail: checks.summary,
741
+ });
742
+ return {
743
+ ok: false,
744
+ status: checks.status,
745
+ error: checks.summary,
746
+ };
747
+ }
748
+ await recordAgentOutcome(agentId, "helpful");
749
+ emitWorkEvent({
750
+ phase: "review_passed",
751
+ taskRef: syncDelegationRef,
752
+ taskName,
753
+ actorId: parentAgentId || agentId,
754
+ targetId: agentId,
755
+ });
756
+ emitWorkEvent({
757
+ phase: "completed",
758
+ taskRef: syncDelegationRef,
759
+ taskName,
760
+ actorId: agentId,
761
+ targetId: parentAgentId || null,
762
+ });
531
763
  return {
532
764
  ok: true,
533
- worker_id: workerId,
765
+ worker_id: agentId,
534
766
  worker_name: worker.name,
767
+ acceptance,
768
+ checks,
535
769
  result,
536
770
  };
537
771
  } catch (err) {
538
- agentBus.notifyTaskFailed(workerId, worker.name, 0, taskName, "", (err as Error).message);
772
+ const errorMessage = (err as Error).message;
773
+ const wasAborted = (config?.signal as AbortSignal | undefined)?.aborted === true;
774
+ agentBus.notifyTaskFailed(agentId, worker.name, 0, taskName, "", errorMessage);
775
+ emitWorkEvent({
776
+ phase: wasAborted ? "aborted" : "failed",
777
+ taskRef: syncDelegationRef,
778
+ taskName,
779
+ actorId: agentId,
780
+ targetId: parentAgentId || null,
781
+ detail: wasAborted ? "Trabajo interrumpido" : errorMessage,
782
+ });
539
783
 
540
784
  return {
541
785
  ok: false,
542
- worker_id: workerId,
543
- error: (err as Error).message,
786
+ worker_id: agentId,
787
+ error: errorMessage,
544
788
  };
789
+ } finally {
790
+ emitDelegationFinished({ workerId: agentId, taskRef: syncDelegationRef });
791
+ await prepared.release();
545
792
  }
546
793
  },
547
794
  };
548
795
 
549
- // ─── task_delegate_code ──────────────────────────────────────────────────────
796
+ // ─── task_revise ─────────────────────────────────────────────────────────────
550
797
 
551
- export const taskDelegateCodeTool: Tool = {
552
- name: "task_delegate_code",
553
- description: "Delegate a coding task to a CLI subagent (Qwen, Claude, etc.) via Code Bridge. Spanish: delegar código, subagente CLI, programación, Qwen",
798
+ const MAX_TASK_REVISIONS = 2;
799
+
800
+ export const taskReviseTool: Tool = {
801
+ name: "task_revise",
802
+ description: "Send a completed or blocked delegated task back to its worker with concrete feedback, instead of reporting it as done. The worker resumes on the SAME thread — it keeps its prior context, so the feedback only needs to describe what's missing. Use this when a delivery doesn't meet its acceptance criteria and you can't fix it yourself.",
554
803
  parameters: {
555
804
  type: "object",
556
805
  properties: {
557
- cli: { type: "string", enum: ["qwen", "claude", "opencode", "gemini"], description: "CLI tool to use" },
558
- task_instructions: { type: "string", description: "Coding task instructions" },
806
+ task_id: { type: "string", description: "The task_id from task_delegate's result." },
807
+ feedback: { type: "string", description: "Concrete, actionable feedback: what's wrong and what the worker still needs to do." },
808
+ acceptance: {
809
+ type: "array",
810
+ description: "Updated acceptance criteria, if they need to change. Defaults to the original task's criteria.",
811
+ items: {
812
+ type: "object",
813
+ properties: {
814
+ id: { type: "string" },
815
+ description: { type: "string" },
816
+ checkTool: { type: "string" },
817
+ },
818
+ required: ["id", "description"],
819
+ },
820
+ },
559
821
  },
560
- required: ["cli", "task_instructions"],
822
+ required: ["task_id", "feedback"],
561
823
  },
562
- execute: async (params: Record<string, unknown>) => {
563
- const cli = params.cli as string;
564
- const taskInstructions = params.task_instructions as string;
824
+ execute: async (params: Record<string, unknown>, config?: any) => {
825
+ const taskId = params.task_id as string | undefined;
826
+ const feedback = params.feedback as string | undefined;
827
+ if (!taskId) return { ok: false, error: "Provide task_id." };
828
+ if (!feedback || !feedback.trim()) return { ok: false, error: "Provide feedback describing what's missing." };
829
+
830
+ const parentAgentId = config?.configurable?.agent_id ?? "";
831
+ if (!parentAgentId) {
832
+ return { ok: false, error: "Caller identity is missing (config.configurable.agent_id)." };
833
+ }
834
+ const agentsCol = await col<AgentDoc>("agents");
835
+ const parentEntry = await agentsCol.get(parentAgentId);
836
+ if (!parentEntry) return { ok: false, error: `Caller agent not found: ${parentAgentId}` };
837
+ const parentProviderId = fromIndexable(parentEntry.doc.provider_id);
838
+ const parentModelId = fromIndexable(parentEntry.doc.model_id);
839
+
840
+ const tasksCol = await col<TaskDoc>("tasks");
841
+ const taskEntry = await tasksCol.get(taskId);
842
+ if (!taskEntry) return { ok: false, error: `Task not found: ${taskId}` };
843
+ const task = taskEntry.doc;
844
+ if (task.status !== "completed" && task.status !== "blocked") {
845
+ return { ok: false, error: `Task ${taskId} is "${task.status}" — only completed or blocked tasks can be revised.` };
846
+ }
847
+ if ((task.attempts ?? 0) >= MAX_TASK_REVISIONS) {
848
+ return { ok: false, error: `Task ${taskId} already used its ${MAX_TASK_REVISIONS} revision attempt(s). Fix it yourself or report the limit to the user.` };
849
+ }
850
+ if (!task.thread_id) {
851
+ return { ok: false, error: `Task ${taskId} has no thread_id — cannot resume its worker.` };
852
+ }
853
+
854
+ const agentId = fromIndexable(task.agent_id);
855
+ const workerEntry = agentId ? await agentsCol.get(agentId) : null;
856
+ if (!workerEntry) return { ok: false, error: `Worker not found for task ${taskId}: ${agentId}` };
857
+ const worker = workerEntry.doc;
858
+ if (!worker.enabled) return { ok: false, error: `Worker is disabled: ${worker.name}` };
859
+
860
+ const { createRun, getRun, deserializeAcceptance } = await import("../../agent/run-store.ts");
861
+ const { getDurableQueue } = await import("../../gateway/durable-queue.ts");
862
+ const { updateDoc } = await import("../../storage/hive.ts");
863
+
864
+ const previousRun = task.run_id ? await getRun(task.run_id) : null;
865
+ const previousAcceptance = previousRun ? deserializeAcceptance(previousRun) : null;
866
+ const acceptance = (params.acceptance as AcceptanceCriterion[] | undefined) ?? previousAcceptance ?? [{ id: "objective", description: task.description ?? feedback }];
867
+
868
+ try {
869
+ const run = await createRun({
870
+ thread_id: task.thread_id,
871
+ agent_id: agentId!,
872
+ user_id: config?.configurable?.user_id ?? "",
873
+ channel: config?.configurable?.channel ?? null,
874
+ kind: "worker",
875
+ max_iterations: worker.max_iterations || 10,
876
+ resume_policy: "resume",
877
+ acceptance,
878
+ catalog_agent_id: worker.source === "catalog" ? agentId! : undefined,
879
+ });
880
+
881
+ const turnId = config?.configurable?.turn_id as string | undefined;
882
+ if (turnId) {
883
+ const { registerDelegatedTask } = await import("../../gateway/delegation-groups.ts");
884
+ await registerDelegatedTask({
885
+ turnId,
886
+ taskId,
887
+ threadId: config?.configurable?.thread_id ?? "",
888
+ channel: config?.configurable?.channel,
889
+ userId: config?.configurable?.user_id,
890
+ sessionId: config?.configurable?.session_id,
891
+ coordinatorAgentId: parentAgentId,
892
+ });
893
+ }
894
+
895
+ const queue = getDurableQueue();
896
+ const job = await queue.enqueue({
897
+ lane: `task:${taskId}`,
898
+ type: "worker_task",
899
+ run_id: run.id,
900
+ payload: {
901
+ workerId: agentId,
902
+ taskDescription: `${task.description ?? ""}\n\nCORRECCIÓN SOLICITADA: ${feedback}`,
903
+ taskName: task.name,
904
+ taskId,
905
+ acceptance,
906
+ parentAgentId,
907
+ parentProviderId,
908
+ parentModelId,
909
+ userId: config?.configurable?.user_id ?? "",
910
+ workspace: config?.configurable?.workspace ?? null,
911
+ originThreadId: config?.configurable?.thread_id ?? null,
912
+ originChannel: config?.configurable?.channel ?? null,
913
+ originSessionId: config?.configurable?.session_id ?? null,
914
+ turnId: turnId ?? null,
915
+ revision: true,
916
+ },
917
+ });
918
+
919
+ await updateDoc<TaskDoc>("tasks", taskId, {
920
+ status: "pending",
921
+ error: null,
922
+ job_id: job.id,
923
+ run_id: run.id,
924
+ attempts: (task.attempts ?? 0) + 1,
925
+ delegation_group_id: turnId ?? task.delegation_group_id ?? null,
926
+ updated_at: Date.now(),
927
+ } as Partial<TaskDoc>);
928
+
929
+ const { recordAgentOutcome } = await import("../../agent/acceptance-checks.ts");
930
+ await recordAgentOutcome(agentId, "harmful");
931
+
932
+ emitWorkEvent({
933
+ phase: "review_failed",
934
+ taskRef: taskId,
935
+ taskName: task.name,
936
+ actorId: parentAgentId,
937
+ targetId: agentId!,
938
+ detail: feedback,
939
+ });
940
+
941
+ if (turnId) {
942
+ const { publishNarration } = await import("../../events/narration.ts");
943
+ await publishNarration({
944
+ turnId,
945
+ threadId: config?.configurable?.thread_id ?? "",
946
+ channel: config?.configurable?.channel,
947
+ userId: config?.configurable?.user_id,
948
+ sessionId: config?.configurable?.session_id,
949
+ agentId: agentId!,
950
+ agentName: worker.name,
951
+ kind: "delegated",
952
+ status: "queued",
953
+ label: `Devolví “${task.name}” a ${worker.name} con correcciones`,
954
+ dedupeKey: `revised:${taskId}:${(task.attempts ?? 0) + 1}`,
955
+ });
956
+ }
957
+
958
+ return {
959
+ ok: true,
960
+ task_id: taskId,
961
+ job_id: job.id,
962
+ run_id: run.id,
963
+ worker_id: agentId,
964
+ attempts: (task.attempts ?? 0) + 1,
965
+ status: "queued",
966
+ message: `Revision enqueued (async). Use task_status with task_id="${taskId}" to check it.`,
967
+ };
968
+ } catch (err) {
969
+ return { ok: false, error: `Task revision failed: ${(err as Error).message}` };
970
+ }
971
+ },
972
+ };
565
973
 
566
- return {
567
- ok: false,
568
- error: `Code Bridge not implemented yet. CLI "${cli}" delegation is a stub. The task was not executed: "${taskInstructions.substring(0, 100)}..."`,
569
- };
974
+ // ─── task_list ──────────────────────────────────────────────────────────────
975
+
976
+ export const taskListTool: Tool = {
977
+ name: "task_list",
978
+ description: "List real delegated task executions for the current user. TaskDoc and JobDoc are the source of truth. Use this instead of agent_find to determine whether work is pending, running, completed, failed, or blocked.",
979
+ parameters: {
980
+ type: "object",
981
+ properties: {
982
+ status: {
983
+ type: "string",
984
+ enum: ["pending", "running", "completed", "failed", "blocked", "all"],
985
+ description: "Execution-state filter (default: all)",
986
+ },
987
+ worker_id: { type: "string", description: "Optional worker agent ID" },
988
+ limit: { type: "number", description: "Maximum tasks to return (default 20, maximum 100)" },
989
+ },
990
+ },
991
+ execute: async (params: Record<string, unknown>, config?: any) => {
992
+ const userId = config?.configurable?.user_id as string | undefined;
993
+ if (!userId) return { ok: false, error: "Missing user context for task_list." };
994
+
995
+ const status = (params.status as string | undefined) ?? "all";
996
+ const workerId = params.worker_id as string | undefined;
997
+ const limit = Math.max(1, Math.min(100, Number(params.limit) || 20));
998
+
999
+ try {
1000
+ const tasksCol = await col<TaskDoc>("tasks");
1001
+ const runsCol = await col<import("../../storage/collections.ts").AgentRunDoc>("agentRuns");
1002
+ const { getJob } = await import("../../gateway/job-store.ts");
1003
+ const allTasks = (await tasksCol.scan({}))
1004
+ .map((entry) => entry.doc)
1005
+ .sort((a, b) => b.updated_at - a.updated_at);
1006
+
1007
+ const result: Array<Record<string, unknown>> = [];
1008
+ for (const task of allTasks) {
1009
+ if (result.length >= limit) break;
1010
+ if (workerId && fromIndexable(task.agent_id) !== workerId) continue;
1011
+
1012
+ const run = task.run_id ? await runsCol.get(task.run_id) : null;
1013
+ if (!run || run.doc.user_id !== userId) continue;
1014
+
1015
+ const job = task.job_id ? await getJob(task.job_id) : null;
1016
+ const executionState =
1017
+ task.status === "pending"
1018
+ ? "pending"
1019
+ : task.status === "in_progress"
1020
+ ? "running"
1021
+ : task.status;
1022
+ if (status !== "all" && executionState !== status) continue;
1023
+
1024
+ result.push({
1025
+ id: task.id,
1026
+ name: task.name,
1027
+ description: task.description,
1028
+ worker_id: fromIndexable(task.agent_id),
1029
+ status: task.status,
1030
+ execution_state: executionState,
1031
+ progress: task.progress,
1032
+ result: task.result,
1033
+ error: task.error,
1034
+ job_id: task.job_id,
1035
+ job_status: job?.status ?? null,
1036
+ run_id: task.run_id,
1037
+ run_status: run.doc.status,
1038
+ attempts: task.attempts ?? 0,
1039
+ created_at: task.created_at,
1040
+ started_at: task.started_at,
1041
+ updated_at: task.updated_at,
1042
+ completed_at: task.completed_at,
1043
+ });
1044
+ }
1045
+
1046
+ return { ok: true, task_count: result.length, tasks: result };
1047
+ } catch (error) {
1048
+ return { ok: false, error: `Failed to list delegated tasks: ${(error as Error).message}` };
1049
+ }
570
1050
  },
571
1051
  };
572
1052
 
@@ -735,7 +1215,8 @@ export function createTools(): Tool[] {
735
1215
  agentFindTool,
736
1216
  agentArchiveTool,
737
1217
  taskDelegateTool,
738
- taskDelegateCodeTool,
1218
+ taskReviseTool,
1219
+ taskListTool,
739
1220
  taskStatusTool,
740
1221
  busPublishTool,
741
1222
  busReadTool,